TyMick / nextjs-redirect

HOC to redirect to any URL in NextJS both in client and server

Home Page:https://pablo.pink

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

nextjs-redirect

Redirect to any URL in NextJS both in client and server

Install

npm install nextjs-redirect

Usage

Let's say you want to create a page /donate that redirects the user to paypal.me 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('https://paypal.me/pablopunk/5')

You can checkout this example live in pablo.pink

Status code (301, 302...)

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

redirect('https://google.es', { 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:

redirect('/user/42/info')

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('https://github.com/pablopunk')

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

Related

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

License

MIT

Author

me
Pablo Varela

About

HOC to redirect to any URL in NextJS both in client and server

https://pablo.pink


Languages

Language:TypeScript 71.8%Language:HTML 28.2%