-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
Copy pathmiddleware.js
279 lines (240 loc) · 7.05 KB
/
middleware.js
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
/* global globalThis */
import { NextRequest, NextResponse, URLPattern } from 'next/server'
import { getSomeData } from './lib/some-data'
import magicValue from 'shared-package'
export const config = {
regions: 'auto',
}
const PATTERNS = [
[
new URLPattern({ pathname: '/:locale/:id' }),
({ pathname }) => ({
pathname: '/:locale/:id',
params: pathname.groups,
}),
],
[
new URLPattern({ pathname: '/:id' }),
({ pathname }) => ({
pathname: '/:id',
params: pathname.groups,
}),
],
]
const params = (url) => {
const input = url.split('?')[0]
let result = {}
for (const [pattern, handler] of PATTERNS) {
const patternResult = pattern.exec(input)
if (patternResult !== null && 'pathname' in patternResult) {
result = handler(patternResult)
break
}
}
return result
}
export async function middleware(request) {
getSomeData()
const url = request.nextUrl
if (request.headers.get('x-prerender-revalidate')) {
return NextResponse.next({
headers: { 'x-middleware': 'hi' },
})
}
// this is needed for tests to get the BUILD_ID
if (url.pathname.startsWith('/_next/static/__BUILD_ID')) {
return NextResponse.next()
}
if (
url.pathname.includes('/_next/static/chunks/pages/_app-non-existent.js')
) {
return NextResponse.rewrite('https://example.vercel.sh')
}
if (url.pathname === '/api/edge-search-params') {
const newUrl = url.clone()
newUrl.searchParams.set('foo', 'bar')
return NextResponse.rewrite(newUrl)
}
if (url.pathname === '/') {
url.pathname = '/ssg/first'
return NextResponse.rewrite(url)
}
if (url.pathname === '/to-ssg') {
url.pathname = '/ssg/hello'
url.searchParams.set('from', 'middleware')
return NextResponse.rewrite(url)
}
if (url.pathname === '/sha') {
url.pathname = '/shallow'
return NextResponse.rewrite(url)
}
if (url.pathname.startsWith('/fetch-user-agent-default')) {
try {
const apiRoute = new URL(url)
apiRoute.pathname = '/api/headers'
const res = await fetch(withLocalIp(apiRoute))
return serializeData(await res.text())
} catch (err) {
return serializeError(err)
}
}
if (url.pathname === '/rewrite-to-dynamic') {
url.pathname = '/blog/from-middleware'
url.searchParams.set('some', 'middleware')
return NextResponse.rewrite(url)
}
if (url.pathname === '/rewrite-to-config-rewrite') {
url.pathname = '/rewrite-3'
url.searchParams.set('some', 'middleware')
return NextResponse.rewrite(url)
}
if (url.pathname.startsWith('/fetch-user-agent-crypto')) {
try {
const apiRoute = new URL(url)
apiRoute.pathname = '/api/headers'
const res = await fetch(withLocalIp(apiRoute), {
headers: {
'user-agent': 'custom-agent',
},
})
return serializeData(await res.text())
} catch (err) {
return serializeError(err)
}
}
if (url.pathname === '/global') {
return serializeData(
JSON.stringify({
process: {
env: {
ANOTHER_MIDDLEWARE_TEST: process.env.ANOTHER_MIDDLEWARE_TEST,
STRING_ENV_VAR: process.env.STRING_ENV_VAR,
MIDDLEWARE_TEST: process.env.MIDDLEWARE_TEST,
NEXT_RUNTIME: process.env.NEXT_RUNTIME,
},
},
})
)
}
if (url.pathname.endsWith('/globalthis')) {
return serializeData(JSON.stringify(Object.keys(globalThis)))
}
if (url.pathname.endsWith('/webcrypto')) {
const response = {}
try {
const algorithm = {
name: 'RSA-PSS',
hash: 'SHA-256',
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
modulusLength: 2048,
}
const keyUsages = ['sign', 'verify']
await crypto.subtle.generateKey(algorithm, false, keyUsages)
} catch (err) {
response.error = true
} finally {
return serializeData(JSON.stringify(response))
}
}
if (url.pathname.endsWith('/fetch-url')) {
const response = {}
try {
await fetch(new URL('http://localhost'))
} catch (err) {
response.error = {
name: err.name,
message: err.message,
}
} finally {
return serializeData(JSON.stringify(response))
}
}
if (url.pathname === '/abort-controller') {
const controller = new AbortController()
const signal = controller.signal
controller.abort()
const response = {}
try {
await fetch('https://example.vercel.sh', { signal })
} catch (err) {
response.error = {
name: err.name,
message: err.message,
}
} finally {
return serializeData(JSON.stringify(response))
}
}
if (url.pathname.endsWith('/root-subrequest')) {
const res = await fetch(url)
res.headers.set('x-dynamic-path', 'true')
return res
}
if (url.pathname === '/about') {
if (magicValue !== 42) throw new Error('shared-package problem')
return NextResponse.rewrite(new URL('/about/a', request.url))
}
if (url.pathname === '/redirect-to-somewhere') {
url.pathname = '/somewhere'
return NextResponse.redirect(url, {
headers: {
'x-redirect-header': 'hi',
},
})
}
if (url.pathname.startsWith('/url')) {
try {
if (request.nextUrl.pathname === '/url/relative-url') {
new URL('/relative')
return Response.next()
}
if (request.nextUrl.pathname === '/url/relative-request') {
await fetch(new Request('/urls-b'))
return Response.next()
}
if (request.nextUrl.pathname === '/url/relative-redirect') {
return Response.redirect('/urls-b')
}
if (request.nextUrl.pathname === '/url/relative-next-redirect') {
return NextResponse.redirect('/urls-b')
}
if (request.nextUrl.pathname === '/url/relative-next-rewrite') {
return NextResponse.rewrite('/urls-b')
}
if (request.nextUrl.pathname === '/url/relative-next-request') {
await fetch(new NextRequest('/urls-b'))
return NextResponse.next()
}
} catch (error) {
return new NextResponse(null, { headers: { error: error.message } })
}
}
if (url.pathname === '/ssr-page') {
url.pathname = '/ssr-page-2'
return NextResponse.rewrite(url)
}
if (url.pathname === '/error-throw' && request.__isData) {
throw new Error('test error')
}
const original = new URL(request.url)
return NextResponse.next({
headers: {
'req-url-path': `${original.pathname}${original.search}`,
'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname,
'req-url-query': request.nextUrl.searchParams.get('foo'),
'req-url-locale': request.nextUrl.locale,
'req-url-params':
url.pathname !== '/static' ? JSON.stringify(params(request.url)) : '{}',
},
})
}
function serializeData(data) {
return new NextResponse(null, { headers: { data } })
}
function serializeError(error) {
return new NextResponse(null, { headers: { error: error.message } })
}
function withLocalIp(url) {
return String(url).replace('localhost', '127.0.0.1')
}