Next.js Discord

Discord Forum

how do I make restricted pages / role based pages in nextjs

Unanswered
German Shepherd Dog posted this in #help-forum
Open in Discord
German Shepherd DogOP
hi,
please help me, I want to create simple web .
I've watched many tutorials about it but they tend to use next-auth.
I am new in nextjs and I want to create restricted pages, and also role based pages.
how do you make that in nextjs , without the help of next-auth.
I'm currently using golang as backend.
I don't mind if the pages have to be fully CSR,or SSR. without SSG and ISG.
what are the best approach for this kind of problem.
and where should I store the jwt token provided provided by my golang backend , in cookie or storage?
any repositories I could see to learn is appreciated.

6 Replies

@KINXZ Cookies would be the way to go. LocalStorage only works on client side. With cookies you can validate it on server side. https://nextjs.org/docs/app/api-reference/functions/cookies
German Shepherd DogOP
hi thank u , I have more questions. should the cookie be made by backend or frontend ?
is it safe to have non http-only cookie ?
and how do you handle restricted pages ? and role based pages?
where do we store this "role" ? should it be in react state like context or in cookie ? for it accessible within server rendered pages
you can make a http-only cookie in nextjs in a route handler or server action. There is multiple ways to store the needed information like role. You could save the information in the cookie directly for example a JWT or query a database/cache like redis.
after you have the information you can either check it manually for every page or make a middleware https://nextjs.org/docs/app/building-your-application/routing/middleware.
@KINXZ you can make a http-only cookie in nextjs in a route handler or server action. There is multiple ways to store the needed information like role. You could save the information in the cookie directly for example a JWT or query a database/cache like redis.
German Shepherd DogOP
hi , so I can make http-only cookie (in nextjs) from the backend response that consist of access_token and refresh_token ?
thank I'll look into it and try around
example flow:
- Login page calls a server action with credentials
- The server actions makes a request to your go backend, creates a cookie and redirects to /dashboard
- Dashboard page (/dashboard) gets the cookie and checks if its valid (if invalid redirect to /login)