Published on

How to do Redirection in Next.js

Authors

Redirection is a common use case in web development, whether you're making a small change to a URL or moving an entire blog to a new domain. If not done properly, it can cause problems such as broken links, lost SEO value, and a poor user experience.

For example, I recently made the decision to move all of my tech-related blog posts from AshikNesin.com to nesin.io. However, I did not handle the migration properly and some of my blog post URLs became broken.

In this article, let's see common methods to handle the redirections in Next.js

Method #1: Using next.config.js

If you know the specific URL you want to redirect to, using the next.config.js file is a simple and effective method. This is the approach that I currently use on my own site.

The next.config.js file allows you to specify redirect rules and configure other aspects of your Next.js application.

Here is how to handle it:

// next.config.js
module.exports = {
  async redirects() {
    return [
        // Simple url update
        {
            source: '/contact-me',
            destination: '/contact',
            permanent: true,
        },
        // Redirect /blog/* to example.com/blog/*
        {
            source: '/blog/:path*',
            destination: 'https://example.com/blog/:path*',
            permanent: true,
        }
    ]
  },
}
  • Destination URLs for redirects can be either internal or external resources.
  • Redirects can also be either permanent (HTTP status code 308) or temporary (HTTP status code 307)

Next.js uses 307/308 redirects to preserve the request method used. This is useful when redirecting users to a different URL that uses a different request method, such as a form submission. Using the correct request method can help ensure that redirects are handled smoothly and do not disrupt the user experience.

Method #2: Using getStaticProps or getServerSideProps

There may be cases where you need to retrieve data from a database or API before performing a redirect. This can be achieved by retrieving the data before performing the redirection.

For such case, we can use getStaticProps or getServerSideProps

Here is how to handle it:

// [id].js
export async function getServerSideProps(context) {
    const { id } = context.params;
    // let's assume that id = "twitter"
    const res = await fetch(`https://example.com/get-my-redirect-url/${id}`) 
    // returns {url: 'https://twitter.com/AshikNesin'}
    const data = await res.json()
    return {
        redirect: {
            destination: data.url,
            permanent: false,
        }
    }
    return {
        props: {}, // will be passed to the page component as props
    }
}

Happy Safe Redirection!

Reference