Giter Site home page Giter Site logo

pablopunk / nextjs-redirect Goto Github PK

View Code? Open in Web Editor NEW
147.0 2.0 10.0 1.33 MB

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

Home Page: https://pablopunk.github.io/nextjs-redirect/

License: MIT License

TypeScript 38.26% HTML 8.61% JavaScript 53.13%
hacktoberfest nextjs redirect hoc dynamic

nextjs-redirect's Introduction

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

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

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=https://google.com
  • /redirect?next=https://twitter.com
  • /redirect?url=https://pablopunk.com

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})

Related

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.

License

MIT

Author

me
Pablo Varela

nextjs-redirect's People

Contributors

dependabot[bot] avatar pablopunk avatar tymick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nextjs-redirect's Issues

Exporting static does not work.

There seems to have been changes since #4 that broke this feature. To be specific, it's that getInitialProps now has calls to Router again once more.

    static async getInitialProps({ res, query }) {
      if (res?.writeHead) {
        let url = redirectUrl

        if (options?.params === true) {
          const param = redirectUrl
          if (!query[param]) {
            throw new Error(PARAMS_ERROR)
          }
          url = query[param]
        }

        res.writeHead(options?.statusCode ?? 301, { Location: url })
        res.end()
      } else if (options?.asUrl) {
        Router.push(redirectUrl, options.asUrl, { shallow: true })
      } else {
        Router.push(redirectUrl)
      }

      return {}
    }

Option to add styles

Hi

I know this might not be really necessary, but since redirection might take a second or so, I would like to apply some styles while it happens

Would you mind adding an option for that, please?

Feature Request

Is it possible to redirect with a value from the original url?

Say the url looks like this:
website.com/redirect?key=value

and then the redirect becomes website.com/another-page?key=value

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.