Is it possible to get the user id from the cookie without having to verify to user and hit the DB?

Right now I have a call to the database that will check if the user with the id has access to the resource being requested. Because of this I need to get the session which can take ~200ms uncached. I don't really need to verify the user is valid before I get the resource and it would speed things up quite a bit if I could just do that at the same time as I am getting the resource. Is it possible to just get the userId from the cookie / apiToken without having to hit the DB first? Right now the code looks something like:
const session = await auth.api.getSession(...);

const resource = await getResource(session.user.id);
const session = await auth.api.getSession(...);

const resource = await getResource(session.user.id);
but ideally I could do something like:
// gets the userId from the session cookie without hitting the DB
const userId = await auth.api.getUserId();

// do this in parallel
const session = auth.api.getSession(...);
const resource = getResource(userId);

if (!session) error(401);
// gets the userId from the session cookie without hitting the DB
const userId = await auth.api.getUserId();

// do this in parallel
const session = auth.api.getSession(...);
const resource = getResource(userId);

if (!session) error(401);
4 Replies
iedan
iedanOP2d ago
The easier thing is just to do the validation yourself in this case I think... What I ended up doing was just getting the sessionToken / apiKey and sending that in my request to the DB. Then I would just join in the user id in my query so that I didn't have to make the extra trip... This is what that looks like for me:
const cookie = getSessionCookie(request.headers);

const sessionToken = cookie?.split('.')[0] ?? null;
const apiKey = request.headers.get('x-api-key');

// send sessionToken and apiKey to the server and get the userId by joining on the session and apikey tables
const cookie = getSessionCookie(request.headers);

const sessionToken = cookie?.split('.')[0] ?? null;
const apiKey = request.headers.get('x-api-key');

// send sessionToken and apiKey to the server and get the userId by joining on the session and apikey tables
Snazzie
Snazzie2d ago
i think the most straight forward way is using bearer token with your api. have claims on the token and since you can verifiy it is signed, you can basicly trust it
iedan
iedanOP18h ago
That works fine for user sessions but not really for api keys. Unless you're suggesting to use JWT for both... But then you can't get the immediately revoked behavior of API keys when deleting them
Snazzie
Snazzie17h ago
true, but u can remedy with revoked key lookup cache layer

Did you find this page helpful?