Skip to content

Instantly share code, notes, and snippets.

@freeatnet
Created March 26, 2024 10:25
Show Gist options
  • Save freeatnet/075cd5aeb2b7219bf18599ef19eded8a to your computer and use it in GitHub Desktop.
Save freeatnet/075cd5aeb2b7219bf18599ef19eded8a to your computer and use it in GitHub Desktop.
An example showing that a cookie set in a Next.js App Router API handler can be read back in the same request
$ curl --verbose http://localhost:3000/cookie-test
* Trying [::1]:3000...
* Connected to localhost (::1) port 3000
> GET /cookie-test HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/8.4.0
> Accept: */*
>
< HTTP/1.1 200 OK
< vary: RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url
< content-type: application/json
< set-cookie: test=ok; Path=/
< Date: Tue, 26 Mar 2024 10:24:05 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
{"ok":{"name":"test","value":"ok","path":"/"}}
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export async function GET() {
cookies().set("test", "ok");
const aTestCookie = cookies().get("test");
return NextResponse.json({ ok: aTestCookie });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment