diff --git a/.changeset/seven-socks-roll.md b/.changeset/seven-socks-roll.md new file mode 100644 index 000000000..e8bacce7b --- /dev/null +++ b/.changeset/seven-socks-roll.md @@ -0,0 +1,5 @@ +--- +'@cloudflare/next-on-pages': patch +--- + +Fix middleware redirects not always bailing out of the routing stages. diff --git a/packages/next-on-pages/templates/_worker.js/routes-matcher.ts b/packages/next-on-pages/templates/_worker.js/routes-matcher.ts index 76921a515..69f74197d 100644 --- a/packages/next-on-pages/templates/_worker.js/routes-matcher.ts +++ b/packages/next-on-pages/templates/_worker.js/routes-matcher.ts @@ -453,8 +453,10 @@ export class RoutesMatcher { // Call and process the middleware if this is a middleware route. const success = await this.runRouteMiddleware(route.middlewarePath); if (!success) return 'error'; - // If the middleware set a response body, we are done. - if (this.body !== undefined) return 'done'; + // If the middleware set a response body or resulted in a redirect, we are done. + if (this.body !== undefined || this.headers.middlewareLocation) { + return 'done'; + } // Update final headers with the ones from this route. this.applyRouteHeaders(route, srcMatch, captureGroupKeys); diff --git a/packages/next-on-pages/tests/templates/requestTestData/middleware.ts b/packages/next-on-pages/tests/templates/requestTestData/middleware.ts index b693ceb6a..fe3832510 100644 --- a/packages/next-on-pages/tests/templates/requestTestData/middleware.ts +++ b/packages/next-on-pages/tests/templates/requestTestData/middleware.ts @@ -27,6 +27,14 @@ const rawVercelConfig: VercelConfig = { middlewareRawSrc: ['/:nextData(_next/data/[^/]{1,})?/api/:path*(.json)?'], override: true, }, + { + src: '^/((?!.+\\.rsc).+?)(?:/)?$', + has: [{ type: 'header', key: 'rsc' }], + dest: '/$1.rsc', + headers: { vary: 'RSC, Next-Router-State-Tree, Next-Router-Prefetch' }, + continue: true, + override: true, + }, { handle: 'resource' }, { src: '/.*', status: 404 }, { handle: 'hit' }, @@ -109,6 +117,18 @@ export const testSet: TestSet = { }, }, }, + { + name: 'middleware route returns redirect when a later matching config rule would be an override', + paths: ['/api/hello?redirect'], + headers: { rsc: '1' }, + expected: { + status: 307, + data: '', + headers: { + location: 'http://localhost/somewhere-else', + }, + }, + }, { name: 'middleware route applies rewrite for `NextResponse.rewrite()`', paths: ['/api/hello?rewrite'],