Skip to content

Commit 7cc63a1

Browse files
update nextjs middleware
1 parent 86b19d1 commit 7cc63a1

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

pages/sessions/cookies/nextjs.md

+17-13
Original file line numberDiff line numberDiff line change
@@ -83,29 +83,33 @@ export function deleteSessionTokenCookie(): void {
8383
}
8484
```
8585

86-
Since we can't extend set cookies insides server components due to a limitation with React, we recommend continuously extending the cookie expiration inside middleware.
86+
Since we can't extend set cookies insides server components due to a limitation with React, we recommend continuously extending the cookie expiration inside middleware. However, this comes with its own issue. Next.js revalidates data when a server action response sets a cookie directly with `cookies()` or indirectly with `NextResponse.cookies` via middleware. We also can't detect if a new cookie was set inside server actions or route handlers from middleware. As such, we'll only extend the cookie expiration on GET requests.
8787

8888
```ts
8989
// middleware.ts
9090
import { NextResponse } from "next/server";
91-
import { cookies } from "next/headers";
9291

9392
import type { NextRequest } from "next/server";
9493

9594
export async function middleware(request: NextRequest): Promise<NextResponse> {
96-
const token = cookies().get("session")?.value ?? null;
97-
if (token !== null) {
98-
// Not using `setSessionCookie()` to avoid accidentally importing Node-only modules.
99-
cookies().set("session", token, {
100-
httpOnly: true,
101-
sameSite: "lax",
102-
secure: process.env.NODE_ENV === "production",
103-
maxAge: 60 * 60 * 24 * 30, // 30 days
104-
path: "/"
105-
});
95+
if (request.method === "GET") {
96+
const response = NextResponse.next();
97+
const token = request.cookies.get("session")?.value ?? null;
98+
if (token !== null) {
99+
// Only extend cookie expiration on GET requests since we can be sure
100+
// a new session wasn't set when handling the request.
101+
response.cookies.set("session", token, {
102+
path: "/",
103+
maxAge: 60 * 60 * 24 * 30,
104+
sameSite: "lax",
105+
httpOnly: true,
106+
secure: process.env.NODE_ENV === "production"
107+
});
108+
}
109+
return response;
106110
}
107111

108-
// CSRF protection, etc
112+
// CSRF protection
109113

110114
return NextResponse.next();
111115
}

0 commit comments

Comments
 (0)