Cookies & Session Management in Next.js
5 questions found
How do you read cookies in a Next.js server component?
Beginner
The App Router gives you a cookies function from next/headers that you can call inside a server component to read any cookie sent with the request, letting you access things like a session token or a user's saved preferences without needing any client side code.
import { cookies } from 'next/headers';
export default async function Page() {
const cookieStore = await cookies();
const theme = cookieStore.get('theme');
return <p>Current theme: {theme?.value}</p>;
}
Real-world example
A website reads a saved theme preference cookie on the server, allowing it to render the page with the correct dark or light theme immediately, without a flash of the wrong theme on load.
Common follow-ups: Can you write or set cookies from within a server component?;What is the difference between reading cookies on the server versus the client?
Authentication & Authorization in Next.js;Server Components
How do you set a cookie in Next.js, such as after a user logs in?
Intermediate
You typically set cookies from a server action or a route handler using the cookies function, calling its set method with the cookie name, value, and options like httpOnly and secure flags, which controls how the browser stores and sends that cookie on future requests.
'use server';
import { cookies } from 'next/headers';
export async function login(formData) {
const token = await authenticateUser(formData);
const cookieStore = await cookies();
cookieStore.set('session', token, { httpOnly: true, secure: true, path: '/' });
}
Real-world example
A login form calls a server action that verifies the user's credentials and then sets a secure session cookie, keeping the user logged in across future visits to the site.
Common follow-ups: What cookie options are important for keeping a session cookie secure?;How long should a session cookie typically last before it expires?
Authentication & Authorization in Next.js;Security Best Practices in Next.js
How would you implement a simple session management system using cookies in Next.js?
Intermediate
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.
Common 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?
Database Integration with Next.js;Authentication & Authorization in Next.js
What is the difference between storing session data in a signed cookie versus a server side session store?
Advanced
A signed cookie stores the session data directly inside the cookie itself, verified with a signature so it cannot be tampered with, while a server side session store keeps only a reference identifier in the cookie and stores the actual data in a database, which is more secure for sensitive information and easier to revoke.
// Signed cookie approach stores encoded data directly
// Server side store approach only stores a reference id
const sessionId = cookieStore.get('sessionId');
const session = await redis.get(sessionId);
Real-world example
A banking application uses a server side session store so that sessions can be instantly revoked if suspicious activity is detected, which would not be possible if the session data lived entirely inside the user's cookie.
Common follow-ups: Which approach scales better for a large application with many users?;How do you revoke a session immediately when using signed cookies?
Security Best Practices in Next.js;Database Integration with Next.js
What security settings should always be applied to cookies that store session or authentication information?
Advanced
Always set the httpOnly flag so client side scripts cannot read the cookie, set the secure flag so it is only sent over HTTPS, choose an appropriate sameSite setting to prevent cross site request forgery, and set a reasonable expiration time so sessions do not last forever.
cookieStore.set('session', token, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 7,
path: '/'
});
Real-world example
An e-commerce platform sets strict cookie security settings on its checkout session cookie, protecting customer payment flows from common attacks like cross site scripting and cross site request forgery.
Common follow-ups: What is the difference between sameSite lax and sameSite strict?;How do these settings affect single sign on flows across subdomains?
Security Best Practices in Next.js;Authentication & Authorization in Next.js