Skip to content

Commit 1188193

Browse files
authored
docs: clarify getAccessToken req/res usage in Route Handlers with cus… (#2577)
2 parents 9c2b76c + 28052c5 commit 1188193

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

EXAMPLES.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -929,6 +929,43 @@ export async function GET() {
929929
}
930930
```
931931

932+
**App Router Route Handlers — Refresh + Custom Response Headers/Cookies:**
933+
934+
If your Route Handler needs to both refresh the session **and** return a `NextResponse` you fully control (e.g., to set additional cookies with a `Domain` or `SameSite` attribute), use the explicit `getAccessToken(req, res, options)` signature. This writes the refreshed session directly onto the `NextResponse` you pass, so all `Set-Cookie` headers — session and custom — are consolidated on the one response object you return.
935+
936+
```typescript
937+
// app/api/refresh/route.ts
938+
import { NextRequest, NextResponse } from "next/server";
939+
940+
import { auth0 } from "@/lib/auth0";
941+
942+
export async function POST(req: NextRequest) {
943+
// 1. Create the response object you will return.
944+
const res = new NextResponse();
945+
946+
// 2. Pass req + res explicitly so the SDK writes the refreshed session
947+
// cookies directly onto `res` rather than into Next.js's internal
948+
// AsyncLocalStorage store. This makes the Set-Cookie headers (including
949+
// Domain, SameSite, Secure, etc. from your session.cookie config)
950+
// available on the response object you control.
951+
const { token } = await auth0.getAccessToken(req, res, { refresh: true });
952+
953+
// 3. Set any additional cookies on the same response object.
954+
res.cookies.set("my-cookie", "value", {
955+
domain: ".example.com",
956+
secure: true,
957+
sameSite: "lax"
958+
});
959+
960+
// 4. Return the single response — it now carries both the refreshed
961+
// session Set-Cookie headers and your custom cookie.
962+
return res;
963+
}
964+
```
965+
966+
> [!IMPORTANT]
967+
> Calling `getAccessToken({ refresh: true })` (without `req`/`res`) in a Route Handler writes the refreshed session through Next.js's internal cookie store, **not** onto a `NextResponse` you construct. If you then build a `new NextResponse()` and add cookies to it, that response will be missing the refreshed session cookies. Always pass `req` and `res` explicitly when you need all cookies on the same response object.
968+
932969
**Pages Router (getServerSideProps, API Routes):**
933970

934971
When calling `getAccessToken` with request and response objects (from `getServerSideProps` context or an API route), the options object is passed as the third argument.

0 commit comments

Comments
 (0)