How to prevent multiple DB calls in this situation
I am using T3 stack with:
- Drizzle
- WorkOS AuthKit
- Next JS app router
The auth/user data from AuthKit only has email address, first/last name so I wanted to store some additional data for each user like username so as a result I created a custom getUser function that wraps the AuthKit getUser function:
Solution:Jump to solution
in the lucia docs they recommends to use the cache function from react
https://lucia-auth.com/guides/validate-session-cookies/nextjs-app...
Lucia
Validate session cookies in Next.js App router
Lucia is an open source auth library that abstracts away the complexity of handling sessions.
4 Replies
I can use this in pages and components like so:
This appears to work fine on the surface, but the problem I am facing is that if I have a page with many components that use
getUser
then I end up making multiple DB calls when essentially I should only need to make one DB call on page load:
How should I structure it so that it only makes one DB call per page, or only when initial application loads?
The AuthKit getUser function alone doesn't require any extra DB calls because it gets the user information from the cookie, but in my application I would like to get some extra info from the Users table in the DB.Solution
in the lucia docs they recommends to use the cache function from react
https://lucia-auth.com/guides/validate-session-cookies/nextjs-app
Lucia
Validate session cookies in Next.js App router
Lucia is an open source auth library that abstracts away the complexity of handling sessions.
maybe this is more clear https://nextjs.org/docs/app/building-your-application/caching#react-cache-function
Building Your Application: Caching | Next.js
An overview of caching mechanisms in Next.js.
Thanks @TerjaN I didn't know about this. I initially thought your recommendation wasn't work as I was still seeing 2 of the same DB query logged, but it was due to
getUser
being called differently:
Split the function in two and cached the DB calling part and now it only does one DB query: