I have a have a project on Next.js and React, which doesn't use any libraries for routing. How should I implement route guards (protected routes) for non-authenticated users? Or should I just redirect them if there is no token in cookie?
You can check in getInitialProps
with some approp. logic evaluating the cookies to decide whether to redirect or not.
import Router from 'next/router'
const redirectToLogin = res => {
if (res) {
res.writeHead(302, {Location: '/login'})
res.end()
res.finished = true
} else {
Router.push('/login')
}
}
class ProtectedPage extends React.Component {
static async getInitialProps ({req, res}) {
// get cookie from req.headers or from document.cookie in browser
// this cookie must not contain sensitive information!
const profile = getProfileFromCookie(req)
if (!profile) {
redirectToLogin(res)
}
}
}
Have a look at this sample code https://github.com/lipp/login-with/blob/master/example/nextjs/with-profile.js#L8 (I am the author).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With