Unverified Commit 77771303 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix middleware URL normalize case (#41342)

Follow-up to https://github.com/vercel/next.js/pull/41341 this fixes a
related issue with the URL normalizing in middleware and updates the
regression tests.

x-ref: [slack
thread](https://vercel.slack.com/archives/C01224Q5M99/p1665161421775079?thread_ts=1664536480.045539&cid=C01224Q5M99)

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`
parent c1de0c0c
...@@ -1724,15 +1724,21 @@ export default class NextNodeServer extends BaseServer { ...@@ -1724,15 +1724,21 @@ export default class NextNodeServer extends BaseServer {
} }
const normalizedPathname = removeTrailingSlash(params.parsed.pathname || '') const normalizedPathname = removeTrailingSlash(params.parsed.pathname || '')
// For middleware to "fetch" we must always provide an absolute URL let url: string
const query = urlQueryToSearchParams(params.parsed.query).toString()
const locale = params.parsed.query.__nextLocale if (this.nextConfig.experimental.skipMiddlewareUrlNormalize) {
url = getRequestMeta(params.request, '__NEXT_INIT_URL')!
const url = `${getRequestMeta(params.request, '_protocol')}://${ } else {
this.hostname // For middleware to "fetch" we must always provide an absolute URL
}:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${ const query = urlQueryToSearchParams(params.parsed.query).toString()
query ? `?${query}` : '' const locale = params.parsed.query.__nextLocale
}`
url = `${getRequestMeta(params.request, '_protocol')}://${
this.hostname
}:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${
query ? `?${query}` : ''
}`
}
if (!url.startsWith('http')) { if (!url.startsWith('http')) {
throw new Error( throw new Error(
......
...@@ -72,7 +72,7 @@ export class NextURL { ...@@ -72,7 +72,7 @@ export class NextURL {
private analyzeUrl() { private analyzeUrl() {
const pathnameInfo = getNextPathnameInfo(this[Internal].url.pathname, { const pathnameInfo = getNextPathnameInfo(this[Internal].url.pathname, {
nextConfig: this[Internal].options.nextConfig, nextConfig: this[Internal].options.nextConfig,
parseData: true, parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,
}) })
this[Internal].domainLocale = detectDomainLocale( this[Internal].domainLocale = detectDomainLocale(
......
...@@ -13,11 +13,6 @@ export async function middleware(request) { ...@@ -13,11 +13,6 @@ export async function middleware(request) {
return NextResponse.next() return NextResponse.next()
} }
if (url.pathname.startsWith('/_next/data/missing-id')) {
console.log(`missing-id rewrite: ${url.toString()}`)
return NextResponse.rewrite('https://example.vercel.sh')
}
if (url.pathname.includes('/to/some/404/path')) { if (url.pathname.includes('/to/some/404/path')) {
return NextResponse.next({ return NextResponse.next({
'x-matched-path': '/404', 'x-matched-path': '/404',
......
...@@ -23,23 +23,6 @@ describe('Middleware Rewrite', () => { ...@@ -23,23 +23,6 @@ describe('Middleware Rewrite', () => {
}) })
function tests() { function tests() {
it('should allow rewriting invalid buildId correctly', async () => {
const res = await fetchViaHTTP(
next.url,
'/_next/data/missing-id/hello.json',
undefined,
{
headers: {
'x-nextjs-data': '1',
},
}
)
expect(res.status).toBe(200)
expect(await res.text()).toContain('Example Domain')
await check(() => next.cliOutput, /missing-id rewrite/)
expect(next.cliOutput).toContain('/_next/data/missing-id/hello.json')
})
it('should not have un-necessary data request on rewrite', async () => { it('should not have un-necessary data request on rewrite', async () => {
const browser = await webdriver(next.url, '/to-blog/first', { const browser = await webdriver(next.url, '/to-blog/first', {
waitHydration: false, waitHydration: false,
......
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export default function handler(req) { export default function handler(req) {
if (req.nextUrl.pathname.startsWith('/_next/data/missing-id')) {
console.log(`missing-id rewrite: ${req.nextUrl.toString()}`)
return NextResponse.rewrite('https://example.vercel.sh')
}
if (req.nextUrl.pathname === '/middleware-rewrite-with-slash') { if (req.nextUrl.pathname === '/middleware-rewrite-with-slash') {
return NextResponse.rewrite(new URL('/another/', req.nextUrl)) return NextResponse.rewrite(new URL('/another/', req.nextUrl))
} }
......
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base' import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP } from 'next-test-utils' import { check, fetchViaHTTP } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
...@@ -15,6 +15,26 @@ describe('skip-trailing-slash-redirect', () => { ...@@ -15,6 +15,26 @@ describe('skip-trailing-slash-redirect', () => {
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
it('should allow rewriting invalid buildId correctly', async () => {
const res = await fetchViaHTTP(
next.url,
'/_next/data/missing-id/hello.json',
undefined,
{
headers: {
'x-nextjs-data': '1',
},
}
)
expect(res.status).toBe(200)
expect(await res.text()).toContain('Example Domain')
if (!(global as any).isNextDeploy) {
await check(() => next.cliOutput, /missing-id rewrite/)
expect(next.cliOutput).toContain('/_next/data/missing-id/hello.json')
}
})
it('should allow response body from middleware with flag', async () => { it('should allow response body from middleware with flag', async () => {
const res = await fetchViaHTTP(next.url, '/middleware-response-body') const res = await fetchViaHTTP(next.url, '/middleware-response-body')
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment