nextjs - 💡(How to fix) Fix Proxy set cookie not work [4 comments, 4 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
vercel/next.js#86798Fetched 2026-04-08 02:09:06
View on GitHub
Comments
4
Participants
4
Timeline
9
Reactions
0
Timeline (top)
commented ×4labeled ×2closed ×1issue_type_added ×1

Code Example

export async function proxy(request: NextRequest) {
	// Check if there is any supported locale in the pathname
	const { pathname } = request.nextUrl;
	if (pathname.startsWith("/api/")) {
		const res = await updateSession(request);

		console.log(res.cookies);

		return res;
	}

	const segments = pathname.split("/").filter(Boolean);

	if (
		segments.length > 1 &&
		(segments[1].startsWith("login") || segments[1].startsWith("register"))
	) {
		const session = await auth.api.getSession({
			headers: request.headers,
		});

		if (session?.session) {
			request.nextUrl.pathname = `/${segments[0]}`;
			return NextResponse.redirect(request.nextUrl);
		}
	}

	const pathnameHasLocale = locales.some(
		(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
	);

	if (pathnameHasLocale) return;

	// Redirect if there is no locale
	const locale = getLocale(request);
	request.nextUrl.pathname = `/${locale}${pathname}`;
	// e.g. incoming request is /products
	// The new URL is now /en-US/products
	return NextResponse.redirect(request.nextUrl);
}

export const config = {
	matcher: [
		/*
		 * Match all request paths except for the ones starting with:
		 * - _next/static (static files)
		 * - _next/image (image optimization files)
		 * - favicon.ico (favicon file)
		 * - api/claims (claims API endpoint)
		 * - api/refresh-token (token refresh endpoint)
		 * Feel free to modify this pattern to include more paths.
		 */
		"/((?!_next/static|_next/image|favicon.ico|api/claims|api/refresh-token|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
	],
};

---

import { NextResponse, type NextRequest } from "next/server";
import { fetchHelpers } from "./common";

export async function updateSession(request: NextRequest) {
	let refreshResponse = NextResponse.next({
		request,
	});

	// With Fluid compute, don't put this client in a global environment
	// variable. Always create a new one on each request.
	await fetchHelpers.get("/claims", {
		...request,
		getCookies() {
			return request.cookies.getAll();
		},
		setCookies(cookiesToSet) {
			cookiesToSet.forEach(({ name, value }) =>
				request.cookies.set(name, value)
			);
			refreshResponse = NextResponse.next({
				request,
			});
			cookiesToSet.forEach(({ name, value, options }) => {
				refreshResponse.cookies.set(name, value, options);
			});
		},
	});

	return refreshResponse;
}

---

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Pro
  Available memory (MB): 32596
  Available CPU cores: 12
Binaries:
  Node: 22.20.0
  npm: 10.9.2
  Yarn: 1.22.22
  pnpm: 10.13.1
Relevant Packages:
  next: 16.0.7
recommended!
  eslint-config-next: N/A
  react: 19.2.0
  react-dom: 19.2.0
  typescript: 5.9.3
Next.js Config:
  output: N/A
RAW_BUFFERClick to expand / collapse

Link to the code that reproduces this issue

https://github.com/rindev0901/learn-next-16

To Reproduce

  1. Install dependencies (npm install or whatever).
  2. Build and start project (npm run start or your equivalent).
  3. Open the app in your browser
  4. Check ternimal set-cookie property

Current vs. Expected behavior

Current behavior

  • When refreshing token via updateSession function i got new cookie from refresh api then passed into callback of current response to do cookie modification but it doesn't work
export async function proxy(request: NextRequest) {
	// Check if there is any supported locale in the pathname
	const { pathname } = request.nextUrl;
	if (pathname.startsWith("/api/")) {
		const res = await updateSession(request);

		console.log(res.cookies);

		return res;
	}

	const segments = pathname.split("/").filter(Boolean);

	if (
		segments.length > 1 &&
		(segments[1].startsWith("login") || segments[1].startsWith("register"))
	) {
		const session = await auth.api.getSession({
			headers: request.headers,
		});

		if (session?.session) {
			request.nextUrl.pathname = `/${segments[0]}`;
			return NextResponse.redirect(request.nextUrl);
		}
	}

	const pathnameHasLocale = locales.some(
		(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
	);

	if (pathnameHasLocale) return;

	// Redirect if there is no locale
	const locale = getLocale(request);
	request.nextUrl.pathname = `/${locale}${pathname}`;
	// e.g. incoming request is /products
	// The new URL is now /en-US/products
	return NextResponse.redirect(request.nextUrl);
}

export const config = {
	matcher: [
		/*
		 * Match all request paths except for the ones starting with:
		 * - _next/static (static files)
		 * - _next/image (image optimization files)
		 * - favicon.ico (favicon file)
		 * - api/claims (claims API endpoint)
		 * - api/refresh-token (token refresh endpoint)
		 * Feel free to modify this pattern to include more paths.
		 */
		"/((?!_next/static|_next/image|favicon.ico|api/claims|api/refresh-token|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
	],
};
import { NextResponse, type NextRequest } from "next/server";
import { fetchHelpers } from "./common";

export async function updateSession(request: NextRequest) {
	let refreshResponse = NextResponse.next({
		request,
	});

	// With Fluid compute, don't put this client in a global environment
	// variable. Always create a new one on each request.
	await fetchHelpers.get("/claims", {
		...request,
		getCookies() {
			return request.cookies.getAll();
		},
		setCookies(cookiesToSet) {
			cookiesToSet.forEach(({ name, value }) =>
				request.cookies.set(name, value)
			);
			refreshResponse = NextResponse.next({
				request,
			});
			cookiesToSet.forEach(({ name, value, options }) => {
				refreshResponse.cookies.set(name, value, options);
			});
		},
	});

	return refreshResponse;
}

Expected behavior

I want cookies to be overwritten on the browser

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Pro
  Available memory (MB): 32596
  Available CPU cores: 12
Binaries:
  Node: 22.20.0
  npm: 10.9.2
  Yarn: 1.22.22
  pnpm: 10.13.1
Relevant Packages:
  next: 16.0.7
recommended!
  eslint-config-next: N/A
  react: 19.2.0
  react-dom: 19.2.0
  typescript: 5.9.3
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Middleware

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

No response

extent analysis

TL;DR

The issue can be resolved by ensuring that the setCookies function in the updateSession method correctly sets the cookies on the refreshResponse object, which is then returned as the response to the client.

Guidance

  • Verify that the cookiesToSet array is being populated correctly with the new cookie values in the updateSession function.
  • Check that the setCookies function is being called with the correct options for the cookies, such as httpOnly, secure, and domain.
  • Ensure that the refreshResponse object is being returned as the response to the client, and that the cookies are being set on this object.
  • Use the browser's developer tools to inspect the response headers and verify that the Set-Cookie header is being sent with the correct values.

Example

// In the updateSession function, verify that the cookies are being set correctly
cookiesToSet.forEach(({ name, value, options }) => {
  console.log(`Setting cookie ${name} with value ${value} and options ${JSON.stringify(options)}`);
  refreshResponse.cookies.set(name, value, options);
});

Notes

The issue seems to be related to the way cookies are being set on the response object in the updateSession function. The provided code snippet does not show any obvious issues, so further debugging may be necessary to identify the root cause.

Recommendation

Apply a workaround by verifying that the setCookies function is being called correctly and that the refreshResponse object is being returned as the response to the client. This can be done by adding logging statements or using a debugger to inspect the values of the cookiesToSet array and the refreshResponse object.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING