diff --git a/cypress/e2e/middleware/standard.cy.ts b/cypress/e2e/middleware/standard.cy.ts index 4992e0186c..79d9630532 100644 --- a/cypress/e2e/middleware/standard.cy.ts +++ b/cypress/e2e/middleware/standard.cy.ts @@ -24,6 +24,13 @@ describe('Standard middleware', () => { cy.url().should('eq', `${Cypress.config().baseUrl}/shows/rewrite-external`) }) + it('doesnt follow redirects from rewritten page', () => { + cy.request({ url: '/rewrite-to-redirect', followRedirect: false }).then((response) => { + expect(response.status).to.eq(302) + expect(response.redirectedToUrl).to.eq('https://example.com/') + }) + }) + it('adds headers to static pages', () => { cy.request('/shows/static/3').then((response) => { expect(response.headers).to.have.property('x-middleware-date') diff --git a/demos/middleware/middleware.ts b/demos/middleware/middleware.ts index 04f894b042..1b1805ea95 100644 --- a/demos/middleware/middleware.ts +++ b/demos/middleware/middleware.ts @@ -38,6 +38,10 @@ export async function middleware(req: NextRequest) { return res } + if (pathname.startsWith("/rewrite-to-redirect")) { + return NextResponse.rewrite('https://httpbin.org/redirect-to?url=https://example.com') + } + // skipMiddlewareUrlNormalize next config option is used so we have to try to match both html path and data blob path if (pathname.startsWith('/request-rewrite') || pathname.endsWith('/request-rewrite.json')) { // request.rewrite() should return the MiddlewareResponse object instead of the Response object. @@ -174,6 +178,7 @@ export const config = { '/cookies/:path*', { source: '/static' }, { source: '/request-rewrite' }, + { source: '/rewrite-to-redirect' }, { source: '/matcher-cookie' }, { source: '/shows/((?!99|88).*)' }, { diff --git a/packages/runtime/src/templates/edge-shared/utils.ts b/packages/runtime/src/templates/edge-shared/utils.ts index 70a2752192..7890addaad 100644 --- a/packages/runtime/src/templates/edge-shared/utils.ts +++ b/packages/runtime/src/templates/edge-shared/utils.ts @@ -265,7 +265,7 @@ export const buildResponse = async ({ } if (rewriteUrl.hostname !== baseUrl.hostname) { // Netlify Edge Functions don't support proxying to external domains, but Next middleware does - const proxied = fetch(new Request(rewriteUrl.toString(), request)) + const proxied = fetch(new Request(rewriteUrl.toString(), request), { redirect: 'manual' }) return addMiddlewareHeaders(proxied, res) } res.headers.set('x-middleware-rewrite', relativeUrl)