Nextjs
Published in

Nextjs

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

How to change the base path in nextjs?

Understand the base path configuration in nextjs with easy ways.

You can change the base path in nextjs. 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.

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

How to use the nextjs base path in-app?

In next/link component, nextjs automatic 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>

Now the 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 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 "    />  )}

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

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

Base path configuration working for monorepo architecture. monorepo 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 the Nextjs. Sign up for a free newsletter and join the nextjs community on medium.

Thanks for joining and visiting the nextjs publication

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store