1
Hello, I would like a help for creating private routes using Nextjs. All files deposited inside the directory pages become accessible routes, in my application some of these must be accessible when the user is logged in. I am currently using useEffect to check if there is an object called username in the sessionStorage, the code below is on the login page and redirects the user if it is already connected:
useEffect(() => {
const session = sessionStorage.getItem('username');
if (session) {
router.push(router.query.followPage || '/');
}
}, [router]);
This method is far from efficient, and redirects the user after the page’s initial load showing the user screen components, as well as being slower at redirecting. Similar validations exist on other pages, in these if username does not exist the user is directed to login page.
I found some instructions for creating a HOC (Higher-Order Component) and involving my private pages with it, that sounds promising but I could not understand how the author proposes that user data be validated, that is, how the user session is verified by the function created by it checkUserAuthentication at this source: https://medium.com/@eslamifard.ali/how-to-Simply-create-a-private-route-in-next-js-38cab204a99c
Use the function getInitialProps next to check the server-side user authentication and redirect it from there seems efficient, I found some sources suggesting to pass a token in the request header but again, I didn’t understand how this works if the user goes to the page directly through the url without using some internal link of the page.
So what’s the best way to create private routes with Nextjs?
The current application I am developing is very simple and does not need large levels of security, a simple validation on the user session is already enough for my case, a response that uses a validation based on the sessionStorage will already be welcome, but if you want to contribute a more advanced response for future users looking for it, feel free.
– mauricio-andre
Just a question to ask... In this scenario (where the user has to be logged in to view the page) is it really worth using Next? The main purpose of Next is to allow SSR (and similar) to improve SEO. But if the page is private, this is not necessary. Anyway, I’m not saying stop using Next, but it’s something to think about. Authentication with Next is not very trivial to do because you have to synchronize the token authorization between client and server, which can take a little work.
– Luiz Felipe
It’s a great question, I didn’t make it clear in the question but I’m extending an existing application, deal with a site that was built in next and that now the client wants to include two pages that only he has access to, there is no really private information in them, but the client does not want to expose the same for now.
– mauricio-andre