Hi @rob, thanks for taking your time on this.
Are you seeing that the dbAuth check for the user is introducing a noticeable delay?
Nope, I worked on my first Redwood project using Auth0 without almost any issue except a wired behavior explained here: Auth0 iframe in unauthenticated routes
For my second project, I decided to use dbAuth. After setting up, I found this code:
export const getCurrentUser = async (session: Decoded) => {
if (!session || typeof session.id !== 'number') {
throw new Error('Invalid session')
}
return await db.user.findUnique({
where: { id: session.id },
select: { id: true, email: true },
})
}
And I wondered if it’s possible to avoid hitting the DB with a simple cache, something like this:
import NodeCache from 'node-cache'
...
const cache = new NodeCache()
export const getCurrentUser = async (session: Decoded) => {
if (!session || typeof session.id !== 'number') {
throw new Error('Invalid session')
}
let user = cache.get(session.id)
if (!user) {
user = await db.user.findUnique({
where: { id: session.id },
select: { id: true, email: true },
})
cache.set(session.id, user)
}
return user
}
Testing this in my dev local environment, seems to work.
The only issue I don’t know how to resolve is: how to remove the user from cache after logout?
Redwood has handlers for:
- login
- signup
- forgotPassword
- resetPassword
but there is no handler for logout
, that’s a pitty.
You could mitigate this by double-checking on any sensitive action that the user is still valid, but you’re making a lot of additional work for yourself.
Of course, with a cache we have to manage to keep all things synchronized. This should not be a problem if we have a “logout hook” the remove users from cache when they close their session. I’m not sure what you mean with “lot of additional work”, I think is not so difficult to do this.
Finally, given that auth is implemented using RW functions, I’m not sure how this may change if we deploy using AWS lambdas or in a baremetal environment. Probably, there is no problem if we use an external cache server like Redis, but using NodeCache may not work with serveless functions.