diff --git a/packages/next/src/client/index.tsx b/packages/next/src/client/index.tsx index e7e44ffbef9ab..f5de8b2adcf53 100644 --- a/packages/next/src/client/index.tsx +++ b/packages/next/src/client/index.tsx @@ -928,7 +928,15 @@ export async function hydrate(opts?: { beforeRender?: () => Promise }) { // In development, error the navigation API usage in runtime, // since it's not allowed to be used in pages router as it doesn't contain error boundary like app router. - if (isNextRouterError(initialErr)) { + if ( + isNextRouterError(initialErr) && + !initialErr.message.includes( + 'Next.js navigation API is not allowed to be used in Middleware' + ) && + !initialErr.message.includes( + 'Next.js navigation API is not allowed to be used in Proxy' + ) + ) { error.message = 'Next.js navigation API is not allowed to be used in Pages Router.' } diff --git a/test/development/app-dir/server-navigation-error/proxy.ts b/test/development/app-dir/server-navigation-error/proxy.ts new file mode 100644 index 0000000000000..6cec7fdf0db1f --- /dev/null +++ b/test/development/app-dir/server-navigation-error/proxy.ts @@ -0,0 +1,10 @@ +import { notFound, redirect } from 'next/navigation' +import { NextRequest } from 'next/server' + +export default function proxy(req: NextRequest) { + if (req.nextUrl.pathname === '/proxy/not-found') { + notFound() + } else if (req.nextUrl.pathname === '/proxy/redirect') { + redirect('/') + } +} diff --git a/test/development/app-dir/server-navigation-error/server-navigation-error.test.ts b/test/development/app-dir/server-navigation-error/server-navigation-error.test.ts index c7d2cf31d1d33..02f097fc18c7b 100644 --- a/test/development/app-dir/server-navigation-error/server-navigation-error.test.ts +++ b/test/development/app-dir/server-navigation-error/server-navigation-error.test.ts @@ -82,4 +82,44 @@ describe('server-navigation-error', () => { `) }) }) + + describe('proxy', () => { + it('should error on navigation API redirect ', async () => { + const browser = await next.browser('/proxy/redirect') + // FIXME: the first request to middleware error load didn't show the redbox, need one more reload + await browser.refresh() + + await expect(browser).toDisplayRedbox(` + { + "description": "Next.js navigation API is not allowed to be used in Proxy.", + "environmentLabel": null, + "label": "Runtime Error", + "source": "proxy.ts (8:13) @ proxy + > 8 | redirect('/') + | ^", + "stack": [ + "proxy proxy.ts (8:13)", + ], + } + `) + }) + + it('should error on navigation API not-found', async () => { + const browser = await next.browser('/proxy/not-found') + + await expect(browser).toDisplayRedbox(` + { + "description": "Next.js navigation API is not allowed to be used in Proxy.", + "environmentLabel": null, + "label": "Runtime Error", + "source": "proxy.ts (6:13) @ proxy + > 6 | notFound() + | ^", + "stack": [ + "proxy proxy.ts (6:13)", + ], + } + `) + }) + }) })