Next.js › Cookies & Session Management in Next.js
How do you set a cookie in Next.js, such as after a user logs in?
IntermediateAnswer
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.