I am trying to create an authentication system with jwt in nextjs. So I built a middleware that could verify the jwt token and use it to set up an authentication system like this:
export default function middleware(request, event) {
const token = request.cookies.token
let authenticated = false
if (pathname === '/dashboard') {
if (token) {
try {
jwt.verify(token, 'HvpkPMarcwoZFAo')
authenticated = true
} catch {
return NextResponse.redirect('/signin')
}
} else {
return NextResponse.redirect('/signin')
}
}
}
According to the above code if the user is not logged in, he will be redirected to the login page.
But the problem is that I want some components to change according to authentication (for example, do not show the registration button for logged in users).
Can I get data from this middleware (for example a boolean value) to be used in different components?
I used response.locals in Expressjs. Is there a similar solution in Nextjs?
You should look at https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
getServerSideProps receives context in params ;)