---
title: "How do you set a cookie on the server in Next.js?"
description: "In the App Router, set cookies with (await cookies()).set() inside a Server Action or Route Handler. Pages Router API routes use res.setHeader."
url: "https://bugsee.com/answers/nextjs/set-a-cookie-on-the-server/"
---

# How do you set a cookie on the server in Next.js?

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.

```ts
// 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=/")`.

## Related questions

- [How do you get URL query parameters in the Next.js App Router?](https://bugsee.com/answers/nextjs/get-url-query-params/)
