-
Notifications
You must be signed in to change notification settings - Fork 87
/
middleware.ts
60 lines (51 loc) · 1.83 KB
/
middleware.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
import type { Context } from '@netlify/edge-functions'
import type { ElementHandlers } from '../vendor/deno.land/x/[email protected]/src/index.ts'
type NextDataTransform = <T>(data: T) => T
interface ResponseCookies {
// This is non-standard that Next.js adds.
// https://github.com/vercel/next.js/blob/de08f8b3d31ef45131dad97a7d0e95fa01001167/packages/next/src/compiled/@edge-runtime/cookies/index.js#L158
readonly _headers: Headers
}
interface MiddlewareResponse extends Response {
originResponse: Response
dataTransforms: NextDataTransform[]
elementHandlers: Array<[selector: string, handlers: ElementHandlers]>
get cookies(): ResponseCookies
}
interface MiddlewareRequest {
request: Request
context: Context
originalRequest: Request
next(): Promise<MiddlewareResponse>
rewrite(destination: string | URL, init?: ResponseInit): Response
}
export function isMiddlewareRequest(
response: Response | MiddlewareRequest,
): response is MiddlewareRequest {
return 'originalRequest' in response
}
export function isMiddlewareResponse(
response: Response | MiddlewareResponse,
): response is MiddlewareResponse {
return 'dataTransforms' in response
}
export const addMiddlewareHeaders = async (
originResponse: Promise<Response> | Response,
middlewareResponse: Response,
) => {
// If there are extra headers, we need to add them to the response.
if ([...middlewareResponse.headers.keys()].length === 0) {
return originResponse
}
// We need to await the response to get the origin headers, then we can add the ones from middleware.
const res = await originResponse
const response = new Response(res.body, res)
middlewareResponse.headers.forEach((value, key) => {
if (key === 'set-cookie') {
response.headers.append(key, value)
} else {
response.headers.set(key, value)
}
})
return response
}