Redirect Static Paths in NextJS

Thursday, February 16th 2023

Redirect Static Paths in NextJS

In Next.js, you can redirect static paths with parameters using getStaticPaths and getRedirects functions.

First, define the dynamic routes and their parameters in the getStaticPaths function of your page component, like this:

export async function getStaticPaths() { const paths = [ { params: { id: '1' } }, { params: { id: '2' } }, { params: { id: '3' } }, ]; return { paths, fallback: false }; }

This defines the dynamic paths with their respective parameters that you want to redirect. In this example, the path is /post/[id] where [id] is the parameter that can take on the values 1, 2, or 3.

Next, define the redirect rule in the getRedirects function, like this:

export async function getRedirects() { return [ { source: '/post/:id', destination: '/blog/:id', permanent: true, }, ]; }

This redirects any request made to the /post/ route to the /blog/ route. Here, is a parameter, which matches the value passed in the URL.

With this configuration, visiting the URL /post/1 will now redirect to /blog/1.

Note that the permanent option is set to true, which indicates that this is a permanent redirect.