Skip to content

fix: preserve original path after middleware rewrite #2177

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cypress/e2e/middleware/standard.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ describe('Standard middleware', () => {
expect(response.headers).to.have.property('x-foo', 'bar')
})
})

it('preserves locale on rewrites (skipMiddlewareUrlNormalize: true)', () => {
cy.visit('/de-de/locale-preserving-rewrite')
cy.get('div').should('contain', 'Locale: de-DE')
cy.url().should('eq', `${Cypress.config().baseUrl}/de-de/locale-preserving-rewrite`)
})
})

describe('Middleware matchers', () => {
Expand Down
12 changes: 10 additions & 2 deletions demos/middleware/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ export async function middleware(req: NextRequest) {
}

const request = new MiddlewareRequest(req)
if (pathname.startsWith('/static')) {

// skipMiddlewareUrlNormalize next config option is used so we have to try to match both html path and data blob path
if (pathname.startsWith('/static') || pathname.endsWith('/static.json')) {
// Unlike NextResponse.next(), this actually sends the request to the origin
const res = await request.next()
const message = `This was static (& escaping test &) but has been transformed in ${req.geo?.city}`
Expand All @@ -36,7 +38,8 @@ export async function middleware(req: NextRequest) {
return res
}

if (pathname.startsWith('/request-rewrite')) {
// 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.
const res = await request.rewrite('/static-rewrite')
const message = `This was static (& escaping test &) but has been transformed in ${req.geo?.city}`
Expand Down Expand Up @@ -100,6 +103,10 @@ export async function middleware(req: NextRequest) {
return response
}

if (pathname.includes('locale-preserving-rewrite')) {
return NextResponse.rewrite(new URL('/locale-test', req.url))
}

if (pathname.startsWith('/shows')) {
if (pathname.startsWith('/shows/222')) {
response = NextResponse.next()
Expand Down Expand Up @@ -151,6 +158,7 @@ export const config = {
matcher: [
'/api/:all*',
'/headers',
'/:all*/locale-preserving-rewrite',
'/cookies/:path*',
{ source: '/static' },
{source: '/request-rewrite' },
Expand Down
1 change: 1 addition & 0 deletions demos/middleware/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const nextConfig = {
defaultLocale: 'en',
locales: ['en', 'de-DE'],
},
skipMiddlewareUrlNormalize: true,
}

module.exports = nextConfig
15 changes: 15 additions & 0 deletions demos/middleware/pages/locale-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as React from 'react'

const Page = ({ pageLocale }) => {
return <div>Locale: {pageLocale}</div>
}

export async function getServerSideProps({ locale }) {
return {
props: {
pageLocale: locale,
},
}
}

export default Page
3 changes: 3 additions & 0 deletions packages/runtime/src/templates/edge-shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,9 @@ export const buildResponse = async ({
}
res.headers.set('x-middleware-rewrite', relativeUrl)

request.headers.set('x-original-path', new URL(request.url, `http://n`).pathname)
request.headers.set('x-middleware-rewrite', rewrite)

return addMiddlewareHeaders(context.rewrite(rewrite), res)
}

Expand Down
7 changes: 7 additions & 0 deletions packages/runtime/src/templates/handlerUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,13 @@ export const normalizePath = (event: HandlerEvent) => {
return originalPath
}
}

if (event.headers['x-original-path']) {
if (event.headers['x-next-debug-logging']) {
console.log('Original path:', event.headers['x-original-path'])
}
return event.headers['x-original-path']
}
// Ensure that paths are encoded - but don't double-encode them
return new URL(event.rawUrl).pathname
}
Expand Down
9 changes: 8 additions & 1 deletion packages/runtime/src/templates/server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { PrerenderManifest } from 'next/dist/build'
// eslint-disable-next-line n/no-deprecated-api -- this is what Next.js uses as well
import { parse } from 'url'

import type { PrerenderManifest } from 'next/dist/build'
import type { BaseNextResponse } from 'next/dist/server/base-http'
import type { NodeRequestHandler, Options } from 'next/dist/server/next-server'

Expand Down Expand Up @@ -36,6 +39,10 @@ const getNetlifyNextServer = (NextServer: NextServerType) => {
public getRequestHandler(): NodeRequestHandler {
const handler = super.getRequestHandler()
return async (req, res, parsedUrl) => {
if (!parsedUrl && typeof req?.headers?.['x-middleware-rewrite'] === 'string') {
parsedUrl = parse(req.headers['x-middleware-rewrite'], true)
}

Comment on lines +42 to +45
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Next does same parsing in https://github.com/vercel/next.js/blob/7dfa56c7141ae2556af0d7fd837e0af686d8fa55/packages/next/src/server/base-server.ts#L662-L665 and later on does a lot of checking on it and potentially messing with it.

Passing parsedUrl along the request handler route allows some control

// preserve the URL before Next.js mutates it for i18n
const { url, headers } = req

Expand Down