fridays / next-routes

Universal dynamic routes for Next.js
MIT License
2.47k stars 230 forks source link

I wish for a <Redirect/> component for next-routes #293

Closed jermsam closed 1 year ago

jermsam commented 5 years ago

Since the it's so common to use next exclusively for ssr and we normally handle authentication from another server other than the next server, I think it would be cool to have a React component that lets one redirect to a page of their choice without bothering the next-server. Something like: <Redirect to='/dashboard?usr=${id}'/> Will be glad to here from the community soon.

WNemencha commented 5 years ago

We typically use an util function for that because Redirect is typically not something to render & it would make the DOM tree looks weird to us. Please find the attached function and see if it can fits your need:

// lib/utils/redirect.js
import Router from "next/router";

// redirect helper function to be used in getInitialProps
export default (res, url) => {
  // res is only available if server-side
  if (res) {
    res.writeHead(302, { location: url })
    res.end()
  } else {
    Router.push(url)
  }
};

With that file in utils, you can then call it with isomorphic support, i.e. In the case you'd like to redirect an user back to login if he is not logged in:

// _document.js
const loginRedirect = (req, res) => {
  const uri = new Url(req ? req.url : window.location, true)
  const redirectUri = uri.query.redirect || '/'
  redirect(res, redirectUri)
}

// withAuthRouter returns an HOC that check if user is logged in via GraphQL
const withLoginRedirect = withAuthRouter(({ error, user, ctx }) => {
  if (!error && user) {
    loginRedirect(ctx.req, ctx.res)
  }
})

const DocumentPage = props => props.children

// Wrap the page with the HOC.
export default withLoginRedirect(DocumentPage)

Hope this helps. Credits to @lucleray for the amazing approach ;)

jermsam commented 5 years ago

Thank @WNemencha for this feedback.