-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathnext-request.js
More file actions
56 lines (48 loc) · 1.59 KB
/
next-request.js
File metadata and controls
56 lines (48 loc) · 1.59 KB
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
export function buildRequestContextFromRequest(request, body) {
return buildRequestContext({
method: request.method,
pathOrUrl: request.url,
headers: request.headers,
body
});
}
export function buildRequestContextFromOnRequestError(request) {
return buildRequestContext({
method: request.method,
pathOrUrl: request.path,
headers: request.headers
});
}
export function buildRequestContext({ method, pathOrUrl, headers, body }) {
const normalizedHeaders = normalizeHeaders(headers);
const origin = getOrigin(normalizedHeaders);
const url = new URL(pathOrUrl, origin);
return {
method,
secure: url.protocol === "https:",
ip: getClientIp(normalizedHeaders),
hostname: url.hostname,
path: url.pathname,
headers: normalizedHeaders,
params: Object.fromEntries(url.searchParams.entries()),
body
};
}
function normalizeHeaders(headers) {
if (headers instanceof Headers) {
return Object.fromEntries(Array.from(headers.entries()).map(([key, value]) => [key.toLowerCase(), value]));
}
return Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), Array.isArray(value) ? value.join(", ") : String(value)]));
}
function getOrigin(headers) {
const host = headers["x-forwarded-host"] ?? headers.host ?? "localhost";
const protocol = headers["x-forwarded-proto"] ?? "http";
return `${protocol}://${host}`;
}
function getClientIp(headers) {
const forwardedFor = headers["x-forwarded-for"];
if (forwardedFor) {
return forwardedFor.split(",")[0]?.trim() ?? "";
}
return headers["x-real-ip"] ?? "";
}