How to Set Up the 301 Redirect in a Next.js App

When switching from an old website URL to a new one, 301 redirection is necessary. Here in this article, we will set up a 301 redirect in a Next.js app.

In React, we need to use third-party packages for redirection. Because Next.js is a framework, it is pre-bundled with the redirection feature.

Let us see a basic example of a 301 redirect. In my blog Techomoro, I have enabled a 301 redirection from my old URL to the new one that I have mentioned below.

// Old URL

https://techomoro.com/how-to-install-and-set-up-angular-8-on-ubuntu-19-04/
// New URL

https://www.techomoro.com/install-and-set-up-angular-on-ubuntu/

We can see the URL I typed on the browser and the final URL in the below GIF.

What is the importance of a 301 redirect?

A 301 redirect implicates a permanent change from one URL to another. This means that when a user accesses an old URL will be redirected to the new one.

One of the advantages of 301 redirects is that the new URL will get all the ranks and backlinks of the old URL.

301 redirection is used when a page is moved or removed from a website.

How to set up a 301 redirect in Next.js

In Next.js, we can list all the redirections inside the next.config.js file.

Assume that the old path is /old-contact-page and the new path is /new-contact-page. Then the redirection code will be coded like below.

adding the attribute permanent: true will make the redirection a status code of 301.

module.exports = {
  async redirects() {
    return [
      {
        source: '/old-contact-page',
        destination: '/new-contact-page',
        permanent: true,
      },
    ]
  },
}

Passing query to the destination Path

We can also pass the old path query values to the new destination path.

{
  source: '/old-blog/:path*',
  destination: '/blog/:path*',
  permanent: false
}

When /old-blog/post-1?user=john is requested, the user will be redirected to /blog/post-1?user=john.

Path matching

If we have the slug or id or any values, that changes in our URL we can match the paths and redirect from the old path to the new path.

For example, if we have written a redirection code from /old-blog/:slug to /new-blog/:slug, the change in slug will now affect the redirection.

That means, the path /old-blog/post-1 will redirect to the new path /new-blog/post-1.

module.exports = {
  async redirects() {
    return [
      {
        source: '/old-blog/:slug',
        destination: '/new-blog/:slug',
        permanent: true,
      },
    ]
  },
}

More redirections such as with i18n support are listed on the official Next.js page. You have to refer it.

Summary

Here in this article, we have discussed what is 301 redirect, its importance, and the method to set up 301 redirect in a Next.js app.

Be the first to reply

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.