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
cje
cje2y ago
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.
hyperzone
hyperzone2y ago
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
cje
cje2y ago
Oh then I misunderstood
hyperzone
hyperzone2y ago
Yeah I apologize
cje
cje2y ago
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
hyperzone
hyperzone2y ago
And redirect instead to a 404 also right?
cje
cje2y ago
Sure
hyperzone
hyperzone2y ago
that's a great idea thank you
cje
cje2y ago
Or just render “you’re not allowed to see this”
hyperzone
hyperzone2y ago
yeah correct
cje
cje2y ago
Either one is fine, depends what fits best with your project as a whole I guess
hyperzone
hyperzone2y ago
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
cje
cje2y ago
Where is your data coming from? I would do like const isAuthed = useSomeHook And then if (!isAuthed) don’t render anything
hyperzone
hyperzone2y ago
I need the data that's in the nextauth session specifically the role that i store in the user object
cje
cje2y ago
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
Want results from more Discord servers?
Add your server