A very basic thing that can not be done right using NextAuth?
I have an app that uses DB sessions. I've got an /admin route that I want to protect using a Next.js middleware by checking the user's role, but I can't do this because I don't have access to 'user' obj.
How can I do this right without having to copy-paste a block of getServerSideProps?
30 Replies
middleware runs on the server so you have access to the server session https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes
Securing pages and API routes | NextAuth.js
You can easily protect client and server side rendered pages and API routes with NextAuth.js.
You can't access the session in middleware.ts
i need to correct myself, I'm trying to protect admin pages not api routes
api routes are protected by tRPC anyways
Oh then I misunderstood
Yeah I apologize
Depending on your needs, you might be able to use a shared layout
Put a hook in it that checks for a role, and a component that doesn’t render children unless that role exists
And redirect instead to a 404 also right?
Sure
that's a great idea thank you
Or just render “you’re not allowed to see this”
yeah correct
Either one is fine, depends what fits best with your project as a whole I guess
Thanks 🙂
So I did this, in the shared layout I called useSession and checked for session.user.role === 'ADMIN' in a useEffect that runs on mount. But the issue is that for the first second session.user is null so it will not satisfy the condition
Where is your data coming from?
I would do like const isAuthed = useSomeHook
And then if (!isAuthed) don’t render anything
I need the data that's in the nextauth session
specifically the role that i store in the user object
No I mean like the data that is displayed on the page
Make the fetching of that conditional
Only fetches if user is airbed
Authed