Unverified Commit 582cb376 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix: only contain middleware in dev middleware manifest (#39217)

x-ref #39199

The change in #39199 isn't correct. Middleware manifest should only contain middleware route, so that when router navigates, it only try to apply middleware instead of checking all edge routes. This PR also changes the middleware manifest global value from array to object for easier access

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
parent f0df2c27
...@@ -11,7 +11,7 @@ import { createRouteLoader, getClientBuildManifest } from './route-loader' ...@@ -11,7 +11,7 @@ import { createRouteLoader, getClientBuildManifest } from './route-loader'
declare global { declare global {
interface Window { interface Window {
__DEV_MIDDLEWARE_MANIFEST?: [location: string, isSSR: boolean][] __DEV_MIDDLEWARE_MANIFEST?: { location?: string }
__DEV_PAGES_MANIFEST?: { pages: string[] } __DEV_PAGES_MANIFEST?: { pages: string[] }
__SSG_MANIFEST_CB?: () => void __SSG_MANIFEST_CB?: () => void
__SSG_MANIFEST?: Set<string> __SSG_MANIFEST?: Set<string>
...@@ -30,9 +30,7 @@ export default class PageLoader { ...@@ -30,9 +30,7 @@ export default class PageLoader {
private assetPrefix: string private assetPrefix: string
private promisedSsgManifest: Promise<Set<string>> private promisedSsgManifest: Promise<Set<string>>
private promisedDevPagesManifest?: Promise<string[]> private promisedDevPagesManifest?: Promise<string[]>
private promisedMiddlewareManifest?: Promise< private promisedMiddlewareManifest?: Promise<{ location: string }>
[location: string, isSSR: boolean][]
>
public routeLoader: RouteLoader public routeLoader: RouteLoader
...@@ -81,12 +79,12 @@ export default class PageLoader { ...@@ -81,12 +79,12 @@ export default class PageLoader {
} }
} }
getMiddlewareList() { getMiddleware() {
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
const middlewareRegex = process.env.__NEXT_MIDDLEWARE_REGEX const middlewareRegex = process.env.__NEXT_MIDDLEWARE_REGEX
window.__MIDDLEWARE_MANIFEST = middlewareRegex window.__MIDDLEWARE_MANIFEST = middlewareRegex
? [[middlewareRegex, false]] ? { location: middlewareRegex }
: [] : undefined
return window.__MIDDLEWARE_MANIFEST return window.__MIDDLEWARE_MANIFEST
} else { } else {
if (window.__DEV_MIDDLEWARE_MANIFEST) { if (window.__DEV_MIDDLEWARE_MANIFEST) {
...@@ -99,7 +97,7 @@ export default class PageLoader { ...@@ -99,7 +97,7 @@ export default class PageLoader {
`${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json` `${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json`
) )
.then((res) => res.json()) .then((res) => res.json())
.then((manifest: [location: string, isSSR: boolean][]) => { .then((manifest: { location?: string }) => {
window.__DEV_MIDDLEWARE_MANIFEST = manifest window.__DEV_MIDDLEWARE_MANIFEST = manifest
return manifest return manifest
}) })
......
...@@ -13,7 +13,7 @@ declare global { ...@@ -13,7 +13,7 @@ declare global {
interface Window { interface Window {
__BUILD_MANIFEST?: Record<string, string[]> __BUILD_MANIFEST?: Record<string, string[]>
__BUILD_MANIFEST_CB?: Function __BUILD_MANIFEST_CB?: Function
__MIDDLEWARE_MANIFEST?: [location: string, isSSR: boolean][] __MIDDLEWARE_MANIFEST?: { location: string }
__MIDDLEWARE_MANIFEST_CB?: Function __MIDDLEWARE_MANIFEST_CB?: Function
} }
} }
......
...@@ -964,15 +964,16 @@ export default class DevServer extends Server { ...@@ -964,15 +964,16 @@ export default class DevServer extends Server {
type: 'route', type: 'route',
name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`, name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`,
fn: async (_req, res) => { fn: async (_req, res) => {
const edgeRoutes = this.getEdgeFunctions().concat(
this.middleware ? [this.middleware] : []
)
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', 'application/json; charset=utf-8')
res res
.body( .body(
JSON.stringify( JSON.stringify(
edgeRoutes.map((edgeRoute) => [edgeRoute.re!.source]) this.middleware
? {
location: this.middleware.re!.source,
}
: {}
) )
) )
.send() .send()
......
...@@ -1159,7 +1159,7 @@ export default class Router implements BaseRouter { ...@@ -1159,7 +1159,7 @@ export default class Router implements BaseRouter {
;[pages, { __rewrites: rewrites }] = await Promise.all([ ;[pages, { __rewrites: rewrites }] = await Promise.all([
this.pageLoader.getPageList(), this.pageLoader.getPageList(),
getClientBuildManifest(), getClientBuildManifest(),
this.pageLoader.getMiddlewareList(), this.pageLoader.getMiddleware(),
]) ])
} catch (err) { } catch (err) {
// If we fail to resolve the page list or client-build manifest, we must // If we fail to resolve the page list or client-build manifest, we must
...@@ -2267,18 +2267,17 @@ interface MiddlewareEffectParams<T extends FetchDataOutput> { ...@@ -2267,18 +2267,17 @@ interface MiddlewareEffectParams<T extends FetchDataOutput> {
function matchesMiddleware<T extends FetchDataOutput>( function matchesMiddleware<T extends FetchDataOutput>(
options: MiddlewareEffectParams<T> options: MiddlewareEffectParams<T>
): Promise<boolean> { ): Promise<boolean> {
return Promise.resolve(options.router.pageLoader.getMiddlewareList()).then( return Promise.resolve(options.router.pageLoader.getMiddleware()).then(
(items) => { (middleware) => {
const { pathname: asPathname } = parsePath(options.asPath) const { pathname: asPathname } = parsePath(options.asPath)
const cleanedAs = hasBasePath(asPathname) const cleanedAs = hasBasePath(asPathname)
? removeBasePath(asPathname) ? removeBasePath(asPathname)
: asPathname : asPathname
return !!items?.some(([regex, ssr]) => { const regex = middleware?.location
return ( return (
!ssr && new RegExp(regex).test(addLocale(cleanedAs, options.locale)) !!regex && new RegExp(regex).test(addLocale(cleanedAs, options.locale))
) )
})
} }
) )
} }
......
...@@ -95,6 +95,15 @@ describe('Middleware Runtime', () => { ...@@ -95,6 +95,15 @@ describe('Middleware Runtime', () => {
await browser.close() await browser.close()
} }
}) })
it('should only contain middleware route in dev middleware manifest', async () => {
const res = await fetchViaHTTP(
next.url,
`/_next/static/${next.buildId}/_devMiddlewareManifest.json`
)
const { location } = await res.json()
expect(location).toBe('.*')
})
} }
if ((global as any).isNextStart) { if ((global as any).isNextStart) {
......
...@@ -90,11 +90,12 @@ describe('Middleware can set the matcher in its config', () => { ...@@ -90,11 +90,12 @@ describe('Middleware can set the matcher in its config', () => {
: 'window.__MIDDLEWARE_MANIFEST' : 'window.__MIDDLEWARE_MANIFEST'
) )
return Array.isArray(manifest) && const { location } = manifest
manifest?.[0]?.[0].includes('with-middleware') && return location &&
manifest?.[0]?.[0].includes('another-middleware') location.includes('with-middleware') &&
location.includes('another-middleware')
? 'success' ? 'success'
: manifest : 'failed'
}, 'success') }, 'success')
}) })
......
...@@ -61,21 +61,13 @@ describe('Switchable runtime', () => { ...@@ -61,21 +61,13 @@ describe('Switchable runtime', () => {
if ((global as any).isNextDev) { if ((global as any).isNextDev) {
describe('Switchable runtime (dev)', () => { describe('Switchable runtime (dev)', () => {
it('should include edge api routes and edge ssr routes into dev middleware manifest', async () => { it('should not include edge api routes and edge ssr routes into dev middleware manifest', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
next.url, next.url,
`/_next/static/${next.buildId}/_devMiddlewareManifest.json` `/_next/static/${next.buildId}/_devMiddlewareManifest.json`
) )
const routesMatchers = await res.json() const devMiddlewareManifest = await res.json()
expect(devMiddlewareManifest).toEqual({})
expect(
routesMatchers.some((matcher) =>
matcher[0].startsWith('^\\/api\\/edge')
)
).toBe(true)
expect(
routesMatchers.some((matcher) => matcher[0].startsWith('^\\/edge'))
).toBe(true)
}) })
it.skip('should support client side navigation to ssr rsc pages', async () => { it.skip('should support client side navigation to ssr rsc pages', async () => {
......
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