Linguine Code

How to redirect on the server side with Next.JS

In a previous article, I discussed what and how getInitialProps() works in NextJS.

To do a quick recap, getInitialProps() is a function/method that lets you write server code before the page component in NextJS gets rendered.

In that function/method you can redirect a user to an internal or external URL via the server side.

Let’s take a quick look at a code snippet to see how this is done programatically.

Redirect user to a different domain on getInitialProps()

In the example above, I’m accessing getInitialProps() with the functional component type.

On line 1, I’m grabbing the res object that NextJS provides for us. This object is only available on the server side.

On line 4 to 7, I’m telling my NextJS application to send some new header information.

The first piece of information is that the status code will be a 301 (permanently moved). This status code can be any of the HTTP status codes that best suits your use case.

The second piece of information I’m modifying, is the Location. This is where you place the URL you want to redirect a user to.

To finish it off, I’m ending with a res.end() to let the application know to execute the changes.

Redirect a user via Zeit Now 2 configuration

If you’re using Zeit hosting platform, Now, you can also do this through their now.json configuration.

In the now configuration file, you’ll need to add a routes property.

In the example above I’m letting Zeit know to check for a specific pathname in my site, /kitties.

If it matches, perform a 301 redirect to my homepage.