Skip to content

Commit

Permalink
feat(docs): add CSP
Browse files Browse the repository at this point in the history
  • Loading branch information
branko-stripe committed Oct 30, 2024
1 parent e95da4d commit 23defb5
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
59 changes: 59 additions & 0 deletions apps/docs/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { NextResponse, type NextRequest } from "next/server";

export function middleware(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");

const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
style-src 'self' 'nonce-${nonce}';
img-src 'self' blob: data:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`;

// Replace newline characters and spaces
const contentSecurityPolicyHeaderValue = cspHeader.replace(/\s{2,}/g, " ").trim();

const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-nonce", nonce);

if (process.env.NODE_ENV === "production") {
requestHeaders.set("Content-Security-Policy", contentSecurityPolicyHeaderValue);
}

const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});

if (process.env.NODE_ENV === "production") {
response.headers.set("Content-Security-Policy", contentSecurityPolicyHeaderValue);
}

return response;
}

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" },
],
},
],
};
3 changes: 2 additions & 1 deletion turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"NEXT_PUBLIC_DOCSEARCH_INDEX_NAME",
"WEBFLOW_API_KEY",
"WEBFLOW_BLOG_ID",
"WEBFLOW_CASE_STUDIES_ID"
"WEBFLOW_CASE_STUDIES_ID",
"NODE_ENV"
]
},
"clean": {
Expand Down

0 comments on commit 23defb5

Please sign in to comment.