Update: Next.js fixed this bug in v14.2.8. Kept here as a reference for older Next.js 14.1 apps and how middleware request and response headers interact.
When Next.js middleware refreshes an auth token or sets a session cookie with response.cookies.set(...), the browser gets the Set-Cookie header. In Next.js <= 14.1.x, though, Server Components calling cookies() during that same request still saw the old Cookie header (or nothing at all).
Why it happened
response.cookies.set() updates the outgoing response headers sent to the browser, not the incoming Cookie header forwarded internally to Server Components.
Workaround: update both request and response cookies
To make updated cookies visible to both Server Components and the browser right away, serialize them into the forwarded request.headers as well as response.cookies:
import { NextResponse } from "next/server";
import cookie from "cookie";
export function applyCookiesInMiddleware(request, newCookies) {
const parsed = cookie.parse(request.headers.get("cookie") || "");
for (const item of newCookies) {
parsed[item.name] = item.value;
}
const headerParts = Object.entries(parsed).map(([k, v]) =>
cookie.serialize(k, v)
);
const requestHeaders = new Headers(request.headers);
requestHeaders.set("cookie", headerParts.join("; "));
const response = NextResponse.next({
request: { headers: requestHeaders },
});
for (const item of newCookies) {
response.cookies.set(item.name, item.value, item);
}
return response;
}
In real apps, make sure middleware only runs this on actual page or API routes rather than firing on static assets and images.