How would you implement a simple session management system using cookies in Next.js?
Short answer
You generate a unique session identifier when a user logs in, store that identifier along with the user's data in a database or cache, save the identifier itself in a secure cookie, and then look up the session on each request by reading that cookie and matching it against your…
Advertisement
AModel answer
You generate a unique session identifier when a user logs in, store that identifier along with the user's data in a database or cache, save the identifier itself in a secure cookie, and then look up the session on each request by reading that cookie and matching it against your stored sessions.
async function getSession() {
const cookieStore = await cookies();
const sessionId = cookieStore.get('sessionId')?.value;
if (!sessionId) return null;
return await db.session.findUnique({ where: { id: sessionId } });
}Real-world example
An online learning platform stores each user's session in a database, keyed by a random session identifier saved in a cookie, letting the app quickly look up who is logged in on every page request.
Likely follow-ups
- Should session data be stored in a database or in the cookie itself?
- How do you handle logging a user out and clearing their session?
Related topics