Hey folks here is my code to check if the session exists in the database I use it in my root loader
export async function getUserId(request: Request, { redirectTo }: { redirectTo?: string | null } = {}) {
const { session: authSession, sessionId } = await getAuthSession(request);
if (!sessionId) return null;
const session = await db.session.findUnique({
where: { id: sessionId, expiresAt: { gt: new Date() } },
select: { userId: true },
});
if (!session?.userId) {
const loginRedirect = getLoginRedirectURI(request, { redirectTo });
throw redirect(loginRedirect, {
headers: {
"Set-Cookie": await authSessionStorage.destroySession(authSession),
},
});
}
return { userId: session.userId };
}
currently my app has an absolute session expiration of 30 days I want to add rolling session in my app so after last time session was updated if 15 days have passed then session will renew for another 30 days so to implement rolling session here is what I'm thinking to do when getting the session from the database also get when it was last time updated after checking session exist I will check if updatedAt + 15 days <= now() if it result in true I will extend the session for another 30days but now this time along with userId I will also return a new property updated: true now in my root loader I can check if the returned data has updated property if it has then I will update the auth session storage cookie also is this rolling session approach good because according to sergio article regarding rolling session loader is not good place for rolling session instead we should use entry.server file but that article only assumes purely cookie session where mine is database-cookie session