Skip to content


Repository files navigation


Redirect to any URL in NextJS both in client and server


npm install nextjs-redirect


Let's say you want to create a page /donate that redirects the user to with a default value for the money. You create the page as you always do in NextJS (pages/donate.js) and then just use this component with the URL you want:

// pages/donate.js
import redirect from 'nextjs-redirect'
export default redirect('')

You can checkout this example live in

Status code (301, 302...)

By default, it will send a 301 status code. This can be customized by an optional parameter:

redirect('', { statusCode: 302 })

Client side dynamic routes (as)

When redirecting on the client side, if the redirected page is dynamic (pages/user/[userId]/info.js), the following redirect will trigger a page refresh:


In this case you can use the asUrl option to make a smooth transition between pages without any refresh:

redirect('/user/[userId]/info', { asUrl: '/user/42/info' })

Static export

This package is compatible with next export since version 4.0.0. See PR #4 for more details.

Custom UI component (HOC)

In case the navigation is happening client-side, you can use this package as a HOC to provide your custom components/styles for the UI:

import redirect from 'nextjs-redirect'

const Redirect = redirect('')

export default () => (
    <MyLayout>Redirecting to github!</MyLayout>

Redirect to URL from parameters

Let's say you have a single page called /redirect, and you wanna use it for all kinds of redirects:

  • /redirect?to=
  • /redirect?next=
  • /redirect?url=

Pretty cool huh!? You can do this with nextjs-redirect by passing the name of the parameter you want on the url. For the examples above:

// NOTE: These are 3 separate examples, you can only choose one name per page
redirect('to', {params: true})
redirect('next', {params: true})
redirect('url', {params: true})


Working with locales routes? Take a look at nextjs-redirect-locale.

Native redirects

There's now a native way of handling redirects on NextJS. You can read more about it here. It requires you to modify your next.config.js. Personally I still think nextjs-redirect is a more friendly way of doing it, and also more flexible. For example you can do dynamic redirects on the server, depeding on the request, which is useful when working with locales (checkout nextjs-redirect-locale) and other request-dependent redirects. It also allows you make client redirects with a custom layout.




Pablo Varela