DEV Community

loading...

How to do a server side redirect in Next.js

creativesuraj profile image Suraj Sharma Originally published at surajsharma.net Updated on ・1 min read

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;
Enter fullscreen mode Exit fullscreen mode

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

export const getServerSideProps = async (context) => {
  const { res } =  context;
  res.writeHead(301, { location: "https://longurl.in/SMZqI" } );
  res.end();
}
Enter fullscreen mode Exit fullscreen mode

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 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.

Discussion (1)

pic
Editor guide
Collapse
tfantina profile image
Travis Fantina

I'm encountering some console errors:

Error: Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?
Enter fullscreen mode Exit fullscreen mode

But overall this functionality works. Thanks 👍️