-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
48 lines (43 loc) · 1.2 KB
/
Copy pathmiddleware.ts
File metadata and controls
48 lines (43 loc) · 1.2 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
import { NextRequest, NextResponse } from "next/server";
function makeNonce(): string {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
let raw = "";
for (const byte of bytes) raw += String.fromCharCode(byte);
return btoa(raw);
}
function csp(nonce: string): string {
return [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}'`,
"style-src 'self'",
"style-src-elem 'self'",
"style-src-attr 'unsafe-inline'",
"img-src 'self' data:",
"font-src 'self' data:",
"connect-src 'self'",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
"object-src 'none'",
].join("; ");
}
export function middleware(req: NextRequest) {
const nonce = makeNonce();
const policy = csp(nonce);
const requestHeaders = new Headers(req.headers);
requestHeaders.set("x-nonce", nonce);
requestHeaders.set("content-security-policy", policy);
const res = NextResponse.next({
request: { headers: requestHeaders },
});
res.headers.set("Content-Security-Policy", policy);
return res;
}
export const config = {
matcher: [
{
source: "/((?!_next/static|_next/image|favicon.ico|icon.svg|robots.txt|sitemap.xml).*)",
},
],
};