Closed jermsam closed 1 year 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 ;)
Thank @WNemencha for this feedback.
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.