Unverified Commit 6bf4df14 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub
parent 01962857
...@@ -156,10 +156,7 @@ impl MiddlewareEndpoint { ...@@ -156,10 +156,7 @@ impl MiddlewareEndpoint {
let next_config = this.project.next_config(); let next_config = this.project.next_config();
let i18n = next_config.i18n().await?; let i18n = next_config.i18n().await?;
let has_i18n = i18n.is_some(); let has_i18n = i18n.is_some();
let has_i18n_locales = i18n let has_i18n_locales = i18n.is_some();
.as_ref()
.map(|i18n| i18n.locales.len() > 1)
.unwrap_or(false);
let base_path = next_config.base_path().await?; let base_path = next_config.base_path().await?;
let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() { let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() {
......
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import { check, fetchViaHTTP } from 'next-test-utils' import { fetchViaHTTP, retry } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
// Redact volatile fields so the snapshot is stable across builds:
// - `env` values are randomly generated per build (encryption keys,
// preview mode ids, build id).
// - `files` and `entrypoint` paths contain content hashes and may
// differ between webpack and Turbopack.
function normalizeMiddlewareManifest(value: unknown, key?: string): unknown {
if (key === 'env' && value && typeof value === 'object') {
return Object.fromEntries(
Object.keys(value)
.sort()
.map((k) => [k, '<redacted>'])
)
}
if (key === 'files') return '<files>'
if (key === 'entrypoint') return '<entrypoint>'
if (Array.isArray(value))
return value.map((v) => normalizeMiddlewareManifest(v))
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [
k,
normalizeMiddlewareManifest(v, k),
])
)
}
return value
}
describe('Middleware can set the matcher in its config', () => { describe('Middleware can set the matcher in its config', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: new FileRef(join(__dirname, 'app')), files: new FileRef(join(__dirname, 'app')),
...@@ -89,19 +117,18 @@ describe('Middleware can set the matcher in its config', () => { ...@@ -89,19 +117,18 @@ describe('Middleware can set the matcher in its config', () => {
it('should load matches in client matchers correctly', async () => { it('should load matches in client matchers correctly', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await check(async () => { await retry(async () => {
const matchers = await browser.eval( const matchers = await browser.eval(
(global as any).isNextDev (global as any).isNextDev
? 'window.__DEV_MIDDLEWARE_MATCHERS' ? 'window.__DEV_MIDDLEWARE_MATCHERS'
: 'window.__MIDDLEWARE_MATCHERS' : 'window.__MIDDLEWARE_MATCHERS'
) )
return matchers && expect(matchers).toSatisfyAny((m) => m.regexp.includes('with-middleware'))
matchers.some((m) => m.regexp.includes('with-middleware')) && expect(matchers).toSatisfyAny((m) =>
matchers.some((m) => m.regexp.includes('another-middleware')) m.regexp.includes('another-middleware')
? 'success' )
: 'failed' })
}, 'success')
}) })
if ((global as any).isNextStart) { if ((global as any).isNextStart) {
...@@ -110,31 +137,7 @@ describe('Middleware can set the matcher in its config', () => { ...@@ -110,31 +137,7 @@ describe('Middleware can set the matcher in its config', () => {
await next.readFile('.next/server/middleware-manifest.json') await next.readFile('.next/server/middleware-manifest.json')
) )
// Redact volatile fields so the snapshot is stable across builds: expect(normalizeMiddlewareManifest(manifest)).toMatchInlineSnapshot(`
// - `env` values are randomly generated per build (encryption keys,
// preview mode ids, build id).
// - `files` and `entrypoint` paths contain content hashes and may
// differ between webpack and Turbopack.
const normalize = (value: unknown, key?: string): unknown => {
if (key === 'env' && value && typeof value === 'object') {
return Object.fromEntries(
Object.keys(value)
.sort()
.map((k) => [k, '<redacted>'])
)
}
if (key === 'files') return '<files>'
if (key === 'entrypoint') return '<entrypoint>'
if (Array.isArray(value)) return value.map((v) => normalize(v))
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, normalize(v, k)])
)
}
return value
}
expect(normalize(manifest)).toMatchInlineSnapshot(`
{ {
"functions": {}, "functions": {},
"middleware": { "middleware": {
...@@ -205,10 +208,11 @@ describe('Middleware can set the matcher in its config', () => { ...@@ -205,10 +208,11 @@ describe('Middleware can set the matcher in its config', () => {
}) })
await browser.elementByCss('#to-blog-slug-2').click() await browser.elementByCss('#to-blog-slug-2').click()
await check( await retry(async () =>
() => browser.eval('document.documentElement.innerHTML'), expect(await browser.eval('document.documentElement.innerHTML')).toMatch(
/"slug":"slug-2"/ /"slug":"slug-2"/
) )
)
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({ expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
message: 'Hello, magnificent world.', message: 'Hello, magnificent world.',
params: { params: {
...@@ -309,11 +313,13 @@ describe('using a single matcher', () => { ...@@ -309,11 +313,13 @@ describe('using a single matcher', () => {
}) })
describe.each([ describe.each([
{ title: '' }, { title: '', includeES: true },
{ title: ' and trailingSlash', trailingSlash: true }, { title: ' and trailingSlash', trailingSlash: true, includeES: true },
{ title: ' and a single locale', includeES: false },
{ title: ' and a single locale', trailingSlash: true, includeES: false },
])( ])(
'using a single matcher with i18n for a non-root route$title', 'using a single matcher with i18n for a non-root route$title',
({ trailingSlash }) => { ({ trailingSlash, includeES }) => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: { files: {
'pages/[...route].js': ` 'pages/[...route].js': `
...@@ -346,7 +352,7 @@ describe.each([ ...@@ -346,7 +352,7 @@ describe.each([
${trailingSlash ? 'trailingSlash: true,' : ''} ${trailingSlash ? 'trailingSlash: true,' : ''}
i18n: { i18n: {
localeDetection: false, localeDetection: false,
locales: ['es', 'en'], locales: ${includeES ? '["es", "en"]' : '["en"]'},
defaultLocale: 'en', defaultLocale: 'en',
} }
} }
...@@ -355,14 +361,66 @@ describe.each([ ...@@ -355,14 +361,66 @@ describe.each([
dependencies: {}, dependencies: {},
}) })
if ((global as any).isNextStart) {
it('produces the expected middleware manifest', async () => {
const manifest = JSON.parse(
await next.readFile('.next/server/middleware-manifest.json')
)
if (!includeES && !trailingSlash) {
expect(normalizeMiddlewareManifest(manifest.middleware['/'].matchers))
.toMatchInlineSnapshot(`
[
{
"originalSource": "/middleware/works",
"regexp": "^(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/((?!_next\\/)[^/.]{1,}))\\/middleware\\/works(\\.json|\\.rsc|\\.segments\\/.+\\.segment\\.rsc)?[\\/#\\?]?$",
},
]
`)
} else if (!includeES && trailingSlash) {
expect(normalizeMiddlewareManifest(manifest.middleware['/'].matchers))
.toMatchInlineSnapshot(`
[
{
"originalSource": "/middleware/works",
"regexp": "^(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/((?!_next\\/)[^/.]{1,}))\\/middleware\\/works(\\.json|\\.rsc|\\.segments\\/.+\\.segment\\.rsc)?[\\/#\\?]?$",
},
]
`)
} else if (includeES && !trailingSlash) {
expect(normalizeMiddlewareManifest(manifest.middleware['/'].matchers))
.toMatchInlineSnapshot(`
[
{
"originalSource": "/middleware/works",
"regexp": "^(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/((?!_next\\/)[^/.]{1,}))\\/middleware\\/works(\\.json|\\.rsc|\\.segments\\/.+\\.segment\\.rsc)?[\\/#\\?]?$",
},
]
`)
} else if (includeES && trailingSlash) {
expect(normalizeMiddlewareManifest(manifest.middleware['/'].matchers))
.toMatchInlineSnapshot(`
[
{
"originalSource": "/middleware/works",
"regexp": "^(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/((?!_next\\/)[^/.]{1,}))\\/middleware\\/works(\\.json|\\.rsc|\\.segments\\/.+\\.segment\\.rsc)?[\\/#\\?]?$",
},
]
`)
}
})
}
it('adds the header for matched paths', async () => { it('adds the header for matched paths', async () => {
const res1 = await fetchViaHTTP(next.url, '/middleware/works') const res1 = await fetchViaHTTP(next.url, '/middleware/works')
expect(await res1.text()).toContain(`(en) Hello from /middleware/works`) expect(await res1.text()).toContain(`(en) Hello from /middleware/works`)
expect(res1.headers.get('X-From-Middleware')).toBe('true') expect(res1.headers.get('X-From-Middleware')).toBe('true')
if (includeES) {
const res2 = await fetchViaHTTP(next.url, '/es/middleware/works') const res2 = await fetchViaHTTP(next.url, '/es/middleware/works')
expect(await res2.text()).toContain(`(es) Hello from /middleware/works`) expect(await res2.text()).toContain(`(es) Hello from /middleware/works`)
expect(res2.headers.get('X-From-Middleware')).toBe('true') expect(res2.headers.get('X-From-Middleware')).toBe('true')
}
}) })
it('adds the header for matched data paths, including the default locale without a prefix', async () => { it('adds the header for matched data paths, including the default locale without a prefix', async () => {
...@@ -379,6 +437,7 @@ describe.each([ ...@@ -379,6 +437,7 @@ describe.each([
}) })
expect(res1.headers.get('X-From-Middleware')).toBe('true') expect(res1.headers.get('X-From-Middleware')).toBe('true')
if (includeES) {
const res2 = await fetchViaHTTP( const res2 = await fetchViaHTTP(
next.url, next.url,
`/_next/data/${next.buildId}/es/middleware/works.json` `/_next/data/${next.buildId}/es/middleware/works.json`
...@@ -389,6 +448,7 @@ describe.each([ ...@@ -389,6 +448,7 @@ describe.each([
}, },
}) })
expect(res2.headers.get('X-From-Middleware')).toBe('true') expect(res2.headers.get('X-From-Middleware')).toBe('true')
}
const res3 = await fetchViaHTTP( const res3 = await fetchViaHTTP(
next.url, next.url,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment