How to do a 301 server side redirect in Next.js

Last updated on May 20, 2021 by Suraj Sharma



In this tutorial, you will learn how you can do a 301 redirect from one URL to another URL using the getServerProps() method in Next.


A 301(HTTP status code) redirect or a server side redirect, is a permanent redirect to a new URL, which is recommended for SEO and is the best method for implementing redirection in your website.


In my URL shortener app LongUrl.In, built using Next and TypeScript, I have used the 301 redirect to redirect from short urls to original long urls. Demo



301 redirect in Next.js


To do a server side redirect in Next,


First, create a server side rendering page component inside the /pages folder


 ./pages/[code].jsx

const RedirectURL = () => {
 return null;
}

export default RedirectURL;

Next, define and export the getServerSideProps function in the same file


export const getServerSideProps = async (context) => {
  const { res } =  context;
  res.writeHead(301, { location: "https://google.com" } );
  res.end();
}

The res.writeHead method sets the response header, the first argument is a 3-digit HTTP status code and the last argument is the response headers object.


the location property of the response headers object contains the destination URL.


The res.end() method signals to the server that all of the response headers and body have been sent. The res.end() method must be called on each response otherwise the response will never resolve or will result in the HTTP 502 error status code.



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.