Deviopath › Next.js

Theme Cookie Route

Medium · Route Handlers

In Next.js you read and write cookies with cookies() from next/headers. Since Next.js 15 it is **async**: const cookieStore = await cookies(). Then:

- cookieStore.get("theme")?.value reads a cookie (the result is undefined when it is missing).

- cookieStore.set("theme", "dark", { path: "/", maxAge: 60 * 60 * 24 * 365, sameSite: "lax" }) sends a Set-Cookie header with the response. maxAge is in **seconds**.

cookieStore.set only works in Route Handlers and Server Actions (Proxy sets cookies on its response instead). Server Components can only read cookies.

Imports are not available here, so a small cookies() stand-in is already written at the top. It turns your set call into the header text, e.g. theme=dark; Path=/; Max-Age=31536000; SameSite=Lax.

Implement the handlers:

- The current theme is the theme cookie when it is "light" or "dark". Anything else (or no cookie) counts as "light".

- GET(): respond 200 with { theme }. Do not set a cookie.

- POST(request): read the body with await request.text(). - Empty body: toggle the current theme. - Otherwise parse it as JSON. If theme is "light" or "dark", use that. If the JSON is invalid or the theme is anything else, respond 400 with { error: 'Theme must be "light" or "dark"' } and set no cookie. - Save the new theme in the cookie for one year with path: "/" and sameSite: "lax", and respond 200 with { theme }.

The driver callThemeRoute(method, cookies, body?) is already written and returns { status, body, setCookie } (setCookie is null when no cookie was set).

Next: Protect Routes in proxy.ts