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

Ensure custom middleware matcher is used correctly in client manifest (#37672)

* Ensure custom middleware matcher is used correctly in client manifest

* lint-fix

* patch e2e case

* fix rsc case

* update test

* add missing normalize
parent 5211ac5c
......@@ -4,7 +4,6 @@ import { tryToExtractExportedConstValue } from './extract-const-value'
import { parseModule } from './parse-module'
import { promises as fs } from 'fs'
import { tryToParsePath } from '../../lib/try-to-parse-path'
import { isMiddlewareFile } from '../utils'
import * as Log from '../output/log'
interface MiddlewareConfig {
......@@ -50,8 +49,7 @@ export async function getPageStaticInfo(params: {
runtime = 'edge'
}
const middlewareConfig =
isMiddlewareFile(params.page!) && getMiddlewareConfig(config)
const middlewareConfig = getMiddlewareConfig(config)
return {
ssr,
......@@ -163,6 +161,8 @@ function getMiddlewareRegExpStrings(matcherOrMatchers: unknown): string[] {
throw new Error(`Invalid path matcher: ${matcher}`)
}
// TODO: is the dataMatcher still needed now that we normalize this
// away while resolving routes
const dataMatcher = `/_next/data/:__nextjsBuildId__${matcher}.json`
const parsedDataRoute = tryToParsePath(dataMatcher)
......
......@@ -465,7 +465,7 @@ function getCreateAssets(params: {
middlewareManifest.clientInfo = middlewareManifest.sortedMiddleware.map(
(key) => [
key,
middlewareManifest.middleware[key].regexp,
!!metadataByEntry.get(middlewareManifest.middleware[key].name)?.edgeSSR,
]
)
......
......@@ -529,6 +529,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
let matcherParams = utils.dynamicRouteMatcher?.(normalizedUrlPath)
if (matcherParams) {
utils.normalizeDynamicRouteParams(matcherParams)
Object.assign(paramsResult.params, matcherParams)
paramsResult.hasValidParams = true
}
......
......@@ -323,7 +323,8 @@ export default class DevServer extends Server {
if (isMiddlewareFile(rootFile)) {
this.actualMiddlewareFile = rootFile
middlewareMatcher = staticInfo.middleware?.pathMatcher
middlewareMatcher =
staticInfo.middleware?.pathMatcher || new RegExp('.*')
routedMiddleware.push('/')
continue
}
......@@ -391,6 +392,7 @@ export default class DevServer extends Server {
})
),
page,
re: middlewareMatcher,
ssr: ssrMiddleware.has(page),
}
})
......@@ -911,7 +913,7 @@ export default class DevServer extends Server {
.body(
JSON.stringify(
this.getMiddleware().map((middleware) => [
middleware.page,
(middleware as any).re.source,
!!middleware.ssr,
])
)
......
......@@ -35,7 +35,7 @@ import { parseRelativeUrl } from './utils/parse-relative-url'
import { searchParamsToUrlQuery } from './utils/querystring'
import resolveRewrites from './utils/resolve-rewrites'
import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex, getMiddlewareRegex } from './utils/route-regex'
import { getRouteRegex } from './utils/route-regex'
import { formatWithValidation } from './utils/format-url'
import { detectDomainLocale } from '../../../client/detect-domain-locale'
import { parsePath } from './utils/parse-path'
......@@ -385,6 +385,7 @@ export type CompletePrivateRouteInfo = {
props?: Record<string, any>
err?: Error
error?: any
route?: string
}
export type AppProps = Pick<CompletePrivateRouteInfo, 'Component' | 'err'> & {
......@@ -1186,14 +1187,13 @@ export default class Router implements BaseRouter {
`\nSee more info: https://nextjs.org/docs/messages/invalid-relative-url-external-as`
)
}
window.location.href = as
return false
}
resolvedAs = removeLocale(removeBasePath(resolvedAs), nextState.locale)
const route = removeTrailingSlash(pathname)
let route = removeTrailingSlash(pathname)
if (!isMiddlewareMatch && isDynamicRoute(route)) {
const parsedAs = parseRelativeUrl(resolvedAs)
......@@ -1265,6 +1265,10 @@ export default class Router implements BaseRouter {
isPreview: nextState.isPreview,
})
if ('route' in routeInfo) {
pathname = routeInfo.route || route
}
// If the routeInfo brings a redirect we simply apply it.
if ('type' in routeInfo) {
if (routeInfo.type === 'redirect-internal') {
......@@ -1314,7 +1318,6 @@ export default class Router implements BaseRouter {
)
return this.change(method, newUrl, newAs, options)
}
window.location.href = destination
return new Promise(() => {})
}
......@@ -1742,6 +1745,7 @@ export default class Router implements BaseRouter {
}
routeInfo.props = props
routeInfo.route = route
this.components[route] = routeInfo
return routeInfo
} catch (err) {
......@@ -2109,19 +2113,15 @@ function matchesMiddleware<T extends FetchDataOutput>(
options: MiddlewareEffectParams<T>
): Promise<boolean> {
return Promise.resolve(options.router.pageLoader.getMiddlewareList()).then(
(fns) => {
(items) => {
const { pathname: asPathname } = parsePath(options.asPath)
const cleanedAs = removeLocale(
hasBasePath(asPathname) ? removeBasePath(asPathname) : asPathname,
options.locale
)
return fns.some(([middleware, isSSR]) => {
return getRouteMatcher(
getMiddlewareRegex(middleware, {
catchAll: !isSSR,
})
)(cleanedAs)
return items?.some(([regex]) => {
return new RegExp(regex).test(cleanedAs)
})
}
)
......@@ -2170,7 +2170,15 @@ function getMiddlewareData<T extends FetchDataOutput>(
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
}
const rewriteTarget = response.headers.get('x-nextjs-matched-path')
// TODO: ensure x-nextjs-matched-path is always present instead of both
// variants
let rewriteTarget = response.headers.get('x-nextjs-matched-path')
const matchedPath = response.headers.get('x-matched-path')
if (!rewriteTarget && !matchedPath?.includes('__next_data_catchall')) {
rewriteTarget = matchedPath
}
if (rewriteTarget) {
if (rewriteTarget.startsWith('/')) {
......
......@@ -118,7 +118,6 @@ describe('Middleware Runtime', () => {
})
}
// TODO: re-enable after fixing server-side resolving priority
it('should redirect the same for direct visit and client-transition', async () => {
const res = await fetchViaHTTP(
next.url,
......@@ -141,7 +140,6 @@ describe('Middleware Runtime', () => {
}, 'success')
})
// TODO: re-enable after fixing server-side resolving priority
it('should rewrite the same for direct visit and client-transition', async () => {
const res = await fetchViaHTTP(next.url, `${locale}/rewrite-1`)
expect(res.status).toBe(200)
......
import { NextResponse } from 'next/server'
export const config = {
matcher: ['/with-middleware/:path*', '/another-middleware/:path*'],
}
export default (req) => {
const res = NextResponse.next()
res.headers.set('X-From-Middleware', 'true')
return res
}
import Link from 'next/link'
export default function Page(props) {
return (
<div>
<p id="another-middleware">This should also run the middleware</p>
<p id="props">{JSON.stringify(props)}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</div>
)
}
export const getServerSideProps = () => {
return {
props: {
message: 'Hello, magnificent world.',
},
}
}
import Link from 'next/link'
export default function Page(props) {
return (
<div>
<p id="blog">This should not run the middleware</p>
<p id="props">{JSON.stringify(props)}</p>
<Link href="/another-middleware">
<a id="to-another-middleware">to /another-middleware</a>
</Link>
<br />
<Link href="/blog/slug-2">
<a id="to-blog-slug-2">to /blog/slug-2</a>
</Link>
<br />
</div>
)
}
export const getServerSideProps = ({ params }) => {
return {
props: {
params,
message: 'Hello, magnificent world.',
},
}
}
import Link from 'next/link'
export default function Page(props) {
return (
<div>
<p id="index">root page</p>
<p id="props">{JSON.stringify(props)}</p>
<Link href="/another-middleware">
<a id="to-another-middleware">to /another-middleware</a>
</Link>
<br />
<Link href="/blog/slug-1">
<a id="to-blog-slug-1">to /blog/slug-1</a>
</Link>
<br />
</div>
)
}
export const getServerSideProps = () => {
return {
props: {
message: 'Hello, world.',
},
}
}
export default function Page({ message }) {
return (
<div>
<p>This should run the middleware</p>
<p>{message}</p>
</div>
)
}
export const getServerSideProps = () => {
return {
props: {
message: 'Hello, cruel world.',
},
}
}
import { createNext } from 'e2e-utils'
import { createNext, FileRef } from 'e2e-utils'
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 webdriver from 'next-webdriver'
describe('Middleware can set the matcher in its config', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/index.js': `
export default function Page({ message }) {
return <div>
<p>root page</p>
<p>{message}</p>
</div>
}
export const getServerSideProps = () => {
return {
props: {
message: "Hello, world."
}
}
}
`,
'pages/with-middleware/index.js': `
export default function Page({ message }) {
return <div>
<p>This should run the middleware</p>
<p>{message}</p>
</div>
}
export const getServerSideProps = () => {
return {
props: {
message: "Hello, cruel world."
}
}
}
`,
'pages/another-middleware/index.js': `
export default function Page({ message }) {
return <div>
<p>This should also run the middleware</p>
<p>{message}</p>
</div>
}
export const getServerSideProps = () => {
return {
props: {
message: "Hello, magnificent world."
}
}
}
`,
'middleware.js': `
import { NextResponse } from 'next/server'
export const config = {
matcher: ['/with-middleware/:path*', '/another-middleware/:path*']
};
export default (req) => {
const res = NextResponse.next();
res.headers.set('X-From-Middleware', 'true');
return res;
}
`,
},
files: new FileRef(join(__dirname, 'app')),
dependencies: {},
})
})
......@@ -131,6 +73,60 @@ describe('Middleware can set the matcher in its config', () => {
})
expect(response.headers.get('X-From-Middleware')).toBeNull()
})
it('should load matches in client manifest correctly', async () => {
const browser = await webdriver(next.url, '/')
await check(async () => {
const manifest = await browser.eval(
(global as any).isNextDev
? 'window.__DEV_MIDDLEWARE_MANIFEST'
: 'window.__MIDDLEWARE_MANIFEST'
)
return Array.isArray(manifest) &&
manifest?.[0]?.[0].includes('with-middleware') &&
manifest?.[0]?.[0].includes('another-middleware')
? 'success'
: manifest
}, 'success')
})
it('should navigate correctly with matchers', async () => {
const browser = await webdriver(next.url, '/')
await browser.eval('window.beforeNav = 1')
await browser.elementByCss('#to-another-middleware').click()
await browser.waitForElementByCss('#another-middleware')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
message: 'Hello, magnificent world.',
})
await browser.elementByCss('#to-index').click()
await browser.waitForElementByCss('#index')
await browser.elementByCss('#to-blog-slug-1').click()
await browser.waitForElementByCss('#blog')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
message: 'Hello, magnificent world.',
params: {
slug: 'slug-1',
},
})
await browser.elementByCss('#to-blog-slug-2').click()
await check(
() => browser.eval('document.documentElement.innerHTML'),
/"slug":"slug-2"/
)
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
message: 'Hello, magnificent world.',
params: {
slug: 'slug-2',
},
})
})
})
describe('using a single matcher', () => {
......@@ -170,6 +166,7 @@ describe('using a single matcher', () => {
})
})
afterAll(() => next.destroy())
it('adds the header for a matched path', async () => {
const response = await fetchViaHTTP(next.url, '/middleware/works')
expect(await response.text()).toContain('Hello from /middleware/works')
......
......@@ -115,7 +115,13 @@ const edgeRuntimeBasicSuite = {
['/next-api/link', true],
['/routes/[dynamic]', true],
]) {
expect(content.clientInfo).toContainEqual(item)
expect(
content.clientInfo.some((infoItem) => {
return (
item[1] === infoItem[1] && new RegExp(infoItem[0]).test(item[0])
)
})
).toBe(true)
}
expect(content.clientInfo).not.toContainEqual([['/404', true]])
})
......
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