Redirecting pages with Next.JS

Created April 10, 2022

Use Cases

You might not want to create new pages but for some reason such as a page not being ready or even in a not so common scenario, you are fixing a security bug on the page and don't want users to use it yet.

With Next.JS you can successfully redirect your users to different pages from your homepage or from other pages.

In the solutions below, I am working on a personal project(with a blog) but I am not sure of the content that should be on the homepage. The project has a blog though so I thought why not start with that and send users to the blog page till I set up the homepage. So I discuss various options to use here and more.

Solution 1 - Using GetStaticProps or GetServerSideProps

This was the first solution that came to my mind when I was thinking of this problem. With getStaticProps and getServerSideProps, you can run a piece of logic on your page that basically runs either on the client or the server and with this we can successfully redirect the user to different pages. Example:

// using getStaticProps
export const getStaticProps = () => {
  return {
    redirect: {
      destination: "/blog",
      permanent: false, // make this true if you want the redirect to be cached by the search engines and clients forever
    },
  };
};

// redirect based on request header
// use the request from the context ({req})
export const getServerSideProps = ({req}) => {
  const userIsActive = req.headers['user'];
  
  if(userIsActive) {
    return {
      redirect: {
        destination: "/blog",
        permanent: false, // make this true if you want the redirect to be cached by the search engines and clients forever
      }, 
    }
  }

  // getServerSideProps still needs a default return if you do nothing at all
  return {
    props: {}
  }
} 

If you want to access the request data to get information such as request headers, query and cookie information then you will have to use getServerSideProps to allow you to get that information.

Solution 2 - Using redirect option in Next.JS config

Next.JS config allows you to redirect based on request pathnames, cookies and headers. To do this though, you will need to edit your next.config.js file. Restart your dev server to see the changes. Example:

// basic redirect
module.exports = {
  async redirects() {
    return [
      {
        source: '/',
        destination: '/blog',
        permanent: false, // make this true if you want the redirect to be cached by the search engines and clients forever
      },
    ]
  },
}

// redirect based on cookie information
// in this example, we already stored user device in a cookie 
// only direct android devices to blog page
module.exports = {
  async redirects() {
    return [
      {
        source: '/',
        has: [
          {
            type: 'cookie',
            key: 'device',
            value: 'android',
          },
        ],
        permanent: false,
        destination: '/blog',
      },
    ]
  },
}

Check out Next.JS redirects for more information

Solution 3 - Using Next.JS Middleware rewrites

In Next.JS 12, middlewares are a thing and you can basically use them to run logic before the page or your pages handles the request. You can return new responses such as a new page or an altogether different response.

export function middleware(req) {
 // to modify url, you need to clone it
  const url = req.nextUrl.clone();

  // Only rewrite requests to `/` to `/blog` as middleware is executed in every request of the app.
  if (url.pathname === "/") {
    // you could use this to get cookies or headers information in the middleware
    const authorization = req.headers['authorization'];
    const deviceCookie = req.cookies['device'];
    url.pathname = "/blog";
    // example, set a request query if you want
     url.searchParams.set(
        "user",
        "John Doe"
      );
     return NextResponse.redirect(url); 
     // you will be redirected to /blog?user=John+Doe
  }
}

Visit Next.JS middleware for more information.