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)
} }
if (pathAfterData === 'index') {
pathname = basePath || '/'
} else {
pathname = basePath ? `${basePath}/${pathAfterData}` : `/${pathAfterData}` 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
......
This diff is collapsed.
...@@ -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