How to create a Next.js redirect in 4 ways (with examples)

Published on September 20, 2024

Explaining (and using) Nextjs Redirects

Next.js redirects are an important function for any frontend application. Redirects take the user from one page to another, either automatically based on the URL or programmatic conditions, or based on a user action (for example, clicking a button). 

Implementing redirects correctly in Next.js apps ensures that applications are seamless and respond quickly to user input. Properly handling redirects also enhances your website’s SEO, ensuring that it doesn’t have dead links and that pages that have moved can be found so that search results are up to date.

This tutorial demonstrates the four ways that you can create a page redirect in Next.js (with full instructions and code examples) and explains when each method should be used.

Two options for Next.js redirects

Permanent vs. temporary redirects

There are two types of page redirects used on the web: permanent redirects and temporary redirects. Each type has a different purpose and behavior, and its own HTTP status code:

  • Permanent redirects: These have an HTTP status code of 301 or 308 that indicates a page has moved permanently. This redirect is cached by the web browser so that in the future, the user is sent immediately to the redirected page.

  • Temporary redirects: These have an HTTP status code of 302 or 307 that indicates a page has moved but will be returning to the current URL in the future. The page is redirected, but it is not cached in the browser so that it can be quickly reverted.

The 307 and 308 status codes differ from 301 and 302 codes in that they retain the original HTTP method of the initial request. Next.js redirects will return a 307 or 308 response by default. Here are the methods used to create permanent and temporary redirects in Next.js.

Method #1: Next.js redirects using the next.config.js file

You can define Next.js redirects in the next.config.js configuration file located in your project directory. These redirects apply to the entirety of your application and all users accessing it.

Create redirects in next.config.js by adding them to the return value of the redirects function exported by the module. You may also need to add the function itself if it doesn’t already exist in your project configuration.

The above code example shows several different ways to redirect. The first is a basic redirect from one page to another, the second redirects everything under the old_blog path to new_blog, and the third uses regex to do the same thing only if the post_id is numeric.

Adding Next.js redirects to the config is best for permanent redirects on the server side, where you need to inform search engines of a changed URL. Storing your redirects in this config file lets you keep all of your static (unchanging) redirects in one place. An example of when you might use this type of redirect is if you have a page that was created early in development that is later found to have a misspelled URL. In this case, you’d correct the URL and then create a permanent redirect in next.config.js to redirect the old URL. That way, links to the old mistyped URL still work.

If you’re just beginning your project with Next.js and want to start out on the right foot, you can check out our Next.js starter to get you up and running with a Contentful-powered Next.js app.

Method #2: Using redirect/permanentRedirect functions in Next.js App Router

The redirect and permanentRedirect functions in the Next.js App Router let you create redirects that occur after a specific action, rather than for a specific page or set of matching URLs that you define in the configuration.

This example Next.js redirect is done server side. Below, the redirect function is used to redirect back to the page after a comment has been left on a blog post:

The redirect function returns a temporary redirect with a 307 HTTP status code and is best for when you need to conditionally redirect based on a user action or other trigger, such as whether a user is logged in or has a specific role. 

Generally, temporary redirects created in this manner are used to manage your application flow rather than telling web browsers and search engines that a page has moved.  For example, if you send a permanent redirect to a success page after a form submission, you could break things for your users who try to use the form again, as they would be immediately redirected before filling it out.

The permanentRedirect function has the same syntax as the redirect function, but it returns a permanent 308 redirect. permanentRedirect can also be used for conditional redirects, but be aware that these will be cached by the browser and treated differently for SEO purposes, as explained later.

Method #3: Redirect Next.js using the NextResponse redirect method in middleware

Next.js middleware is code that runs before each incoming request to the server is completed. Redirects can be performed as part of a middleware’s logic, which is useful when performing redirects related to authentication, authorization, language, time, or location that can’t be done using basic URL pattern matching.

Below is an example of a Next.js redirect using middleware. The NextResponse interface is used to call the redirect method to change which page will be loaded next, implemented as a 307 temporary redirect.

In this example, access to the URLs under work_tools (as matched in the exported matcher config property) is restricted to hours after 9 a.m.

Using middleware for Next.js redirects is best for site-wide redirects where multiple conditions must be checked, for example, authentication and user roles. It is not intended for permanent redirects, as the conditions that get checked in middleware are not themselves permanent — authentication, permissions, user roles, and location will differ from user to user and change over time.

Method #4: Next.js redirect using useRouter/push

The Next.js useRouter hook redirects pages on the client side based on user actions. Calling the push method from the useRouter hook will send the user to a given path. In the example below, the user is redirected to a new page when they click a button:

This method of Next.js redirection should be used when a new page needs to load in response to a user action. As this action is taken on the client side, a HTTP status code is not produced by the server.

If you’re still using the old deprecated pages router, take a look at our App Router tutorial to learn about how the new Next.js router works.

Troubleshooting Next.js redirects

There are a few things you should check and consider if you’re centrally managing your Next.js redirects using the config or middleware:

  • Make sure they work! You don’t want your app experience to be compromised by dead links.

  • Use custom 404 pages instead of adding redirects for pages that no longer exist. Custom 404 pages help browsers and search engines know that the page has been removed and not relocated.

  • If you are doing a lot of redirects, use a redirect map stored in a database or JSON file to make them easier to manage and debug.

  • Check for conflicting paths or syntax errors, especially when pattern matching.

  • Avoid infinite redirect loops.

  • If you’re seeing an unexpected redirect, try clearing your web browser cache or testing in an incognito window.

If your Next.js redirect is part of your app flow and uses conditional logic using the redirect or push methods, you should investigate whether it’s possible to move them to the config or middleware, where they are more easily found and managed.

Next.js redirects best practices for SEO and performance

If your Next.js application includes public pages that you want to index and rank in search engines, you must make sure you are using the right kinds of redirects.

For SEO purposes, pages in your app should have unique URLs and not just load content dynamically without updating the current page address. Permanently redirected URLs will pass their SEO score on to the new page, which is good for maintaining SEO. Temporary redirects will not pass on their SEO score, making them suitable only for short-lived redirects like temporarily hiding a page while it is updated.

As for the performance of Next.js redirects, you shouldn’t bounce your users around too much. Each redirect requires reloading content, which will disrupt your users’ experience. To get the best performance for your Next.js apps, use a composable content platform to deliver optimized media from a high-speed CDN.

To see how Contentful can be used with Next.js, check out our blog starter templates.


Subscribe for updates

Build better digital experiences with Contentful updates direct to your inbox.

Related articles

Guides

Snake Charmer’s Secret: Metaprogramming the Python SDK

March 17, 2017

When companies need better ways to maintain a consistent digital experience across multiple web pages, apps and devices, design systems are the solution.
Guides

What is a design system?

June 20, 2023

This step-by-step tutorial shows you how to extend the capabilities of your Next.js blog to include live preview using the Contentful live preview SDK.
Guides

5 steps to elevate your Contentful and Next.js workflow with live preview

June 6, 2023

Contentful Logo 2.5 Dark

Ready to start building?

Put everything you learned into action. Create and publish your content with Contentful — no credit card required.

Get started