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

Update middleware prefetch handling (#45772)

When doing external rewrites with middleware we shouldn't bail for the
prefetch case as this is valid and the bailing can occur on the
destination application.

x-ref: [slack
thread](https://vercel.slack.com/archives/C01RGMANU9Y/p1675754630039439)

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)
parent db2e9b28
......@@ -306,6 +306,9 @@ export function getDefineEnv({
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE': JSON.stringify(
config.skipMiddlewareUrlNormalize
),
'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE': JSON.stringify(
config.experimental.externalMiddlewareRewritesResolve
),
'process.env.__NEXT_MANUAL_TRAILING_SLASH': JSON.stringify(
config.skipTrailingSlashRedirect
),
......
......@@ -278,6 +278,9 @@ const configSchema = {
externalDir: {
type: 'boolean',
},
externalMiddlewareRewritesResolve: {
type: 'boolean',
},
fallbackNodePolyfills: {
type: 'boolean',
},
......
......@@ -113,6 +113,7 @@ export interface NextJsWebpackConfig {
}
export interface ExperimentalConfig {
externalMiddlewareRewritesResolve?: boolean
extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[]
fetchCache?: boolean
......
......@@ -1993,14 +1993,6 @@ export default class NextNodeServer extends BaseServer {
? `${parsedDestination.hostname}:${parsedDestination.port}`
: parsedDestination.hostname) !== req.headers.host
) {
// when we are handling a middleware prefetch and it doesn't
// resolve to a static data route we bail early to avoid
// unexpected SSR invocations
if (req.headers['x-middleware-prefetch']) {
res.setHeader('x-middleware-skip', '1')
res.body('{}').send()
return { finished: true }
}
return this.proxyRequest(
req as NodeNextRequest,
res as NodeNextResponse,
......
......@@ -194,7 +194,10 @@ function getMiddlewareData<T extends FetchDataOutput>(
}
if (rewriteTarget) {
if (rewriteTarget.startsWith('/')) {
if (
rewriteTarget.startsWith('/') ||
process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE
) {
const parsedRewriteTarget = parseRelativeUrl(rewriteTarget)
const pathnameInfo = getNextPathnameInfo(parsedRewriteTarget.pathname, {
nextConfig,
......@@ -270,7 +273,6 @@ function getMiddlewareData<T extends FetchDataOutput>(
}
})
}
const src = parsePath(source)
const pathname = formatNextPathnameInfo({
...getNextPathnameInfo(src.pathname, { nextConfig, parseData: true }),
......
......@@ -2,6 +2,17 @@ import { NextResponse } from 'next/server'
export default function handler(req) {
console.log(req.nextUrl)
let { pathname } = req.nextUrl
if (pathname.includes('docs') || pathname.includes('chained-rewrite')) {
if (pathname === '/docs') {
pathname = '/'
}
return NextResponse.rewrite(
`https://middleware-external-rewrite-target-epsp8idgo-uncurated-tests.vercel.app${pathname}`
)
}
if (req.nextUrl.pathname.startsWith('/_next/data/missing-id')) {
console.log(`missing-id rewrite: ${req.nextUrl.toString()}`)
......
......@@ -2,6 +2,7 @@ import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { check, fetchViaHTTP } from 'next-test-utils'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
describe('skip-trailing-slash-redirect', () => {
......@@ -15,6 +16,54 @@ describe('skip-trailing-slash-redirect', () => {
})
afterAll(() => next.destroy())
it.each([
{ pathname: '/chained-rewrite-ssg' },
{ pathname: '/chained-rewrite-static' },
{ pathname: '/chained-rewrite-ssr' },
{ pathname: '/docs/first' },
{ pathname: '/docs-auto-static/first' },
{ pathname: '/docs-ssr/first' },
])(
'should handle external rewrite correctly $pathname',
async ({ pathname }) => {
const res = await fetchViaHTTP(next.url, pathname, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
if (!pathname.includes('static')) {
expect(JSON.parse($('#props').text()).params).toEqual({
slug: 'first',
})
expect(JSON.parse($('#query').text())).toEqual({
slug: 'first',
})
}
const browser = await webdriver(next.url, '/docs', {
waitHydration: false,
})
await check(
() => browser.eval('next.router.isReady ? "yes": "no"'),
'yes'
)
await check(() => browser.elementByCss('#mounted').text(), 'yes')
await browser.eval('window.beforeNav = 1')
await browser.elementByCss(`#${pathname.replace(/\//g, '')}`).click()
await check(async () => {
const query = JSON.parse(await browser.elementByCss('#query').text())
expect(query).toEqual({ slug: 'first' })
return 'success'
}, 'success')
expect(await browser.eval('window.beforeNav')).toBe(1)
}
)
it('should allow rewriting invalid buildId correctly', async () => {
const res = await fetchViaHTTP(
next.url,
......
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