Unverified Commit 2155e07d authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

next-routing: middleware matching and app request URL normalization (#91859)

## Summary
- gate middleware invocation with configured next-routing matchers
- normalize app request URLs in app-page routing paths
- prevent static route matches from inheriting dynamic `routeMatches`
- add test coverage for next-routing captures/resolve-routes/next-data
and app-page URL normalization

## Validation
- validated downstream in adapter-bun deploy E2E runs with `HEADLESS=1`,
`--retries 0`, and `--debug`
parent 0ed3b186
...@@ -454,6 +454,52 @@ describe('Has Condition Captures in Destination', () => { ...@@ -454,6 +454,52 @@ describe('Has Condition Captures in Destination', () => {
expect(result.resolvedPathname).toBe('/localized/en-US/page') expect(result.resolvedPathname).toBe('/localized/en-US/page')
}) })
it('should use named has regex captures in rewrite destinations', async () => {
const headers = new Headers({
'next-url': '/en',
})
const params = createBaseParams({
url: new URL('https://example.com/en/show'),
headers,
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/(?:[^/]+?)/show$',
destination: '/$nxtPlocale/(.)show',
has: [
{
type: 'header',
key: 'next-url',
value: '/(?<nxtPlocale>[^/]+?)(?:/.*)?',
},
],
},
],
afterFiles: [],
dynamicRoutes: [
{
sourceRegex: '^[/]?/(?<nxtPlocale>[^/]+)/\\(\\.\\)show(?:/)?$',
destination: '/[locale]/(.)show?nxtPlocale=$nxtPlocale',
},
],
onMatch: [],
fallback: [],
},
pathnames: ['/[locale]/(.)show'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/[locale]/(.)show')
expect(result.routeMatches).toEqual({
'1': 'en',
nxtPlocale: 'en',
})
expect(result.invocationTarget?.pathname).toBe('/en/(.)show')
})
it('should use has captures in query string', async () => { it('should use has captures in query string', async () => {
const headers = new Headers({ const headers = new Headers({
'x-user-id': '999', 'x-user-id': '999',
......
...@@ -37,7 +37,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -37,7 +37,7 @@ describe('resolveRoutes with i18n', () => {
it('should redirect to locale prefix when accept-language is set', async () => { it('should redirect to locale prefix when accept-language is set', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about'), url: new URL('http://example.com/'),
headers: new Headers({ headers: new Headers({
'accept-language': 'fr,en;q=0.9', 'accept-language': 'fr,en;q=0.9',
}), }),
...@@ -45,14 +45,14 @@ describe('resolveRoutes with i18n', () => { ...@@ -45,14 +45,14 @@ describe('resolveRoutes with i18n', () => {
}) })
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/fr/about') expect(result.redirect?.url.pathname).toBe('/fr/')
expect(result.redirect?.status).toBe(307) expect(result.redirect?.status).toBe(307)
}) })
it('should use quality values from accept-language', async () => { it('should use quality values from accept-language', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about'), url: new URL('http://example.com/'),
headers: new Headers({ headers: new Headers({
'accept-language': 'de;q=0.8,fr;q=0.9,en;q=0.7', 'accept-language': 'de;q=0.8,fr;q=0.9,en;q=0.7',
}), }),
...@@ -60,13 +60,46 @@ describe('resolveRoutes with i18n', () => { ...@@ -60,13 +60,46 @@ describe('resolveRoutes with i18n', () => {
}) })
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/fr/about') expect(result.redirect?.url.pathname).toBe('/fr/')
})
it('should preserve middleware response headers on locale redirect', async () => {
const invokeMiddleware = jest.fn(async () => ({
responseHeaders: new Headers({
'x-nested-header': 'valid',
'x-append-me': 'top',
}),
}))
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/'),
headers: new Headers({
'accept-language': 'fr,en;q=0.9',
}),
i18n: i18nConfigNoDomains,
invokeMiddleware,
routes: {
...baseParams.routes,
middlewareMatchers: [
{
sourceRegex: '^/.*$',
},
],
},
})
expect(invokeMiddleware).toHaveBeenCalledTimes(1)
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/fr/')
expect(result.resolvedHeaders?.get('x-nested-header')).toBe('valid')
expect(result.resolvedHeaders?.get('x-append-me')).toBe('top')
}) })
it('should not redirect when locale matches default', async () => { it('should not redirect when locale matches default', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about'), url: new URL('http://example.com/'),
headers: new Headers({ headers: new Headers({
'accept-language': 'en', 'accept-language': 'en',
}), }),
...@@ -76,13 +109,26 @@ describe('resolveRoutes with i18n', () => { ...@@ -76,13 +109,26 @@ describe('resolveRoutes with i18n', () => {
// Should prefix internally but not redirect // Should prefix internally but not redirect
expect(result.redirect).toBeUndefined() expect(result.redirect).toBeUndefined()
}) })
it('should not redirect preferred locale for non-index pathnames', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
'accept-language': 'fr,en;q=0.9',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeUndefined()
})
}) })
describe('locale detection from cookie', () => { describe('locale detection from cookie', () => {
it('should redirect to locale from NEXT_LOCALE cookie', async () => { it('should redirect to locale from NEXT_LOCALE cookie', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about'), url: new URL('http://example.com/'),
headers: new Headers({ headers: new Headers({
cookie: 'NEXT_LOCALE=ja', cookie: 'NEXT_LOCALE=ja',
}), }),
...@@ -90,13 +136,13 @@ describe('resolveRoutes with i18n', () => { ...@@ -90,13 +136,13 @@ describe('resolveRoutes with i18n', () => {
}) })
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/ja/about') expect(result.redirect?.url.pathname).toBe('/ja/')
}) })
it('should prioritize cookie over accept-language', async () => { it('should prioritize cookie over accept-language', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about'), url: new URL('http://example.com/'),
headers: new Headers({ headers: new Headers({
cookie: 'session=abc; NEXT_LOCALE=ja; theme=dark', cookie: 'session=abc; NEXT_LOCALE=ja; theme=dark',
'accept-language': 'fr', 'accept-language': 'fr',
...@@ -105,7 +151,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -105,7 +151,7 @@ describe('resolveRoutes with i18n', () => {
}) })
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/ja/about') expect(result.redirect?.url.pathname).toBe('/ja/')
}) })
}) })
...@@ -125,7 +171,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -125,7 +171,7 @@ describe('resolveRoutes with i18n', () => {
it('should redirect to correct domain for preferred locale', async () => { it('should redirect to correct domain for preferred locale', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about'), url: new URL('http://example.com/'),
headers: new Headers({ headers: new Headers({
'accept-language': 'fr', 'accept-language': 'fr',
}), }),
...@@ -134,13 +180,13 @@ describe('resolveRoutes with i18n', () => { ...@@ -134,13 +180,13 @@ describe('resolveRoutes with i18n', () => {
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.hostname).toBe('example.fr') expect(result.redirect?.url.hostname).toBe('example.fr')
expect(result.redirect?.url.pathname).toBe('/about') expect(result.redirect?.url.pathname).toBe('/')
}) })
it('should not include locale prefix for domain default locale', async () => { it('should not include locale prefix for domain default locale', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about'), url: new URL('http://example.com/'),
headers: new Headers({ headers: new Headers({
'accept-language': 'de', 'accept-language': 'de',
}), }),
...@@ -149,7 +195,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -149,7 +195,7 @@ describe('resolveRoutes with i18n', () => {
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.hostname).toBe('example.de') expect(result.redirect?.url.hostname).toBe('example.de')
expect(result.redirect?.url.pathname).toBe('/about') expect(result.redirect?.url.pathname).toBe('/')
}) })
}) })
...@@ -240,7 +286,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -240,7 +286,7 @@ describe('resolveRoutes with i18n', () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
basePath: '/base', basePath: '/base',
url: new URL('http://example.com/base/about'), url: new URL('http://example.com/base'),
headers: new Headers({ headers: new Headers({
'accept-language': 'ja', 'accept-language': 'ja',
}), }),
...@@ -248,14 +294,14 @@ describe('resolveRoutes with i18n', () => { ...@@ -248,14 +294,14 @@ describe('resolveRoutes with i18n', () => {
}) })
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/base/ja/about') expect(result.redirect?.url.pathname).toBe('/base/ja/')
}) })
it('should handle basePath with domain redirect', async () => { it('should handle basePath with domain redirect', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
basePath: '/base', basePath: '/base',
url: new URL('http://example.com/base/about'), url: new URL('http://example.com/base'),
headers: new Headers({ headers: new Headers({
'accept-language': 'de', 'accept-language': 'de',
}), }),
...@@ -264,7 +310,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -264,7 +310,7 @@ describe('resolveRoutes with i18n', () => {
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.hostname).toBe('example.de') expect(result.redirect?.url.hostname).toBe('example.de')
expect(result.redirect?.url.pathname).toBe('/base/about') expect(result.redirect?.url.pathname).toBe('/base/')
}) })
}) })
...@@ -287,7 +333,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -287,7 +333,7 @@ describe('resolveRoutes with i18n', () => {
it('should handle query strings', async () => { it('should handle query strings', async () => {
const result = await resolveRoutes({ const result = await resolveRoutes({
...baseParams, ...baseParams,
url: new URL('http://example.com/about?foo=bar'), url: new URL('http://example.com/?foo=bar'),
headers: new Headers({ headers: new Headers({
'accept-language': 'ja', 'accept-language': 'ja',
}), }),
...@@ -295,7 +341,7 @@ describe('resolveRoutes with i18n', () => { ...@@ -295,7 +341,7 @@ describe('resolveRoutes with i18n', () => {
}) })
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/ja/about') expect(result.redirect?.url.pathname).toBe('/ja/')
expect(result.redirect?.url.search).toBe('?foo=bar') expect(result.redirect?.url.search).toBe('?foo=bar')
}) })
...@@ -358,5 +404,38 @@ describe('resolveRoutes with i18n', () => { ...@@ -358,5 +404,38 @@ describe('resolveRoutes with i18n', () => {
id: '123', id: '123',
}) })
}) })
it('should match non-localized dynamic templates when localized variant is absent', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/app-dir/foo'),
headers: new Headers({}),
pathnames: ['/app-dir/[[...slug]]', '/en/[[...slug]]'],
routes: {
...baseParams.routes,
dynamicRoutes: [
{
sourceRegex:
'^[/]?(?<nextLocale>[^/]{1,})/app\\-dir(?:/(?<nxtPslug>.+?))?(?:/)?$',
destination:
'/$nextLocale/app-dir/[[...slug]]?nxtPslug=$nxtPslug',
},
{
sourceRegex:
'^[/]?(?<nextLocale>[^/]{1,})(?:/(?<nxtPslug>.+?))?(?:/)?$',
destination: '/$nextLocale/[[...slug]]?nxtPslug=$nxtPslug',
},
],
},
i18n: {
defaultLocale: 'en',
locales: ['en', 'en-GB'],
localeDetection: false,
},
})
expect(result.redirect).toBeUndefined()
expect(result.resolvedPathname).toBe('/app-dir/[[...slug]]')
})
}) })
}) })
...@@ -90,6 +90,41 @@ describe('normalizeNextData - beforeMiddleware', () => { ...@@ -90,6 +90,41 @@ describe('normalizeNextData - beforeMiddleware', () => {
}) })
}) })
describe('normalizeNextData - middleware matchers', () => {
it('should match middleware against normalized pathname for data URLs', async () => {
const middlewareMock = jest.fn().mockResolvedValue({})
const params = createBaseParams({
url: new URL('https://example.com/_next/data/BUILD_ID/blog/post.json'),
basePath: '',
pathnames: ['/_next/data/BUILD_ID/blog/post.json'],
invokeMiddleware: middlewareMock,
routes: {
beforeMiddleware: [],
middlewareMatchers: [
{
sourceRegex: '^/blog/post$',
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
shouldNormalizeNextData: true,
},
})
const result = await resolveRoutes(params)
expect(middlewareMock).toHaveBeenCalledTimes(1)
expect(middlewareMock.mock.calls[0][0].url.pathname).toBe(
'/_next/data/BUILD_ID/blog/post.json'
)
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/blog/post.json')
})
})
describe('normalizeNextData - pathname checking', () => { describe('normalizeNextData - pathname checking', () => {
it('should denormalize before checking pathnames after beforeFiles', async () => { it('should denormalize before checking pathnames after beforeFiles', async () => {
const params = createBaseParams({ const params = createBaseParams({
...@@ -114,6 +149,37 @@ describe('normalizeNextData - pathname checking', () => { ...@@ -114,6 +149,37 @@ describe('normalizeNextData - pathname checking', () => {
) )
}) })
it('should normalize index data URL to root pathname', async () => {
const params = createBaseParams({
url: new URL('https://example.com/_next/data/BUILD_ID/index.json'),
basePath: '',
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [
{
sourceRegex: '^/(?<nxtPid>[^/]+)$',
destination: '/[id]?nxtPid=$nxtPid',
},
],
onMatch: [],
fallback: [],
shouldNormalizeNextData: true,
},
pathnames: ['/', '/[id]', '/_next/data/BUILD_ID/index.json'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/_next/data/BUILD_ID/index.json')
expect(result.routeMatches).toBeUndefined()
expect(result.invocationTarget).toEqual({
pathname: '/_next/data/BUILD_ID/index.json',
query: {},
})
})
it('should work with rewrites then pathname check', async () => { it('should work with rewrites then pathname check', async () => {
const params = createBaseParams({ const params = createBaseParams({
url: new URL('https://example.com/_next/data/BUILD_ID/blog.json'), url: new URL('https://example.com/_next/data/BUILD_ID/blog.json'),
......
...@@ -632,4 +632,101 @@ describe('Redirect priority and precedence', () => { ...@@ -632,4 +632,101 @@ describe('Redirect priority and precedence', () => {
expect(result.redirect).toBeDefined() expect(result.redirect).toBeDefined()
expect(middlewareMock).not.toHaveBeenCalled() expect(middlewareMock).not.toHaveBeenCalled()
}) })
it('should process middleware before beforeMiddleware stop routes without destination', async () => {
const middlewareMock = jest.fn().mockResolvedValue({
responseHeaders: new Headers({
'x-nested-header': 'valid',
}),
})
const params = createBaseParams({
url: new URL('https://example.com/'),
routes: {
beforeMiddleware: [
{
sourceRegex: '^/$',
status: 308,
headers: {
location: '/en',
},
},
],
middlewareMatchers: [
{
sourceRegex: '^/.*$',
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
invokeMiddleware: middlewareMock,
})
const result = await resolveRoutes(params)
expect(middlewareMock).toHaveBeenCalledTimes(1)
expect(result.status).toBe(308)
expect(result.resolvedHeaders?.get('location')).toBe('/en')
expect(result.resolvedHeaders?.get('x-nested-header')).toBe('valid')
})
it('should preserve request query in location header redirects without destination', async () => {
const params = createBaseParams({
url: new URL('https://example.com/?hello=world'),
routes: {
beforeMiddleware: [
{
sourceRegex: '^/$',
status: 308,
headers: {
location: '/en',
},
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
const result = await resolveRoutes(params)
expect(result.redirect).toBeUndefined()
expect(result.status).toBe(308)
expect(result.resolvedHeaders?.get('location')).toBe('/en?hello=world')
})
it('should not overwrite existing location query in redirects without destination', async () => {
const params = createBaseParams({
url: new URL('https://example.com/?hello=world'),
routes: {
beforeMiddleware: [
{
sourceRegex: '^/$',
status: 308,
headers: {
location: '/en?from=route',
},
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
const result = await resolveRoutes(params)
expect(result.redirect).toBeUndefined()
expect(result.status).toBe(308)
expect(result.resolvedHeaders?.get('location')).toBe('/en?from=route')
})
}) })
...@@ -89,6 +89,41 @@ describe('resolveRoutes - beforeMiddleware', () => { ...@@ -89,6 +89,41 @@ describe('resolveRoutes - beforeMiddleware', () => {
expect(result.redirect?.url.pathname).toBe('/new') expect(result.redirect?.url.pathname).toBe('/new')
}) })
it('should stop at first matching redirect headers route', async () => {
const params = createBaseParams({
url: new URL('https://example.com/en/redirect-1'),
routes: {
beforeMiddleware: [
{
sourceRegex: '^/en/redirect-1(?:/)?$',
status: 307,
headers: {
Location: '/somewhere/else',
},
},
{
sourceRegex: '^(?:/(en|fr|nl))/redirect-1(?:/)?$',
status: 307,
headers: {
Location: '/$1/somewhere/else',
},
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
const result = await resolveRoutes(params)
expect(result.status).toBe(307)
expect(result.redirect).toBeUndefined()
expect(result.resolvedHeaders?.get('location')).toBe('/somewhere/else')
})
it('should handle external rewrite in beforeMiddleware', async () => { it('should handle external rewrite in beforeMiddleware', async () => {
const params = createBaseParams({ const params = createBaseParams({
url: new URL('https://example.com/proxy'), url: new URL('https://example.com/proxy'),
...@@ -142,7 +177,229 @@ describe('resolveRoutes - beforeMiddleware', () => { ...@@ -142,7 +177,229 @@ describe('resolveRoutes - beforeMiddleware', () => {
}) })
}) })
describe('resolveRoutes - case sensitivity', () => {
it('should match routes case-insensitively by default', async () => {
const params = createBaseParams({
url: new URL('https://example.com/rewrite-no-basePath'),
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [
{
sourceRegex: '^/rewrite-no-basepath(?:/)?$',
destination: 'https://example.vercel.sh/',
},
],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
const result = await resolveRoutes(params)
expect(result.externalRewrite?.toString()).toBe(
'https://example.vercel.sh/'
)
})
it('should respect caseSensitive route matching when enabled', async () => {
const params = createBaseParams({
url: new URL('https://example.com/rewrite-no-basePath'),
routes: {
caseSensitive: true,
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [
{
sourceRegex: '^/rewrite-no-basepath(?:/)?$',
destination: 'https://example.vercel.sh/',
},
],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
const result = await resolveRoutes(params)
expect(result.externalRewrite).toBeUndefined()
expect(result.redirect).toBeUndefined()
})
})
describe('resolveRoutes - invokeMiddleware', () => { describe('resolveRoutes - invokeMiddleware', () => {
it('should skip invokeMiddleware when middleware matchers are empty', async () => {
const middlewareMock = jest.fn().mockResolvedValue({})
const params = createBaseParams({
url: new URL('https://example.com/no-matchers'),
pathnames: ['/no-matchers'],
invokeMiddleware: middlewareMock,
routes: {
beforeMiddleware: [],
middlewareMatchers: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
const result = await resolveRoutes(params)
expect(middlewareMock).not.toHaveBeenCalled()
expect(result.resolvedPathname).toBe('/no-matchers')
})
it('should skip invokeMiddleware when middleware matchers do not match', async () => {
const middlewareMock = jest.fn().mockResolvedValue({})
const params = createBaseParams({
url: new URL('https://example.com/no-match'),
pathnames: ['/no-match'],
invokeMiddleware: middlewareMock,
routes: {
beforeMiddleware: [],
middlewareMatchers: [
{
sourceRegex: '^/middleware-only$',
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
const result = await resolveRoutes(params)
expect(middlewareMock).not.toHaveBeenCalled()
expect(result.resolvedPathname).toBe('/no-match')
})
it('should call invokeMiddleware when a middleware matcher matches', async () => {
const middlewareMock = jest.fn().mockResolvedValue({})
const params = createBaseParams({
url: new URL('https://example.com/middleware-only'),
pathnames: ['/middleware-only'],
invokeMiddleware: middlewareMock,
routes: {
beforeMiddleware: [],
middlewareMatchers: [
{
sourceRegex: '^/middleware-only$',
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
await resolveRoutes(params)
expect(middlewareMock).toHaveBeenCalledTimes(1)
})
it('should call invokeMiddleware when a middleware matcher matches decoded pathname', async () => {
const middlewareMock = jest.fn().mockResolvedValue({})
const params = createBaseParams({
url: new URL('https://example.com/vercel%20copy.svg'),
pathnames: ['/vercel copy.svg'],
invokeMiddleware: middlewareMock,
routes: {
beforeMiddleware: [],
middlewareMatchers: [
{
sourceRegex: '^/vercel copy\\.svg$',
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
await resolveRoutes(params)
expect(middlewareMock).toHaveBeenCalledTimes(1)
})
it('should skip invokeMiddleware when pathname decoding fails and encoded pathname does not match', async () => {
const middlewareMock = jest.fn().mockResolvedValue({})
const params = createBaseParams({
url: new URL('https://example.com/%E0%A4%A'),
pathnames: ['/%E0%A4%A'],
invokeMiddleware: middlewareMock,
routes: {
beforeMiddleware: [],
middlewareMatchers: [
{
sourceRegex: '^/decoded-only$',
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
await resolveRoutes(params)
expect(middlewareMock).not.toHaveBeenCalled()
})
it('should evaluate has conditions in middleware matchers', async () => {
const middlewareMock = jest.fn().mockResolvedValue({})
const params = createBaseParams({
url: new URL('https://example.com/has-header'),
pathnames: ['/has-header'],
headers: new Headers({
'x-test': 'enabled',
}),
invokeMiddleware: middlewareMock,
routes: {
beforeMiddleware: [],
middlewareMatchers: [
{
sourceRegex: '^/has-header$',
has: [
{
type: 'header',
key: 'x-test',
value: 'enabled',
},
],
},
],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
})
await resolveRoutes(params)
expect(middlewareMock).toHaveBeenCalledTimes(1)
})
it('should call invokeMiddleware with current URL and headers', async () => { it('should call invokeMiddleware with current URL and headers', async () => {
const middlewareMock = jest.fn().mockResolvedValue({}) const middlewareMock = jest.fn().mockResolvedValue({})
...@@ -756,6 +1013,70 @@ describe('resolveRoutes - dynamic routes', () => { ...@@ -756,6 +1013,70 @@ describe('resolveRoutes - dynamic routes', () => {
}) })
}) })
it('should prefer exact static resolvedPathname when both concrete and dynamic pathnames exist', async () => {
const params = createBaseParams({
url: new URL('https://example.com/blog/post-1'),
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [
{
sourceRegex: '^/blog/(?<nxtPslug>[^/]+?)$',
destination: '/blog/[slug]?nxtPslug=$nxtPslug',
},
],
onMatch: [],
fallback: [],
},
pathnames: ['/blog/[slug]', '/blog/post-1'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/blog/post-1')
expect(result.routeMatches).toBeUndefined()
expect(result.invocationTarget).toEqual({
pathname: '/blog/post-1',
query: {},
})
})
it('should replace missing optional dynamic placeholders with empty values', async () => {
const params = createBaseParams({
url: new URL('https://example.com/catch-all-optional'),
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [
{
sourceRegex:
'^[/]?/catch-all-optional(?:/(?<nxtPslug>.+?))?(?:/)?$',
destination: '/catch-all-optional/[[...slug]]?nxtPslug=$nxtPslug',
},
],
onMatch: [],
fallback: [],
},
pathnames: ['/catch-all-optional/[[...slug]]'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/catch-all-optional/[[...slug]]')
expect(result.routeMatches).toEqual({})
expect(result.resolvedQuery).toEqual({
nxtPslug: '',
})
expect(result.invocationTarget).toEqual({
pathname: '/catch-all-optional',
query: {
nxtPslug: '',
},
})
})
it('should match dynamic route with multiple segments', async () => { it('should match dynamic route with multiple segments', async () => {
const params = createBaseParams({ const params = createBaseParams({
url: new URL('https://example.com/posts/2024/my-article'), url: new URL('https://example.com/posts/2024/my-article'),
......
...@@ -13,18 +13,14 @@ export function replaceDestination( ...@@ -13,18 +13,14 @@ export function replaceDestination(
if (regexMatches) { if (regexMatches) {
// Replace numbered groups (skip index 0 which is the full match) // Replace numbered groups (skip index 0 which is the full match)
for (let i = 1; i < regexMatches.length; i++) { for (let i = 1; i < regexMatches.length; i++) {
const value = regexMatches[i] const value = regexMatches[i] ?? ''
if (value !== undefined) { result = result.replace(new RegExp(`\\$${i}`, 'g'), value)
result = result.replace(new RegExp(`\\$${i}`, 'g'), value)
}
} }
// Replace named groups ($name) // Replace named groups ($name)
if (regexMatches.groups) { if (regexMatches.groups) {
for (const [name, value] of Object.entries(regexMatches.groups)) { for (const [name, value] of Object.entries(regexMatches.groups)) {
if (value !== undefined) { result = result.replace(new RegExp(`\\$${name}`, 'g'), value ?? '')
result = result.replace(new RegExp(`\\$${name}`, 'g'), value)
}
} }
} }
} }
......
...@@ -8,7 +8,11 @@ import type { RouteHas } from './types' ...@@ -8,7 +8,11 @@ import type { RouteHas } from './types'
function matchesCondition( function matchesCondition(
actualValue: string | undefined, actualValue: string | undefined,
conditionValue: string | undefined conditionValue: string | undefined
): { matched: boolean; capturedValue?: string } { ): {
matched: boolean
capturedValue?: string
namedCaptures?: Record<string, string>
} {
if (actualValue === undefined) { if (actualValue === undefined) {
return { matched: false } return { matched: false }
} }
...@@ -20,10 +24,24 @@ function matchesCondition( ...@@ -20,10 +24,24 @@ function matchesCondition(
// Try to match as regex first // Try to match as regex first
try { try {
const regex = new RegExp(conditionValue) const exactRegex = new RegExp(`^(?:${conditionValue})$`)
const match = actualValue.match(regex) const fallbackRegex = new RegExp(conditionValue)
const match =
actualValue.match(exactRegex) ?? actualValue.match(fallbackRegex)
if (match) { if (match) {
return { matched: true, capturedValue: match[0] } const namedCaptures: Record<string, string> = {}
if (match.groups) {
for (const [key, value] of Object.entries(match.groups)) {
if (typeof value === 'string' && value.length > 0) {
namedCaptures[key] = value
}
}
}
return {
matched: true,
capturedValue: match[0],
...(Object.keys(namedCaptures).length > 0 ? { namedCaptures } : {}),
}
} }
} catch (e) { } catch (e) {
// Not a valid regex, fall through to direct match // Not a valid regex, fall through to direct match
...@@ -104,6 +122,12 @@ export function checkHasConditions( ...@@ -104,6 +122,12 @@ export function checkHasConditions(
return { matched: false, captures: {} } return { matched: false, captures: {} }
} }
if (result.namedCaptures) {
for (const [key, value] of Object.entries(result.namedCaptures)) {
captures[key] = value
}
}
// Store captured value with normalized key name for named replacements // Store captured value with normalized key name for named replacements
if (result.capturedValue !== undefined && condition.type !== 'host') { if (result.capturedValue !== undefined && condition.type !== 'host') {
const normalizedKey = normalizeCaptureKey(condition.key) const normalizedKey = normalizeCaptureKey(condition.key)
......
...@@ -22,7 +22,11 @@ export function normalizeNextDataUrl( ...@@ -22,7 +22,11 @@ export function normalizeNextDataUrl(
pathAfterData = pathAfterData.slice(0, -5) pathAfterData = pathAfterData.slice(0, -5)
} }
pathname = basePath ? `${basePath}/${pathAfterData}` : `/${pathAfterData}` if (pathAfterData === 'index') {
pathname = basePath || '/'
} else {
pathname = basePath ? `${basePath}/${pathAfterData}` : `/${pathAfterData}`
}
newUrl.pathname = pathname newUrl.pathname = pathname
} }
...@@ -50,6 +54,10 @@ export function denormalizeNextDataUrl( ...@@ -50,6 +54,10 @@ export function denormalizeNextDataUrl(
pathWithoutBase = pathname.slice(basePath.length) pathWithoutBase = pathname.slice(basePath.length)
} }
if (pathWithoutBase === '' || pathWithoutBase === '/') {
pathWithoutBase = '/index'
}
// Add the /_next/data/${buildId}/ prefix and .json extension // Add the /_next/data/${buildId}/ prefix and .json extension
pathname = `${basePath}/_next/data/${buildId}${pathWithoutBase}.json` pathname = `${basePath}/_next/data/${buildId}${pathWithoutBase}.json`
newUrl.pathname = pathname newUrl.pathname = pathname
......
...@@ -15,13 +15,52 @@ import { ...@@ -15,13 +15,52 @@ import {
import { normalizeNextDataUrl, denormalizeNextDataUrl } from './next-data' import { normalizeNextDataUrl, denormalizeNextDataUrl } from './next-data'
import { detectLocale, detectDomainLocale, normalizeLocalePath } from './i18n' import { detectLocale, detectDomainLocale, normalizeLocalePath } from './i18n'
function getHeaderValueCaseInsensitive(
headers: Record<string, string>,
targetHeader: string
): string | undefined {
const targetHeaderLower = targetHeader.toLowerCase()
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === targetHeaderLower) {
return value
}
}
return undefined
}
function resolveRedirectLocationWithRequestQuery(
locationHeader: string,
requestUrl: URL
): string {
if (!requestUrl.search) {
return locationHeader
}
try {
const resolvedLocation = new URL(locationHeader, requestUrl)
if (resolvedLocation.search) {
return locationHeader
}
resolvedLocation.search = requestUrl.search
if (resolvedLocation.origin !== requestUrl.origin) {
return resolvedLocation.toString()
}
return `${resolvedLocation.pathname}${resolvedLocation.search}${resolvedLocation.hash}`
} catch {
return locationHeader
}
}
/** /**
* Attempts to match a route against the current URL and conditions * Attempts to match a route against the current URL and conditions
*/ */
function matchRoute( function matchRoute(
route: Route, route: Route,
url: URL, url: URL,
headers: Headers headers: Headers,
caseSensitive: boolean
): { ): {
matched: boolean matched: boolean
destination?: string destination?: string
...@@ -30,7 +69,7 @@ function matchRoute( ...@@ -30,7 +69,7 @@ function matchRoute(
hasCaptures?: Record<string, string> hasCaptures?: Record<string, string>
} { } {
// Check if source regex matches the pathname // Check if source regex matches the pathname
const regex = new RegExp(route.sourceRegex) const regex = new RegExp(route.sourceRegex, caseSensitive ? '' : 'i')
const regexMatches = url.pathname.match(regex) const regexMatches = url.pathname.match(regex)
if (!regexMatches) { if (!regexMatches) {
...@@ -79,7 +118,8 @@ function processRoutes( ...@@ -79,7 +118,8 @@ function processRoutes(
url: URL, url: URL,
requestHeaders: Headers, requestHeaders: Headers,
responseHeaders: Headers, responseHeaders: Headers,
initialOrigin: string initialOrigin: string,
caseSensitive: boolean
): { ): {
url: URL url: URL
externalRewrite?: URL externalRewrite?: URL
...@@ -94,7 +134,7 @@ function processRoutes( ...@@ -94,7 +134,7 @@ function processRoutes(
let currentStatus: number | undefined let currentStatus: number | undefined
for (const route of routes) { for (const route of routes) {
const match = matchRoute(route, currentUrl, requestHeaders) const match = matchRoute(route, currentUrl, requestHeaders, caseSensitive)
if (match.matched) { if (match.matched) {
if (match.headers) { if (match.headers) {
...@@ -107,13 +147,12 @@ function processRoutes( ...@@ -107,13 +147,12 @@ function processRoutes(
currentStatus = route.status currentStatus = route.status
} }
if (match.destination) { if (
// Check if route has redirect status and Location/Refresh header isRedirectStatus(route.status) &&
if ( match.headers &&
isRedirectStatus(route.status) && hasRedirectHeaders(match.headers)
match.headers && ) {
hasRedirectHeaders(match.headers) if (match.destination) {
) {
const redirectUrl = isExternalDestination(match.destination) const redirectUrl = isExternalDestination(match.destination)
? new URL(match.destination) ? new URL(match.destination)
: applyDestination(currentUrl, match.destination) : applyDestination(currentUrl, match.destination)
...@@ -129,6 +168,25 @@ function processRoutes( ...@@ -129,6 +168,25 @@ function processRoutes(
} }
} }
const locationHeader = getHeaderValueCaseInsensitive(
match.headers,
'location'
)
if (locationHeader) {
responseHeaders.set(
'location',
resolveRedirectLocationWithRequestQuery(locationHeader, currentUrl)
)
}
return {
url: currentUrl,
stopped: true,
status: currentStatus,
}
}
if (match.destination) {
// Check if it's an external rewrite // Check if it's an external rewrite
if (isExternalDestination(match.destination)) { if (isExternalDestination(match.destination)) {
return { return {
...@@ -173,6 +231,60 @@ function matchesPathname( ...@@ -173,6 +231,60 @@ function matchesPathname(
return undefined return undefined
} }
function matchesPathnameWithLocaleFallback({
pathname,
pathnames,
basePath,
i18n,
}: {
pathname: string
pathnames: string[]
basePath: string
i18n?: ResolveRoutesParams['i18n']
}): string | undefined {
const directMatch = matchesPathname(pathname, pathnames)
if (directMatch || !i18n) {
return directMatch
}
const withoutBasePath =
basePath && pathname.startsWith(basePath)
? pathname.slice(basePath.length) || '/'
: pathname
for (const locale of i18n.locales) {
const localePrefix = `/${locale}`
if (
withoutBasePath !== localePrefix &&
!withoutBasePath.startsWith(`${localePrefix}/`)
) {
continue
}
const withoutLocale =
withoutBasePath === localePrefix
? '/'
: withoutBasePath.slice(localePrefix.length) || '/'
const localeFallbackPathname = basePath
? `${basePath}${withoutLocale}`
: withoutLocale
const localeFallbackMatch = matchesPathname(
localeFallbackPathname,
pathnames
)
if (localeFallbackMatch) {
return localeFallbackMatch
}
}
return undefined
}
function isDynamicTemplatePathname(pathname: string): boolean {
return /\[[^/]+?\]/.test(pathname)
}
function toResolvedQuery(url: URL): ResolveRoutesQuery { function toResolvedQuery(url: URL): ResolveRoutesQuery {
const query: ResolveRoutesQuery = {} const query: ResolveRoutesQuery = {}
for (const [key, value] of url.searchParams.entries()) { for (const [key, value] of url.searchParams.entries()) {
...@@ -230,13 +342,14 @@ function withResolvedInvocationTarget({ ...@@ -230,13 +342,14 @@ function withResolvedInvocationTarget({
*/ */
function matchDynamicRoute( function matchDynamicRoute(
pathname: string, pathname: string,
route: Route route: Route,
caseSensitive: boolean
): { ): {
matched: boolean matched: boolean
params?: Record<string, string> params?: Record<string, string>
regexMatches?: RegExpMatchArray regexMatches?: RegExpMatchArray
} { } {
const regex = new RegExp(route.sourceRegex) const regex = new RegExp(route.sourceRegex, caseSensitive ? '' : 'i')
const match = pathname.match(regex) const match = pathname.match(regex)
if (!match) { if (!match) {
...@@ -267,12 +380,13 @@ function applyOnMatchHeaders( ...@@ -267,12 +380,13 @@ function applyOnMatchHeaders(
routes: Route[], routes: Route[],
url: URL, url: URL,
requestHeaders: Headers, requestHeaders: Headers,
responseHeaders: Headers responseHeaders: Headers,
caseSensitive: boolean
): Headers { ): Headers {
const newHeaders = new Headers(responseHeaders) const newHeaders = new Headers(responseHeaders)
for (const route of routes) { for (const route of routes) {
const match = matchRoute(route, url, requestHeaders) const match = matchRoute(route, url, requestHeaders, caseSensitive)
if (match.matched && match.headers) { if (match.matched && match.headers) {
for (const [key, value] of Object.entries(match.headers)) { for (const [key, value] of Object.entries(match.headers)) {
...@@ -296,8 +410,10 @@ function checkDynamicRoutes( ...@@ -296,8 +410,10 @@ function checkDynamicRoutes(
onMatchRoutes: Route[], onMatchRoutes: Route[],
basePath: string, basePath: string,
buildId: string, buildId: string,
i18n: ResolveRoutesParams['i18n'],
shouldNormalizeNextData?: boolean, shouldNormalizeNextData?: boolean,
isDataUrl?: boolean isDataUrl?: boolean,
caseSensitive: boolean = false
): { ): {
matched: boolean matched: boolean
result?: ResolveRoutesResult result?: ResolveRoutesResult
...@@ -310,7 +426,7 @@ function checkDynamicRoutes( ...@@ -310,7 +426,7 @@ function checkDynamicRoutes(
} }
for (const route of dynamicRoutes) { for (const route of dynamicRoutes) {
const match = matchDynamicRoute(checkUrl.pathname, route) const match = matchDynamicRoute(checkUrl.pathname, route, caseSensitive)
if (match.matched) { if (match.matched) {
// Check has/missing conditions // Check has/missing conditions
...@@ -334,7 +450,12 @@ function checkDynamicRoutes( ...@@ -334,7 +450,12 @@ function checkDynamicRoutes(
const pathnameToCheck = replacedDestination const pathnameToCheck = replacedDestination
? replacedDestination.split('?')[0] ? replacedDestination.split('?')[0]
: checkUrl.pathname : checkUrl.pathname
const matchedPath = matchesPathname(pathnameToCheck, pathnames) const matchedPath = matchesPathnameWithLocaleFallback({
pathname: pathnameToCheck,
pathnames,
basePath,
i18n,
})
if (matchedPath) { if (matchedPath) {
const resolvedUrl = replacedDestination const resolvedUrl = replacedDestination
? mergeDestinationQueryIntoUrl(checkUrl, replacedDestination) ? mergeDestinationQueryIntoUrl(checkUrl, replacedDestination)
...@@ -343,7 +464,8 @@ function checkDynamicRoutes( ...@@ -343,7 +464,8 @@ function checkDynamicRoutes(
onMatchRoutes, onMatchRoutes,
resolvedUrl, resolvedUrl,
requestHeaders, requestHeaders,
responseHeaders responseHeaders,
caseSensitive
) )
const result = withResolvedInvocationTarget({ const result = withResolvedInvocationTarget({
result: { result: {
...@@ -367,6 +489,71 @@ function checkDynamicRoutes( ...@@ -367,6 +489,71 @@ function checkDynamicRoutes(
return { matched: false } return { matched: false }
} }
function shouldInvokeMiddlewareForRequest(
middlewareMatchers: Route[] | undefined,
url: URL,
requestHeaders: Headers,
caseSensitive: boolean
): boolean {
const matchesMiddlewareMatchers = (candidatePathname: string): boolean => {
if (!middlewareMatchers || middlewareMatchers.length === 0) {
return false
}
for (const matcher of middlewareMatchers) {
const regex = new RegExp(matcher.sourceRegex, caseSensitive ? '' : 'i')
const regexMatches = candidatePathname.match(regex)
if (!regexMatches) {
continue
}
const hasResult = checkHasConditions(matcher.has, url, requestHeaders)
if (!hasResult.matched) {
continue
}
const missingMatched = checkMissingConditions(
matcher.missing,
url,
requestHeaders
)
if (!missingMatched) {
continue
}
return true
}
return false
}
// Preserve legacy behavior for callers that don't yet provide matchers.
if (middlewareMatchers === undefined) {
return true
}
if (middlewareMatchers.length === 0) {
return false
}
if (matchesMiddlewareMatchers(url.pathname)) {
return true
}
let decodedPathname = url.pathname
try {
decodedPathname = decodeURIComponent(url.pathname)
} catch {
return false
}
if (decodedPathname === url.pathname) {
return false
}
return matchesMiddlewareMatchers(decodedPathname)
}
export async function resolveRoutes( export async function resolveRoutes(
params: ResolveRoutesParams params: ResolveRoutesParams
): Promise<ResolveRoutesResult> { ): Promise<ResolveRoutesResult> {
...@@ -382,12 +569,23 @@ export async function resolveRoutes( ...@@ -382,12 +569,23 @@ export async function resolveRoutes(
i18n, i18n,
} = params } = params
const { shouldNormalizeNextData } = routes const { shouldNormalizeNextData, caseSensitive = false } = routes
let currentUrl = new URL(initialUrl.toString()) let currentUrl = new URL(initialUrl.toString())
let currentRequestHeaders = new Headers(initialHeaders) let currentRequestHeaders = new Headers(initialHeaders)
let currentResponseHeaders = new Headers() let currentResponseHeaders = new Headers()
let currentStatus: number | undefined let currentStatus: number | undefined
let pendingLocaleRedirect:
| {
url: URL
status: number
}
| undefined
let pendingBeforeMiddlewareStop:
| {
status: number | undefined
}
| undefined
const initialOrigin = initialUrl.origin const initialOrigin = initialUrl.origin
// Check if the original URL is a data URL and normalize if so // Check if the original URL is a data URL and normalize if so
...@@ -425,8 +623,14 @@ export async function resolveRoutes( ...@@ -425,8 +623,14 @@ export async function resolveRoutes(
// Determine target locale if locale detection is enabled // Determine target locale if locale detection is enabled
let targetLocale = pathLocaleResult.detectedLocale || defaultLocale let targetLocale = pathLocaleResult.detectedLocale || defaultLocale
if (i18n.localeDetection !== false && !localeInPath) { // Match Next.js behavior: preferred-locale auto-detection redirects only
// Full locale detection when no locale in path // on index requests, not on arbitrary non-locale pathnames.
const shouldDetectPreferredLocale =
i18n.localeDetection !== false &&
!localeInPath &&
pathLocaleResult.pathname === '/'
if (shouldDetectPreferredLocale) {
const detectedResult = detectLocale({ const detectedResult = detectLocale({
pathname, pathname,
hostname, hostname,
...@@ -456,12 +660,9 @@ export async function resolveRoutes( ...@@ -456,12 +660,9 @@ export async function resolveRoutes(
`${scheme}://${targetDomain.domain}${basePath}${localePrefix}${pathname}${currentUrl.search}` `${scheme}://${targetDomain.domain}${basePath}${localePrefix}${pathname}${currentUrl.search}`
) )
return { pendingLocaleRedirect = {
redirect: { url: redirectUrl,
url: redirectUrl, status: 307,
status: 307,
},
resolvedHeaders: currentResponseHeaders,
} }
} }
...@@ -474,19 +675,16 @@ export async function resolveRoutes( ...@@ -474,19 +675,16 @@ export async function resolveRoutes(
const redirectUrl = new URL(currentUrl.toString()) const redirectUrl = new URL(currentUrl.toString())
redirectUrl.pathname = `${basePath}/${targetLocale}${pathname}` redirectUrl.pathname = `${basePath}/${targetLocale}${pathname}`
return { pendingLocaleRedirect = {
redirect: { url: redirectUrl,
url: redirectUrl, status: 307,
status: 307,
},
resolvedHeaders: currentResponseHeaders,
} }
} }
} }
} }
// Prefix the locale internally for route resolution (without redirecting) // Prefix the locale internally for route resolution (without redirecting)
if (!localeInPath) { if (!localeInPath && !pendingLocaleRedirect) {
const localeToPrefix = const localeToPrefix =
targetLocale || domainLocale?.defaultLocale || i18n.defaultLocale targetLocale || domainLocale?.defaultLocale || i18n.defaultLocale
currentUrl.pathname = `${basePath}/${localeToPrefix}${pathname}` currentUrl.pathname = `${basePath}/${localeToPrefix}${pathname}`
...@@ -500,7 +698,8 @@ export async function resolveRoutes( ...@@ -500,7 +698,8 @@ export async function resolveRoutes(
currentUrl, currentUrl,
currentRequestHeaders, currentRequestHeaders,
currentResponseHeaders, currentResponseHeaders,
initialOrigin initialOrigin,
caseSensitive
) )
if (beforeMiddlewareResult.status) { if (beforeMiddlewareResult.status) {
...@@ -523,66 +722,107 @@ export async function resolveRoutes( ...@@ -523,66 +722,107 @@ export async function resolveRoutes(
} }
} }
if (beforeMiddlewareResult.stopped) {
pendingBeforeMiddlewareStop = {
status: currentStatus,
}
}
currentUrl = beforeMiddlewareResult.url currentUrl = beforeMiddlewareResult.url
let middlewareInvocationUrl = currentUrl
// Denormalize before invoking middleware if this was originally a data URL // Denormalize before invoking middleware if this was originally a data URL
if (isDataUrl && shouldNormalizeNextData) { if (isDataUrl && shouldNormalizeNextData) {
currentUrl = denormalizeNextDataUrl(currentUrl, basePath, buildId) middlewareInvocationUrl = denormalizeNextDataUrl(
currentUrl,
basePath,
buildId
)
} }
// Invoke middleware const shouldInvokeMiddleware = shouldInvokeMiddlewareForRequest(
const middlewareResult = await invokeMiddleware({ routes.middlewareMatchers,
url: currentUrl, currentUrl,
headers: currentRequestHeaders, currentRequestHeaders,
requestBody, caseSensitive
}) )
// Check if middleware sent the response body if (shouldInvokeMiddleware) {
if (middlewareResult.bodySent) { // Invoke middleware
return { middlewareResponded: true } const middlewareResult = await invokeMiddleware({
} url: middlewareInvocationUrl,
headers: currentRequestHeaders,
requestBody,
})
// Apply request headers from middleware // Check if middleware sent the response body
if (middlewareResult.requestHeaders) { if (middlewareResult.bodySent) {
currentRequestHeaders = new Headers(middlewareResult.requestHeaders) return { middlewareResponded: true }
} }
// Apply request headers from middleware
if (middlewareResult.requestHeaders) {
currentRequestHeaders = new Headers(middlewareResult.requestHeaders)
}
// Apply response headers from middleware
if (middlewareResult.responseHeaders) {
middlewareResult.responseHeaders.forEach((value, key) => {
if (key.toLowerCase() === 'set-cookie') {
currentResponseHeaders.append(key, value)
} else {
currentResponseHeaders.set(key, value)
}
})
}
// Apply response headers from middleware // Handle middleware redirect
if (middlewareResult.responseHeaders) { if (middlewareResult.redirect) {
middlewareResult.responseHeaders.forEach((value, key) => { if (!currentResponseHeaders.has('location')) {
if (key.toLowerCase() === 'set-cookie') { currentResponseHeaders.set(
currentResponseHeaders.append(key, value) 'Location',
} else { middlewareResult.redirect.url.toString()
currentResponseHeaders.set(key, value) )
} }
}) return {
resolvedHeaders: currentResponseHeaders,
status: middlewareResult.redirect.status,
}
}
// Handle middleware rewrite
if (middlewareResult.rewrite) {
currentUrl = middlewareResult.rewrite
// Check if it's an external rewrite
if (currentUrl.origin !== initialOrigin) {
return {
externalRewrite: currentUrl,
resolvedHeaders: currentResponseHeaders,
status: currentStatus,
}
}
}
} }
// Handle middleware redirect if (pendingLocaleRedirect) {
if (middlewareResult.redirect) {
if (!currentResponseHeaders.has('location')) { if (!currentResponseHeaders.has('location')) {
currentResponseHeaders.set( currentResponseHeaders.set(
'Location', 'location',
middlewareResult.redirect.url.toString() pendingLocaleRedirect.url.toString()
) )
} }
return { return {
redirect: pendingLocaleRedirect,
resolvedHeaders: currentResponseHeaders, resolvedHeaders: currentResponseHeaders,
status: middlewareResult.redirect.status,
} }
} }
// Handle middleware rewrite if (pendingBeforeMiddlewareStop) {
if (middlewareResult.rewrite) { return {
currentUrl = middlewareResult.rewrite resolvedHeaders: currentResponseHeaders,
status: pendingBeforeMiddlewareStop.status,
// Check if it's an external rewrite
if (currentUrl.origin !== initialOrigin) {
return {
externalRewrite: currentUrl,
resolvedHeaders: currentResponseHeaders,
status: currentStatus,
}
} }
} }
...@@ -597,7 +837,8 @@ export async function resolveRoutes( ...@@ -597,7 +837,8 @@ export async function resolveRoutes(
currentUrl, currentUrl,
currentRequestHeaders, currentRequestHeaders,
currentResponseHeaders, currentResponseHeaders,
initialOrigin initialOrigin,
caseSensitive
) )
if (beforeFilesResult.status) { if (beforeFilesResult.status) {
...@@ -620,6 +861,13 @@ export async function resolveRoutes( ...@@ -620,6 +861,13 @@ export async function resolveRoutes(
} }
} }
if (beforeFilesResult.stopped) {
return {
resolvedHeaders: currentResponseHeaders,
status: currentStatus,
}
}
currentUrl = beforeFilesResult.url currentUrl = beforeFilesResult.url
// Denormalize before checking pathnames if this was originally a data URL // Denormalize before checking pathnames if this was originally a data URL
...@@ -630,52 +878,101 @@ export async function resolveRoutes( ...@@ -630,52 +878,101 @@ export async function resolveRoutes(
// Check if pathname matches any provided pathnames (pathnames are in denormalized form) // Check if pathname matches any provided pathnames (pathnames are in denormalized form)
let matchedPath = matchesPathname(currentUrl.pathname, pathnames) let matchedPath = matchesPathname(currentUrl.pathname, pathnames)
if (matchedPath) { if (matchedPath) {
// Check if any dynamic route also matches to extract parameters
for (const route of routes.dynamicRoutes) { for (const route of routes.dynamicRoutes) {
const match = matchDynamicRoute(currentUrl.pathname, route) const match = matchDynamicRoute(currentUrl.pathname, route, caseSensitive)
if (match.matched) { if (!match.matched) {
// Check has/missing conditions continue
const hasResult = checkHasConditions( }
route.has,
currentUrl,
currentRequestHeaders
)
const missingMatched = checkMissingConditions(
route.missing,
currentUrl,
currentRequestHeaders
)
if (hasResult.matched && missingMatched) { const hasResult = checkHasConditions(
const replacedDestination = route.destination route.has,
? replaceDestination( currentUrl,
route.destination, currentRequestHeaders
match.regexMatches || null, )
hasResult.captures const missingMatched = checkMissingConditions(
) route.missing,
: undefined currentUrl,
const resolvedUrl = replacedDestination currentRequestHeaders
? mergeDestinationQueryIntoUrl(currentUrl, replacedDestination) )
: currentUrl
const finalHeaders = applyOnMatchHeaders( if (!hasResult.matched || !missingMatched) {
routes.onMatch, continue
resolvedUrl, }
currentRequestHeaders,
currentResponseHeaders const replacedDestination = route.destination
? replaceDestination(
route.destination,
match.regexMatches || null,
hasResult.captures
) )
return withResolvedInvocationTarget({ : undefined
result: { const pathnameToCheck = replacedDestination
routeMatches: match.params, ? replacedDestination.split('?')[0]
resolvedHeaders: finalHeaders, : currentUrl.pathname
status: currentStatus, const dynamicMatchedPath = matchesPathnameWithLocaleFallback({
}, pathname: pathnameToCheck,
url: resolvedUrl, pathnames,
resolvedPathname: matchedPath, basePath,
invocationPathname: currentUrl.pathname, i18n,
}) })
if (!dynamicMatchedPath) {
// When a dynamic route rewrites to a non-template/static destination
// that isn't part of pathnames, preserve route params for the currently
// matched concrete pathname.
if (isDynamicTemplatePathname(pathnameToCheck)) {
continue
} }
const resolvedUrl = replacedDestination
? mergeDestinationQueryIntoUrl(currentUrl, replacedDestination)
: currentUrl
const finalHeaders = applyOnMatchHeaders(
routes.onMatch,
resolvedUrl,
currentRequestHeaders,
currentResponseHeaders,
caseSensitive
)
return withResolvedInvocationTarget({
result: {
routeMatches: match.params,
resolvedHeaders: finalHeaders,
status: currentStatus,
},
url: resolvedUrl,
resolvedPathname: matchedPath,
invocationPathname: currentUrl.pathname,
})
}
const shouldUseDynamicMatch =
dynamicMatchedPath === matchedPath ||
isDynamicTemplatePathname(matchedPath)
if (!shouldUseDynamicMatch) {
continue
} }
const resolvedUrl = replacedDestination
? mergeDestinationQueryIntoUrl(currentUrl, replacedDestination)
: currentUrl
const finalHeaders = applyOnMatchHeaders(
routes.onMatch,
resolvedUrl,
currentRequestHeaders,
currentResponseHeaders,
caseSensitive
)
return withResolvedInvocationTarget({
result: {
routeMatches: match.params,
resolvedHeaders: finalHeaders,
status: currentStatus,
},
url: resolvedUrl,
resolvedPathname: dynamicMatchedPath,
invocationPathname: currentUrl.pathname,
})
} }
// No dynamic route matched, return without route matches // No dynamic route matched, return without route matches
...@@ -683,7 +980,8 @@ export async function resolveRoutes( ...@@ -683,7 +980,8 @@ export async function resolveRoutes(
routes.onMatch, routes.onMatch,
currentUrl, currentUrl,
currentRequestHeaders, currentRequestHeaders,
currentResponseHeaders currentResponseHeaders,
caseSensitive
) )
return withResolvedInvocationTarget({ return withResolvedInvocationTarget({
result: { result: {
...@@ -703,7 +1001,12 @@ export async function resolveRoutes( ...@@ -703,7 +1001,12 @@ export async function resolveRoutes(
// Process afterFiles routes // Process afterFiles routes
for (const route of routes.afterFiles) { for (const route of routes.afterFiles) {
const match = matchRoute(route, currentUrl, currentRequestHeaders) const match = matchRoute(
route,
currentUrl,
currentRequestHeaders,
caseSensitive
)
if (match.matched) { if (match.matched) {
if (match.headers) { if (match.headers) {
...@@ -768,8 +1071,10 @@ export async function resolveRoutes( ...@@ -768,8 +1071,10 @@ export async function resolveRoutes(
routes.onMatch, routes.onMatch,
basePath, basePath,
buildId, buildId,
i18n,
shouldNormalizeNextData, shouldNormalizeNextData,
isDataUrl isDataUrl,
caseSensitive
) )
if (dynamicResult.matched && dynamicResult.result) { if (dynamicResult.matched && dynamicResult.result) {
// Reset URL to the denormalized version if it matched // Reset URL to the denormalized version if it matched
...@@ -796,7 +1101,8 @@ export async function resolveRoutes( ...@@ -796,7 +1101,8 @@ export async function resolveRoutes(
routes.onMatch, routes.onMatch,
pathnameCheckUrl, pathnameCheckUrl,
currentRequestHeaders, currentRequestHeaders,
currentResponseHeaders currentResponseHeaders,
caseSensitive
) )
return withResolvedInvocationTarget({ return withResolvedInvocationTarget({
result: { result: {
...@@ -814,7 +1120,7 @@ export async function resolveRoutes( ...@@ -814,7 +1120,7 @@ export async function resolveRoutes(
// Check dynamic routes // Check dynamic routes
for (const route of routes.dynamicRoutes) { for (const route of routes.dynamicRoutes) {
const match = matchDynamicRoute(currentUrl.pathname, route) const match = matchDynamicRoute(currentUrl.pathname, route, caseSensitive)
if (match.matched) { if (match.matched) {
// Check has/missing conditions // Check has/missing conditions
...@@ -842,7 +1148,12 @@ export async function resolveRoutes( ...@@ -842,7 +1148,12 @@ export async function resolveRoutes(
const pathnameToCheck = replacedDestination const pathnameToCheck = replacedDestination
? replacedDestination.split('?')[0] ? replacedDestination.split('?')[0]
: currentUrl.pathname : currentUrl.pathname
matchedPath = matchesPathname(pathnameToCheck, pathnames) matchedPath = matchesPathnameWithLocaleFallback({
pathname: pathnameToCheck,
pathnames,
basePath,
i18n,
})
if (matchedPath) { if (matchedPath) {
const resolvedUrl = replacedDestination const resolvedUrl = replacedDestination
? mergeDestinationQueryIntoUrl(currentUrl, replacedDestination) ? mergeDestinationQueryIntoUrl(currentUrl, replacedDestination)
...@@ -851,7 +1162,8 @@ export async function resolveRoutes( ...@@ -851,7 +1162,8 @@ export async function resolveRoutes(
routes.onMatch, routes.onMatch,
resolvedUrl, resolvedUrl,
currentRequestHeaders, currentRequestHeaders,
currentResponseHeaders currentResponseHeaders,
caseSensitive
) )
return withResolvedInvocationTarget({ return withResolvedInvocationTarget({
result: { result: {
...@@ -870,7 +1182,12 @@ export async function resolveRoutes( ...@@ -870,7 +1182,12 @@ export async function resolveRoutes(
// Process fallback routes // Process fallback routes
for (const route of routes.fallback) { for (const route of routes.fallback) {
const match = matchRoute(route, currentUrl, currentRequestHeaders) const match = matchRoute(
route,
currentUrl,
currentRequestHeaders,
caseSensitive
)
if (match.matched) { if (match.matched) {
if (match.headers) { if (match.headers) {
...@@ -935,8 +1252,10 @@ export async function resolveRoutes( ...@@ -935,8 +1252,10 @@ export async function resolveRoutes(
routes.onMatch, routes.onMatch,
basePath, basePath,
buildId, buildId,
i18n,
shouldNormalizeNextData, shouldNormalizeNextData,
isDataUrl isDataUrl,
caseSensitive
) )
if (dynamicResult.matched && dynamicResult.result) { if (dynamicResult.matched && dynamicResult.result) {
// Reset URL to the denormalized version if it matched // Reset URL to the denormalized version if it matched
...@@ -963,7 +1282,8 @@ export async function resolveRoutes( ...@@ -963,7 +1282,8 @@ export async function resolveRoutes(
routes.onMatch, routes.onMatch,
pathnameCheckUrl, pathnameCheckUrl,
currentRequestHeaders, currentRequestHeaders,
currentResponseHeaders currentResponseHeaders,
caseSensitive
) )
return withResolvedInvocationTarget({ return withResolvedInvocationTarget({
result: { result: {
......
...@@ -58,7 +58,17 @@ export type ResolveRoutesParams = { ...@@ -58,7 +58,17 @@ export type ResolveRoutesParams = {
locales: string[] locales: string[]
} }
routes: { routes: {
/**
* When false (default), route matching is case-insensitive to mirror
* Next.js default behavior. When true, matches are case-sensitive.
*/
caseSensitive?: boolean
beforeMiddleware: Array<Route> beforeMiddleware: Array<Route>
/**
* Middleware matcher definitions used to decide whether middleware should
* be invoked for the current request.
*/
middlewareMatchers?: Array<Route>
beforeFiles: Array<Route> beforeFiles: Array<Route>
afterFiles: Array<Route> afterFiles: Array<Route>
dynamicRoutes: Array<Route> dynamicRoutes: Array<Route>
......
...@@ -379,6 +379,12 @@ export interface NextAdapter { ...@@ -379,6 +379,12 @@ export interface NextAdapter {
onBuildComplete?: (ctx: { onBuildComplete?: (ctx: {
routing: { routing: {
beforeMiddleware: Array<Route> beforeMiddleware: Array<Route>
/**
* middlewareMatchers are the middleware matcher definitions emitted by
* Next.js for this build and can be used to decide whether middleware
* should be invoked for a given request.
*/
middlewareMatchers: Array<Route>
beforeFiles: Array<Route> beforeFiles: Array<Route>
afterFiles: Array<Route> afterFiles: Array<Route>
dynamicRoutes: Array<Route> dynamicRoutes: Array<Route>
...@@ -2151,6 +2157,13 @@ export async function handleBuildComplete({ ...@@ -2151,6 +2157,13 @@ export async function handleBuildComplete({
await adapterMod.onBuildComplete({ await adapterMod.onBuildComplete({
routing: { routing: {
beforeMiddleware: [...headers, ...redirects], beforeMiddleware: [...headers, ...redirects],
middlewareMatchers:
outputs.middleware?.config.matchers?.map((matcher) => ({
source: matcher.source,
sourceRegex: matcher.sourceRegex,
has: matcher.has,
missing: matcher.missing,
})) ?? [],
beforeFiles: rewrites.beforeFiles, beforeFiles: rewrites.beforeFiles,
afterFiles: rewrites.afterFiles, afterFiles: rewrites.afterFiles,
dynamicRoutes: combinedDynamicRoutes, dynamicRoutes: combinedDynamicRoutes,
......
...@@ -46,6 +46,7 @@ import { getIsPossibleServerAction } from '../../server/lib/server-action-reques ...@@ -46,6 +46,7 @@ import { getIsPossibleServerAction } from '../../server/lib/server-action-reques
import { import {
RSC_HEADER, RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_INSTANT_PREFETCH_HEADER, NEXT_INSTANT_PREFETCH_HEADER,
NEXT_INSTANT_TEST_COOKIE, NEXT_INSTANT_TEST_COOKIE,
NEXT_IS_PRERENDER_HEADER, NEXT_IS_PRERENDER_HEADER,
...@@ -491,7 +492,17 @@ export async function handler( ...@@ -491,7 +492,17 @@ export async function handler(
// need to transfer it to the request meta because it's only read // need to transfer it to the request meta because it's only read
// within this function; the static segment data should have already been // within this function; the static segment data should have already been
// generated, so we will always either return a static response or a 404. // generated, so we will always either return a static response or a 404.
const segmentPrefetchHeader = getRequestMeta(req, 'segmentPrefetchRSCRequest') const rawSegmentPrefetchHeader =
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]
const segmentPrefetchHeader =
getRequestMeta(req, 'segmentPrefetchRSCRequest') ??
(isPrefetchRSCRequest
? typeof rawSegmentPrefetchHeader === 'string'
? rawSegmentPrefetchHeader
: Array.isArray(rawSegmentPrefetchHeader)
? rawSegmentPrefetchHeader[0]
: undefined
: undefined)
// TODO: investigate existing bug with shouldServeStreamingMetadata always // TODO: investigate existing bug with shouldServeStreamingMetadata always
// being true for a revalidate due to modifying the base-server this.renderOpts // being true for a revalidate due to modifying the base-server this.renderOpts
......
...@@ -32,7 +32,10 @@ import { RSCPathnameNormalizer } from '../../normalizers/request/rsc' ...@@ -32,7 +32,10 @@ import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc' import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import { normalizeAppPageRequestUrl } from './normalize-request-url' import {
applyAppPageRscRequestMetaFromHeaders,
normalizeAppPageRequestUrl,
} from './normalize-request-url'
let vendoredReactRSC let vendoredReactRSC
let vendoredReactSSR let vendoredReactSSR
...@@ -139,11 +142,13 @@ export class AppPageRouteModule extends RouteModule< ...@@ -139,11 +142,13 @@ export class AppPageRouteModule extends RouteModule<
// Mark the request as a RSC request. // Mark the request as a RSC request.
req.headers[RSC_HEADER] = '1' req.headers[RSC_HEADER] = '1'
addRequestMeta(req, 'isRSCRequest', true)
} else { } else {
super.normalizeUrl(req, parsedUrl) super.normalizeUrl(req, parsedUrl)
} }
// Minimal adapters can bypass base-server request normalization and invoke
// route modules directly, so derive RSC/prefetch metadata from headers.
applyAppPageRscRequestMetaFromHeaders(req)
normalizeAppPageRequestUrl(req, parsedUrl.pathname || '/') normalizeAppPageRequestUrl(req, parsedUrl.pathname || '/')
} }
......
...@@ -4,12 +4,16 @@ import { ...@@ -4,12 +4,16 @@ import {
RSC_HEADER, RSC_HEADER,
} from '../../../client/components/app-router-headers' } from '../../../client/components/app-router-headers'
import { parseReqUrl } from '../../../lib/url' import { parseReqUrl } from '../../../lib/url'
import { getRequestMeta } from '../../request-meta'
import { RSCPathnameNormalizer } from '../../normalizers/request/rsc' import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc' import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import { normalizeAppPageRequestUrl } from './normalize-request-url' import {
applyAppPageRscRequestMetaFromHeaders,
normalizeAppPageRequestUrl,
} from './normalize-request-url'
type TestRequest = { type TestRequest = {
headers: Record<string, string> headers: Record<string, string | string[]>
url: string url: string
} }
...@@ -79,3 +83,41 @@ describe('normalizeAppPageRequestUrl', () => { ...@@ -79,3 +83,41 @@ describe('normalizeAppPageRequestUrl', () => {
) )
}) })
}) })
describe('applyAppPageRscRequestMetaFromHeaders', () => {
it('sets RSC and prefetch request meta from headers', () => {
const req: TestRequest = {
headers: {
[RSC_HEADER]: '1',
[NEXT_ROUTER_PREFETCH_HEADER]: '1',
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/_tree',
},
url: '/docs/frameworks/frontend?foo=bar',
}
applyAppPageRscRequestMetaFromHeaders(req)
expect(getRequestMeta(req as any, 'isRSCRequest')).toBe(true)
expect(getRequestMeta(req as any, 'isPrefetchRSCRequest')).toBe(true)
expect(getRequestMeta(req as any, 'segmentPrefetchRSCRequest')).toBe(
'/_tree'
)
})
it('uses the first segment prefetch header value when provided as an array', () => {
const req: TestRequest = {
headers: {
[RSC_HEADER]: '1',
[NEXT_ROUTER_PREFETCH_HEADER]: '1',
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: ['/_tree', '/ignored'],
},
url: '/docs/frameworks/frontend?foo=bar',
}
applyAppPageRscRequestMetaFromHeaders(req)
expect(getRequestMeta(req as any, 'segmentPrefetchRSCRequest')).toBe(
'/_tree'
)
})
})
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
RSC_HEADER,
} from '../../../client/components/app-router-headers'
import type { BaseNextRequest } from '../../base-http' import type { BaseNextRequest } from '../../base-http'
import { parseReqUrl } from '../../../lib/url' import { parseReqUrl } from '../../../lib/url'
import { formatUrl } from '../../../shared/lib/router/utils/format-url' import { formatUrl } from '../../../shared/lib/router/utils/format-url'
import { addRequestMeta } from '../../request-meta'
function getHeaderValue(
value: string | string[] | undefined
): string | undefined {
if (Array.isArray(value)) {
return value[0]
}
return value
}
export function applyAppPageRscRequestMetaFromHeaders(
req: Pick<IncomingMessage | BaseNextRequest, 'headers'>
): void {
const isRscRequest = getHeaderValue(req.headers[RSC_HEADER]) === '1'
if (!isRscRequest) {
return
}
addRequestMeta(req as IncomingMessage, 'isRSCRequest', true)
const isPrefetchRequest =
getHeaderValue(req.headers[NEXT_ROUTER_PREFETCH_HEADER]) === '1'
if (!isPrefetchRequest) {
return
}
addRequestMeta(req as IncomingMessage, 'isPrefetchRSCRequest', true)
const segmentPrefetchPath = getHeaderValue(
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]
)
if (segmentPrefetchPath) {
addRequestMeta(
req as IncomingMessage,
'segmentPrefetchRSCRequest',
segmentPrefetchPath
)
}
}
export function normalizeAppPageRequestUrl( export function normalizeAppPageRequestUrl(
req: Pick<IncomingMessage | BaseNextRequest, 'url'>, req: Pick<IncomingMessage | BaseNextRequest, 'url'>,
......
...@@ -82,6 +82,7 @@ describe('adapter-config export', () => { ...@@ -82,6 +82,7 @@ describe('adapter-config export', () => {
expect(routing).toEqual({ expect(routing).toEqual({
beforeMiddleware: expect.toBeArray(), beforeMiddleware: expect.toBeArray(),
middlewareMatchers: expect.toBeArray(),
beforeFiles: expect.toBeArray(), beforeFiles: expect.toBeArray(),
afterFiles: expect.toBeArray(), afterFiles: expect.toBeArray(),
dynamicRoutes: expect.toBeArray(), dynamicRoutes: expect.toBeArray(),
......
...@@ -379,6 +379,7 @@ describe('adapter-config', () => { ...@@ -379,6 +379,7 @@ describe('adapter-config', () => {
expect(routing).toEqual({ expect(routing).toEqual({
beforeMiddleware: expect.toBeArray(), beforeMiddleware: expect.toBeArray(),
middlewareMatchers: expect.toBeArray(),
beforeFiles: expect.toBeArray(), beforeFiles: expect.toBeArray(),
afterFiles: expect.toBeArray(), afterFiles: expect.toBeArray(),
dynamicRoutes: expect.toBeArray(), dynamicRoutes: expect.toBeArray(),
......
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