NextAuth getServerSession used multiple time

I wonder what is the best way to know if your user is authenticated in multiple places in Next App router using NextAuth. Super classic usecase (I would think): I need to know if Im authenticated both from my header (RSC) and page (RSC). If I use getServerSession two times, one in each RSC, my DB will be fetched two times, clearly feels overkill for a single server request overall. What would be the recommended way then ? - Calling getServerSession from the root layout and passing it down everywhere ? Seems not convenient and quite bad DX. - Using a client provider at the root and using client useSession everytime I need it ? Seems like not the RSC way of doing it. - Creating my custom context where I fetch if Im authenticated in server once and share it across the app on client ? - Caching the session on server but not secure. There must be a easier way right ? My usecase seems quite common but Im a noob in both NextJS and NextAuth, maybe Im missing something.
4 Replies
Ayoub K
Ayoub K2w ago
I personally do all my critical auth checks in the middleware
Xanacas
Xanacas2w ago
If you're using v5, you'll be using useSession() as a hook on client side components and auth() on RSC, API Routes and Middleware. To my understanding you don't need to take care of any caching, this is done by nextAuth/AuthJS. https://authjs.dev/getting-started/migrating-to-v5#authenticating-server-side
Migrating to v5
Authentication for the Web
Reador
ReadorOP2w ago
Im using the default t3 app so NextAuth v4 with DB provider. Using getServerSession() triggers two DB query (one for header, one for page). And I guess it will be same if I use v5 auth() as its the "normal" with DB provider. Using useSession forces me to make my component client components and use a client side provider. To me the whole point of using NextJS is to avoid that whenever possible, and here it definitely feels overkill. But again maybe Im missing something.
Reador
ReadorOP2w ago
Clearly I spoke too fast, I did the migration to v5 using https://github.com/t3-oss/create-t3-app/pull/2000 Now its cached correctly and the DB is called only once, thats perfect, didnt expect the v5 to fix this specific thing.
GitHub
feat: next 15 by ronanru · Pull Request #2000 · t3-oss/create-t3-app
✅ Checklist I have followed every step in the contributing guide (updated 2022-10-06). The PR title follows the convention we established conventional-commit I performed a functional test on my...
Want results from more Discord servers?
Add your server