nextjs - 💡(How to fix) Fix Coluld not use nextUrl.searchParams in route in Next@16 [1 comments, 2 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#86149Fetched 2026-04-08 02:12:19
View on GitHub
Comments
1
Participants
2
Timeline
6
Reactions
0
Author
Timeline (top)
labeled ×2closed ×1commented ×1issue_type_added ×1

Error Message

Error: Route /api/authorize needs to bail out of prerendering at this point because it used nextUrl.searchParams.

Root Cause

Error: Route /api/authorize needs to bail out of prerendering at this point because it used nextUrl.searchParams.

Another Error

Error: During prerendering, `cookies()` rejects when the prerender is complete. Typically these errors are handled by React but if you move `cookies()` to a different context by using `setTimeout`, `after`, or similar functions you may observe this error and you should handle it in that context. This occurred at route "/account/api/whoami".

Code Example

Error: Route /api/authorize needs to bail out of prerendering at this point because it used nextUrl.searchParams.

---

Error: During prerendering, `cookies()` rejects when the prerender is complete. Typically these errors are handled by React but if you move `cookies()` to a different context by using `setTimeout`, `after`, or similar functions you may observe this error and you should handle it in that context. This occurred at route "/account/api/whoami".

---

import { type NextRequest, NextResponse } from 'next/server';
import mm_logger from '../../../../atoms/server/logger';
import ctrls from '../../../ctrls';
import type { QywxAuthorizeParam, QywxAuthorizeResult } from '../../../../controllers/qywx';

const logger = mm_logger(__dirname);


export type Data = QywxAuthorizeResult;

export type Result = {
	ok: true;
	data: Data;
} | {
	ok: false;
	message: string;
};

export type Message = QywxAuthorizeParam;

/**
 * authorize
 */
export function GET(req: NextRequest/* , { params: { id } }: { params: { id: string; } }*/) {
	try {
		const msg = (() => {
			// const { searchParams: sp } = new URL(req.url);
			const sp = req.nextUrl.searchParams;   // Error: Route /api/authorize needs to bail out of prerendering at this point because it used nextUrl.searchParams.
			return Array.from(sp.keys()).reduce((pre, key) => {
				const val = sp.get(key);
				return {
					...pre,
					[key]: val
				};
			}, {} as Message);
		})();
		logger.debug('msg', msg);
		const data = ctrls.qywx.authorize(msg);
		return NextResponse.json({
			ok: true,
			data
		} as Result);
	} catch (error) {
		logger.error(error);
		return NextResponse.json({ ok: false, message: (error as Error).message });
		// return new Response((error as Error).message, {
		// 	status: 500,
		// 	headers: {
		// 		'Content-Type': 'text/plain; charset=utf-8'
		// 	},
		// });
	}
}

---

import { type NextRequest, NextResponse } from 'next/server';
import mm_logger from '../../../../atoms/server/logger';
import ctrls from '../../../ctrls';
import type { UserGetUserByCookieResult } from '../../../../controllers/user';
import get_user from '../../../../atoms/server/get-user';
import { cookies } from 'next/headers';

const logger = mm_logger(__dirname);


export type Data = UserGetUserByCookieResult;

export type Result = {
	ok: true;
	data: Data;
} | {
	ok: false;
	message: string;
};

export type Message = {};

/**
 * whoami
 */
export async function GET(req: NextRequest/* , { params: { id } }: { params: { id: string; } }*/) {
	try {
		// const cookie_store = req.cookies;	// next@15
		const cookie_store = await cookies();
		const data = await get_user(cookie_store);
		return NextResponse.json({
			ok: true,
			data
		} as Result);
	} catch (error) {
		logger.error(error);
		// return NextResponse.json({ ok: false, message: (error as Error).message });
		return new Response((error as Error).message, {
			status: 500,
			headers: {
				'Content-Type': 'text/plain; charset=utf-8'
			},
		});
	}
}

---

v16
RAW_BUFFERClick to expand / collapse

Link to the code that reproduces this issue

https://

To Reproduce

  1. Upgrade 15 to 16
  2. Build project
  3. Exception thrown:
Error: Route /api/authorize needs to bail out of prerendering at this point because it used nextUrl.searchParams.

Another Error

Error: During prerendering, `cookies()` rejects when the prerender is complete. Typically these errors are handled by React but if you move `cookies()` to a different context by using `setTimeout`, `after`, or similar functions you may observe this error and you should handle it in that context. This occurred at route "/account/api/whoami".

This is my code

import { type NextRequest, NextResponse } from 'next/server';
import mm_logger from '../../../../atoms/server/logger';
import ctrls from '../../../ctrls';
import type { QywxAuthorizeParam, QywxAuthorizeResult } from '../../../../controllers/qywx';

const logger = mm_logger(__dirname);


export type Data = QywxAuthorizeResult;

export type Result = {
	ok: true;
	data: Data;
} | {
	ok: false;
	message: string;
};

export type Message = QywxAuthorizeParam;

/**
 * authorize
 */
export function GET(req: NextRequest/* , { params: { id } }: { params: { id: string; } }*/) {
	try {
		const msg = (() => {
			// const { searchParams: sp } = new URL(req.url);
			const sp = req.nextUrl.searchParams;   // Error: Route /api/authorize needs to bail out of prerendering at this point because it used nextUrl.searchParams.
			return Array.from(sp.keys()).reduce((pre, key) => {
				const val = sp.get(key);
				return {
					...pre,
					[key]: val
				};
			}, {} as Message);
		})();
		logger.debug('msg', msg);
		const data = ctrls.qywx.authorize(msg);
		return NextResponse.json({
			ok: true,
			data
		} as Result);
	} catch (error) {
		logger.error(error);
		return NextResponse.json({ ok: false, message: (error as Error).message });
		// return new Response((error as Error).message, {
		// 	status: 500,
		// 	headers: {
		// 		'Content-Type': 'text/plain; charset=utf-8'
		// 	},
		// });
	}
}
import { type NextRequest, NextResponse } from 'next/server';
import mm_logger from '../../../../atoms/server/logger';
import ctrls from '../../../ctrls';
import type { UserGetUserByCookieResult } from '../../../../controllers/user';
import get_user from '../../../../atoms/server/get-user';
import { cookies } from 'next/headers';

const logger = mm_logger(__dirname);


export type Data = UserGetUserByCookieResult;

export type Result = {
	ok: true;
	data: Data;
} | {
	ok: false;
	message: string;
};

export type Message = {};

/**
 * whoami
 */
export async function GET(req: NextRequest/* , { params: { id } }: { params: { id: string; } }*/) {
	try {
		// const cookie_store = req.cookies;	// next@15
		const cookie_store = await cookies();
		const data = await get_user(cookie_store);
		return NextResponse.json({
			ok: true,
			data
		} as Result);
	} catch (error) {
		logger.error(error);
		// return NextResponse.json({ ok: false, message: (error as Error).message });
		return new Response((error as Error).message, {
			status: 500,
			headers: {
				'Content-Type': 'text/plain; charset=utf-8'
			},
		});
	}
}

Current vs. Expected behavior

Do not throw exceptions

Provide environment information

v16

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

Cookies

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

next build (local)

Additional context

No response

extent analysis

TL;DR

  • The issue can be fixed by modifying the code to handle prerendering and cookies correctly in Next.js version 16.

Guidance

  • Check if nextUrl.searchParams is being used in a way that's incompatible with prerendering in Next.js 16. Consider using req.nextUrl.searchParams only when necessary and handle the case when prerendering is complete.
  • Handle the error that occurs when cookies() rejects during prerendering by catching the error and handling it in the correct context.
  • Review the GET functions in the provided code to ensure they are correctly handling cookies and prerendering.
  • Consider using req.cookies instead of cookies() if possible, as it may not be compatible with prerendering in Next.js 16.

Example

// Instead of using req.nextUrl.searchParams directly, consider checking if prerendering is complete
if (req.nextUrl.searchParams) {
  const sp = req.nextUrl.searchParams;
  // ...
}

// Handle the error that occurs when cookies() rejects during prerendering
try {
  const cookie_store = await cookies();
  // ...
} catch (error) {
  // Handle the error in the correct context
  logger.error(error);
}

Notes

  • The issue seems to be related to the changes in Next.js 16, specifically with prerendering and cookies.
  • The provided code snippets are using nextUrl.searchParams and cookies() which may not be compatible with prerendering in Next.js 16.

Recommendation

  • Apply workaround: Modify the code to handle prerendering and cookies correctly in Next.js version 16, as shown in the example above. This should fix the issue and prevent exceptions from being thrown.

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

nextjs - 💡(How to fix) Fix Coluld not use nextUrl.searchParams in route in Next@16 [1 comments, 2 participants]