How do you all handle Role based access?
I'm creating a new Next app which will require RBA.
So let's say I have 2 routes for my user roles:
/student/* and /teacher/*
Is it better to handle Authorization to those pages in getServerSideProps and then redirect if the role isn't correct.
Or should I lazy load the main content and then display if the role is right?
E.g. I have a page for showing all tasks. Teachers are supposed to see the tasks only they have created, while students should see all the created tasks. Since both pages show mostly the same components only with some different data, should I make that into 2 routes /students/tasks and /teachers/tasks, and use getSSP like I explained or is it better to just query content depending on role and then when it arrives display it? Or if they aren't logged in at all, show login component.
9 Replies
you can use a middleware to block any unauthorised access or redirect to the correct page
no user? redirect to sign in page teacher using student page? redirect to teacher student using teacher page? redirect to studentthe fetching side of things, can be handled on its own at api level
This only works with JWT strategy tho...
if you can fetch the user before rendering the page, the same applies to middleware/gssp
Found this:
https://next-auth.js.org/configuration/nextjs
Next.js | NextAuth.js
unstable_getServerSession
So yes I can use it in middleware... the only thing I was worried about was the loading state, but it seems I was worried for nothing... xD
Usually fetching the data is cheap as long it's a fine query
You can add redirects and such at the routing layer, but might be worth adding something closer to the persistence/service layer too (in case someone does manage to sneak past your route guards)
Client API | NextAuth.js
The NextAuth.js client library makes it easy to interact with sessions from React applications.
might give you some insight 👍