How to implement redirect based on user role
Hi, I would love to implement redirections based on the user role.
I want to implement it so that on every single page, I can explicitly define which roles are allowed to view the current page and the redirect url to which the user will be redirected if he isn't authorized to view the page.
Now I have implemented a simple hook which works but the content of the page still flashes before the user gets redirected.
What is the recommended way to protect routes in t3-app based on roles?
My implementation: useRoleRedirect.ts: Usage of hook in other component: Now this thing works but the original content from "Page" still gets flashed which I would like to prevent. I'm also just curious what the standard way of handling this type of problem is. I greatly appreciate any advice 🙂
My implementation: useRoleRedirect.ts: Usage of hook in other component: Now this thing works but the original content from "Page" still gets flashed which I would like to prevent. I'm also just curious what the standard way of handling this type of problem is. I greatly appreciate any advice 🙂
5 Replies
middlewares
Do you have any resources on how I could implement that specifically?
Or a good example?
I already found out that I can have protected pages with nextAuth:
https://next-auth.js.org/tutorials/securing-pages-and-api-routes
Im not sure how to access the session object there to get the user role
Securing pages and API routes | NextAuth.js
You can easily protect client and server side rendered pages and API routes with NextAuth.js.
Role-based access control | Auth.js
There are two ways to add role-based access control (RBAC) to your application, based on the session strategy you choose. Let's see an example for each of these.
how to add role to the auth js side of things
the middleware side, the matcher is whatever you define
but you shold check if the user exists, and later check his role
both of those operations should redirect to whatever you need
but the docs are awful
Thanks for the link, I'll check it out