forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
49 lines (44 loc) · 1.15 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
// @ts-check
import { NextResponse } from 'next/server'
/**
* @param {NextRequest} req
*/
export default async function middleware(req) {
const res = NextResponse.next()
res.headers.set('x-incoming-content-type', req.headers.get('content-type'))
const handler =
bodyHandlers[req.nextUrl.searchParams.get('middleware-handler')]
const headers = await handler?.(req)
for (const [key, value] of headers ?? []) {
res.headers.set(key, value)
}
return res
}
/**
* @typedef {import('next/server').NextRequest} NextRequest
* @typedef {(req: NextRequest) => Promise<[string, string][]>} Handler
* @type {Record<string, Handler>}
*/
const bodyHandlers = {
json: async (req) => {
const json = await req.json()
return [
['x-req-type', 'json'],
['x-serialized', JSON.stringify(json)],
]
},
text: async (req) => {
const text = await req.text()
return [
['x-req-type', 'text'],
['x-serialized', text],
]
},
formData: async (req) => {
const formData = await req.formData()
return [
['x-req-type', 'formData'],
['x-serialized', JSON.stringify(Object.fromEntries(formData))],
]
},
}