In the App Router, await cookies() and call set() from a Server Action or Route Handler. Server Components cannot set cookies because their response has already started.
// app/api/login/route.ts
import { cookies } from "next/headers";
export async function POST() {
const jar = await cookies(); // cookies() is async since Next.js 15
jar.set("session", "abc123", {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7,
});
return Response.json({ ok: true });
}Use httpOnly for session identifiers so scripts cannot read them, and secure so they are sent over https only. Reading works anywhere on the server with (await cookies()).get(name).
In the Pages Router, set the header yourself: res.setHeader("Set-Cookie", "session=abc123; HttpOnly; Path=/").
