How to change the base path in nextjs?
How to change the base path in nextjs?

Nextjs

How to change the base path in nextjs?

Understand the base path configuration in nextjs in easy ways.

FrontEnd web
Published in
2 min readJun 22, 2022

--

You can change the base path in nextjs. The base path help distribute the nextjs app on a different subdomain.

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true, basePath: '/blog',}module.exports = nextConfig

Now your application serves on http://localhost:3000/blog.

If you access your application on http://localhost:3000, you face a 404 error.

How to use the nextjs base path in-app?

Link

In next/link component, nextjs automatically generate a path with a combined base path + /about and your base is http://localhost:3000/blog/about

<Link href="/page"><a>about</a></Link>

Image

Now access your public folder image with /blog in your project.

<Image   width={724}   height={324}   objectFit="cover"   src="/blog/vercel.svg"   alt="vercel logo "/>

In nextjs, your images are in the asset folder; you cannot access an image with a base path. You import images and use them.

import heavyrain from '../Images/heavy-rain.jpg'export default function Home() {return (     <Image         width={724}         height={324}         objectFit="cover"         src={heavyrain}         alt="vercel logo "    />  )}

useRouter Hook

In nextjs, you use the useRouter hook in the component—useRouter hook return basepath. No difference in the useRouter hook functionality with the base path.it

let router= useRouter()console.log(router.basePath,' router ');

Conclusion

Base path configuration working for mono repo architecture. Mono repo means you deploy multiple nextjs projects on one domain.

An excellent example of Base path configuration for next. The Ecommerce and blog website.

  1. https://yourdomain.com/blog
  2. https://yourdomain.com/store

In the example are one domain and two different nextjs applications.

You can follow and read more articles on officialrajdeepsingh.dev and tag them on Twitter.

Read More content on Nextjs. Sign up for a free newsletter and join the nextjs community on medium.

--

--

Rajdeep Singh
FrontEnd web

JavaScript | TypeScript | Reactjs | Nextjs | Rust | Biotechnology | Bioinformatic | Frontend Developer | Author | https://linktr.ee/officialrajdeepsingh