-
Summaryim trying to write session and refresh tokens to cookies in middleware, then redirect to another page. the redirect works, and the cookies are present in the application, but my session does not see them. i need to refresh the page for the cookies to take effect. I've tried a few variations of writing the cookie, forcing the cookie into the header, getting the new cookie directly from the request in middleware. but it appears that writing a cookie within middleware and trying to use it in the next page in middleware isn't working. Additional informationsample from middleware logic
if (pathname.startsWith("/verify")) {
const params = pathname.split("/");
const type = params[2];
const id = params[3];
const token = params[4];
const new_tokens = await attemptLoginLink({ id, token });
// return await attemptLoginLink({ id, token, type, origin });
console.log("mw - new_tokens", new_tokens);
if (new_tokens) {
const response = NextResponse.redirect(
new URL(
type === "password"
? CHANGE_PASSWORD_URL
: EMAIL_REGISTRATION_SUCCESS_URL,
request.url
)
);
response.cookies.set({
name: "session",
value: new_tokens.accessToken,
httpOnly: true,
sameSite: "strict",
maxAge: jwtExpiryTime / 1000,
});
response.cookies.set({
name: "refresh",
value: new_tokens.refreshToken,
httpOnly: true,
sameSite: "strict",
maxAge: refreshExpirytime / 1000,
});
// applySetCookie(request, response);
return response; // redirects as expected, and cookies are present in chrome/dev tools application
}
}
const user = await getSession(); // attempts to get cookies from next/cookies but they are not visible
console.log("middle ware user", user); ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
Hi, You are writing the cookie to the outgoing response, but the incoming request does not have it.
So, you have to set it to the incoming request. Try for example: import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
type Cookie = Parameters<
ReturnType<typeof NextResponse.next>["cookies"]["set"]
>[0];
export function middleware(request: NextRequest) {
const cookie = { name: "vercel", value: "fast", path: "/" } satisfies Cookie;
request.cookies.set(cookie.name, cookie.value);
const response = NextResponse.next(request.clone());
response.cookies.set(cookie);
return response;
} |
Beta Was this translation helpful? Give feedback.
Could you try with same-site policy, set to lax? IIRC, over Chrome had some quirky behavior with redirects and cookies. Does it work with other browsers?