Base Path

Version History

VersionChanges
v9.5.0Base Path added.

To deploy a Next.js application under a sub-path of a domain you can use the basePath config option.

basePath allows you to set a path prefix for the application. For example, to use /docs instead of / (the default), open next.config.js and add the basePath config:

  1. module.exports = {
  2. basePath: '/docs',
  3. }

Note: this value must be set at build time and can not be changed without re-building as the value is inlined in the client-side bundles.

When linking to other pages using next/link and next/router the basePath will be automatically applied.

For example, using /about will automatically become /docs/about when basePath is set to /docs.

  1. export default function HomePage() {
  2. return (
  3. <>
  4. <Link href="/about">
  5. <a>About Page</a>
  6. </Link>
  7. </>
  8. )
  9. }

Output html:

  1. <a href="/docs/about">About Page</a>

This makes sure that you don’t have to change all links in your application when changing the basePath value.

Images

When using the next/image component, you will need to add the basePath in front of src.

For example, using /docs/me.png will properly serve your image when basePath is set to /docs.

  1. import Image from 'next/image'
  2. function Home() {
  3. return (
  4. <>
  5. <h1>My Homepage</h1>
  6. <Image
  7. src="/docs/me.png"
  8. alt="Picture of the author"
  9. width={500}
  10. height={500}
  11. />
  12. <p>Welcome to my homepage!</p>
  13. </>
  14. )
  15. }
  16. export default Home