In NextJS 13, what is the best way of dealing with routes where a user’s authentication status affects the content they see on a certain route. Specifically, I have 2 scenarios I’m not sure how best to implement:
-
How to redirect an unauthenticated user (e.g. they try to access home page so are redirected to a login page.)
-
How to display different content based on their auth status.
I assume that for the second point, I can just conditionally render different components based on the status, but it is the first scenario I am more unsure about. I’m aware that there is a NextJS redirect function but is this suitable for preventing unauthenticated users seeing private data i.e. is it guaranteed that the user will be redirected before any route content is displayed? Where would this redirect function be used to achieve this?
2
Answers
If you are using the redirect in server component, the user will be redirected before any route content is displayed.
If you are using pages directory, you should use middleware. You can use middleware even for app router. But above solution seems more readable and cleaner to me.
Yeah, it looks like you need to make an authentication system where verified users can access the home page and non-verified users can’t, and they should redirect to Login.jsx automatically.
If I am correct, I highly recommend Hitesh Chaudhory’s latest NextJS video. It’s free, and on YouTube, the language is English, so you need not worry about it as it looks like you are already good in English from your writing style.So, I will leave the link below.
Watch it carefully because NextJS 13 has a lot of new features and has changed its way to authenticate users via the server component.
It will definitely help you.
video’s link