Skip to content

Commit

Permalink
fix: middleware redirect not always bailing out of routing (#386)
Browse files Browse the repository at this point in the history
  • Loading branch information
james-elicx authored Jul 19, 2023
1 parent ef63ae2 commit 6c28128
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/seven-socks-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@cloudflare/next-on-pages': patch
---

Fix middleware redirects not always bailing out of the routing stages.
6 changes: 4 additions & 2 deletions packages/next-on-pages/templates/_worker.js/routes-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down Expand Up @@ -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'],
Expand Down

0 comments on commit 6c28128

Please sign in to comment.