How to easily change basePath - Next.js

Cover Image for How to easily change basePath - Next.js
Ali Bentaleb

It is possible to escape the default base path that next.js provides and prefix your pages by a prefix for all URL depending on your need.

In this tutorial, we will explain how to change base path and how you can redirect your clients to your new URL using the old URL with next.js redirects.

Install Next.js project

You need to install next.js project first if you do not have it using

npx create-next-app@latest my-app

You can learn more on how to setup your next.js project on this link

Edit next.config.js

In your config file next.config.js under the root directory, add base path to the config like the below

const nextConfig = {
	reactStrictMode: true,
	swcMinify: true,
	basePath: '/blog'
};

module.exports = nextConfig;

with this configuration , all pages will be served under /blog

script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7011429793744057" crossorigin="anonymous">

Test the configuration

Create page.js under pages folder and insert the following

export default function Page() {
	return <div>Hello</div>;
}

Now, run http://localhost:3000/blog/page and you should see your page displayed

nextjs baspath with blog

redirect files

Now, sometime you would like to keep some pages as they are so that user will not notice any difference, but you need to redirect those so they will be recognized by the system.

let’s see an example of how can we redirect a page

let’s change our config file like the below

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

	async redirects() {
		return [
			{
				source: '/page2',
				destination: '/blog/page2',
				permanent: true,
				basePath: false
			}
		];
	}
};

module.exports = nextConfig;

Next, let’s create page2 as below

Create page2.js under pages

export default function Page2() {
	return <div>Hello 2</div>;
}

Now, run http://localhost:3000/page2 and you should be able to see that the URL has been redirected to http://localhost:3000/blog/page2 and the page get resolved

 redirect in next.js with basepath

Conclusion

It is easy to use base path to use a specific basepath for our pages, and with next.js redirects, you can keep your old URLs and redirect them to the new locations .

How to use bootstrap table in ...How to easily use context prov...