-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
104 lines (90 loc) · 3.09 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
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
import { get } from "@vercel/edge-config";
import { NextRequest, NextResponse } from "next/server";
import { env } from "@/env.mjs";
import FeatureFlags from "@/types/FeatureFlags";
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
{
source: "/((?!api|_next/static|_next/image|favicon.ico).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
};
export async function middleware(request: NextRequest) {
/*
* Generate a nonce for the CSP header
* See also:
* - https://web.dev/articles/strict-csp
* - https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy
*/
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const cspHeader = `
script-src 'nonce-${nonce}' 'unsafe-inline' 'strict-dynamic' https: http:;
object-src 'none';
base-uri 'none';
form-action 'self';
frame-ancestors 'none';
`;
// Replace newline characters and spaces
const contentSecurityPolicyHeaderValue = cspHeader
.replace(/\s{2,}/g, " ")
.trim();
// Set the nonce in the request headers so it can be read in server components
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-nonce", nonce);
requestHeaders.set(
"Content-Security-Policy",
contentSecurityPolicyHeaderValue,
);
const response = await resolveNextResponse(request, requestHeaders);
if (env.VERCEL_ENV !== "development") {
// Set the CSP header in the response
response.headers.set(
"Content-Security-Policy",
contentSecurityPolicyHeaderValue,
);
}
return response;
}
async function resolveNextResponse(request: NextRequest, headers: Headers) {
const response = NextResponse.next({ request: { headers } });
if (!env.EDGE_CONFIG || !env.VERCEL_ENV) {
// If the environment variables are not defined, log an error and continue
console.error(
"Missing environment variables for feature flags, both should be defined:",
{
EDGE_CONFIG: !!env.EDGE_CONFIG,
VERCEL_ENV: !!env.VERCEL_ENV,
},
);
return response;
}
try {
// Check whether the maintenance page should be shown
const flags = await get<FeatureFlags>(env.VERCEL_ENV);
// If it is in maintenance mode, point the url pathname to the maintenance page
if (flags?.maintenance) {
request.nextUrl.pathname = `/maintenance`;
// Rewrite to the url
return NextResponse.rewrite(request.nextUrl, { request: { headers } });
}
// If it is not in maintenance mode, but the user is trying to access the maintenance page, redirect to home page
if (request.nextUrl.pathname === "/maintenance") {
// Redirect to home page
return NextResponse.redirect(new URL("/", request.url));
}
} catch (error) {
console.error(error);
}
return response;
}