-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathedge-middleware.test.ts
299 lines (233 loc) · 11.1 KB
/
edge-middleware.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { expect, Response } from '@playwright/test'
import { nextVersionSatisfies } from '../utils/next-version-helpers.mjs'
import { test } from '../utils/playwright-helpers.js'
import { getImageSize } from 'next/dist/server/image-optimizer.js'
test('Runs edge middleware', async ({ page, middleware }) => {
await page.goto(`${middleware.url}/test/redirect`)
await expect(page).toHaveTitle('Simple Next App')
const h1 = page.locator('h1')
await expect(h1).toHaveText('Other')
})
test('Does not run edge middleware at the origin', async ({ page, middleware }) => {
const res = await page.goto(`${middleware.url}/test/next`)
expect(await res?.headerValue('x-deno')).toBeTruthy()
expect(await res?.headerValue('x-node')).toBeNull()
await expect(page).toHaveTitle('Simple Next App')
const h1 = page.locator('h1')
await expect(h1).toHaveText('Message from middleware: hello')
})
test('does not run middleware again for rewrite target', async ({ page, middleware }) => {
const direct = await page.goto(`${middleware.url}/test/rewrite-target`)
expect(await direct?.headerValue('x-added-rewrite-target')).toBeTruthy()
const rewritten = await page.goto(`${middleware.url}/test/rewrite-loop-detect`)
expect(await rewritten?.headerValue('x-added-rewrite-target')).toBeNull()
const h1 = page.locator('h1')
await expect(h1).toHaveText('Hello rewrite')
})
test('Supports CJS dependencies in Edge Middleware', async ({ page, middleware }) => {
const res = await page.goto(`${middleware.url}/test/next`)
expect(await res?.headerValue('x-cjs-module-works')).toEqual('true')
})
// adaptation of https://github.com/vercel/next.js/blob/8aa9a52c36f338320d55bd2ec292ffb0b8c7cb35/test/e2e/app-dir/metadata-edge/index.test.ts#L24C5-L31C7
test('it should render OpenGraph image meta tag correctly', async ({ page, middlewareOg }) => {
test.skip(!nextVersionSatisfies('>=14.0.0'), 'This test is only for Next.js 14+')
await page.goto(`${middlewareOg.url}/`)
const ogURL = await page.locator('meta[property="og:image"]').getAttribute('content')
expect(ogURL).toBeTruthy()
const ogResponse = await fetch(new URL(new URL(ogURL!).pathname, middlewareOg.url))
const imageBuffer = await ogResponse.arrayBuffer()
const size = await getImageSize(Buffer.from(imageBuffer), 'png')
expect([size.width, size.height]).toEqual([1200, 630])
})
test('json data rewrite works', async ({ middlewarePages }) => {
const response = await fetch(`${middlewarePages.url}/_next/data/build-id/sha.json`, {
headers: {
'x-nextjs-data': '1',
},
})
expect(response.ok).toBe(true)
const body = await response.text()
expect(body).toMatch(/^{"pageProps":/)
const data = JSON.parse(body)
expect(data.pageProps.message).toBeDefined()
})
// those tests use `fetch` instead of `page.goto` intentionally to avoid potential client rendering
// hiding any potential edge/server issues
test.describe('Middleware with i18n and excluded paths', () => {
const DEFAULT_LOCALE = 'en'
/** helper function to extract JSON data from page rendering data with `<pre>{JSON.stringify(data)}</pre>` */
function extractDataFromHtml(html: string): Record<string, any> {
const match = html.match(/<pre>(?<rawInput>[^<]+)<\/pre>/)
if (!match || !match.groups?.rawInput) {
console.error('<pre> not found in html input', {
html,
})
throw new Error('Failed to extract data from HTML')
}
const { rawInput } = match.groups
const unescapedInput = rawInput.replaceAll('"', '"')
try {
return JSON.parse(unescapedInput)
} catch (originalError) {
console.error('Failed to parse JSON', {
originalError,
rawInput,
unescapedInput,
})
}
throw new Error('Failed to extract data from HTML')
}
// those tests hit paths ending with `/json` which has special handling in middleware
// to return JSON response from middleware itself
test.describe('Middleware response path', () => {
test('should match on non-localized not excluded page path', async ({
middlewareI18nExcludedPaths,
}) => {
const response = await fetch(`${middlewareI18nExcludedPaths.url}/json`)
expect(response.headers.get('x-test-used-middleware')).toBe('true')
expect(response.status).toBe(200)
const { nextUrlPathname, nextUrlLocale } = await response.json()
expect(nextUrlPathname).toBe('/json')
expect(nextUrlLocale).toBe(DEFAULT_LOCALE)
})
test('should match on localized not excluded page path', async ({
middlewareI18nExcludedPaths,
}) => {
const response = await fetch(`${middlewareI18nExcludedPaths.url}/fr/json`)
expect(response.headers.get('x-test-used-middleware')).toBe('true')
expect(response.status).toBe(200)
const { nextUrlPathname, nextUrlLocale } = await response.json()
expect(nextUrlPathname).toBe('/json')
expect(nextUrlLocale).toBe('fr')
})
})
// those tests hit paths that don't end with `/json` while still satisfying middleware matcher
// so middleware should pass them through to origin
test.describe('Middleware passthrough', () => {
test('should match on non-localized not excluded page path', async ({
middlewareI18nExcludedPaths,
}) => {
const response = await fetch(`${middlewareI18nExcludedPaths.url}/html`)
expect(response.headers.get('x-test-used-middleware')).toBe('true')
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toMatch(/text\/html/)
const html = await response.text()
const { locale, params } = extractDataFromHtml(html)
expect(params).toMatchObject({ catchall: ['html'] })
expect(locale).toBe(DEFAULT_LOCALE)
})
test('should match on localized not excluded page path', async ({
middlewareI18nExcludedPaths,
}) => {
const response = await fetch(`${middlewareI18nExcludedPaths.url}/fr/html`)
expect(response.headers.get('x-test-used-middleware')).toBe('true')
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toMatch(/text\/html/)
const html = await response.text()
const { locale, params } = extractDataFromHtml(html)
expect(params).toMatchObject({ catchall: ['html'] })
expect(locale).toBe('fr')
})
})
// those tests hit paths that don't satisfy middleware matcher, so should go directly to origin
// without going through middleware
test.describe('Middleware skipping (paths not satisfying middleware matcher)', () => {
test('should NOT match on non-localized excluded API path', async ({
middlewareI18nExcludedPaths,
}) => {
const response = await fetch(`${middlewareI18nExcludedPaths.url}/api/html`)
expect(response.headers.get('x-test-used-middleware')).not.toBe('true')
expect(response.status).toBe(200)
const { params } = await response.json()
expect(params).toMatchObject({ catchall: ['html'] })
})
test('should NOT match on non-localized excluded page path', async ({
middlewareI18nExcludedPaths,
}) => {
const response = await fetch(`${middlewareI18nExcludedPaths.url}/excluded`)
expect(response.headers.get('x-test-used-middleware')).not.toBe('true')
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toMatch(/text\/html/)
const html = await response.text()
const { locale, params } = extractDataFromHtml(html)
expect(params).toMatchObject({ catchall: ['excluded'] })
expect(locale).toBe(DEFAULT_LOCALE)
})
test('should NOT match on localized excluded page path', async ({
middlewareI18nExcludedPaths,
}) => {
const response = await fetch(`${middlewareI18nExcludedPaths.url}/fr/excluded`)
expect(response.headers.get('x-test-used-middleware')).not.toBe('true')
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toMatch(/text\/html/)
const html = await response.text()
const { locale, params } = extractDataFromHtml(html)
expect(params).toMatchObject({ catchall: ['excluded'] })
expect(locale).toBe('fr')
})
})
})
test("requests with x-middleware-subrequest don't skip middleware (GHSA-f82v-jwr5-mffw)", async ({
middlewareSubrequestVuln,
}) => {
const response = await fetch(`${middlewareSubrequestVuln.url}`, {
headers: {
'x-middleware-subrequest': 'middleware:middleware:middleware:middleware:middleware',
},
})
// middleware was not skipped
expect(response.headers.get('x-test-used-middleware')).toBe('true')
// ensure we are testing version before the fix for self hosted
expect(response.headers.get('x-test-used-next-version')).toBe('15.2.2')
})
test('requests with different encoding than matcher match anyway', async ({
middlewareStaticAssetMatcher,
}) => {
const response = await fetch(`${middlewareStaticAssetMatcher.url}/hello%2Fworld.txt`)
// middleware was not skipped
expect(await response.text()).toBe('hello from middleware')
})
test.describe('RSC cache poisoning', () => {
test('Middleware rewrite', async ({ page, middleware }) => {
const prefetchResponsePromise = new Promise<Response>((resolve) => {
page.on('response', (response) => {
if (response.url().includes('/test/rewrite-to-cached-page')) {
resolve(response)
}
})
})
await page.goto(`${middleware.url}/link-to-rewrite-to-cached-page`)
// ensure prefetch
await page.hover('text=NextResponse.rewrite')
// wait for prefetch request to finish
const prefetchResponse = await prefetchResponsePromise
// ensure prefetch respond with RSC data
expect(prefetchResponse.headers()['content-type']).toMatch(/text\/x-component/)
expect(prefetchResponse.headers()['netlify-cdn-cache-control']).toMatch(/s-maxage=31536000/)
const htmlResponse = await page.goto(`${middleware.url}/test/rewrite-to-cached-page`)
// ensure we get HTML response
expect(htmlResponse?.headers()['content-type']).toMatch(/text\/html/)
expect(htmlResponse?.headers()['netlify-cdn-cache-control']).toMatch(/s-maxage=31536000/)
})
test('Middleware redirect', async ({ page, middleware }) => {
const prefetchResponsePromise = new Promise<Response>((resolve) => {
page.on('response', (response) => {
if (response.url().includes('/caching-redirect-target')) {
resolve(response)
}
})
})
await page.goto(`${middleware.url}/link-to-redirect-to-cached-page`)
// ensure prefetch
await page.hover('text=NextResponse.redirect')
// wait for prefetch request to finish
const prefetchResponse = await prefetchResponsePromise
// ensure prefetch respond with RSC data
expect(prefetchResponse.headers()['content-type']).toMatch(/text\/x-component/)
expect(prefetchResponse.headers()['netlify-cdn-cache-control']).toMatch(/s-maxage=31536000/)
const htmlResponse = await page.goto(`${middleware.url}/test/redirect-to-cached-page`)
// ensure we get HTML response
expect(htmlResponse?.headers()['content-type']).toMatch(/text\/html/)
expect(htmlResponse?.headers()['netlify-cdn-cache-control']).toMatch(/s-maxage=31536000/)
})
})