UNPKG

@nosecone/next

Version:

Protect your Next.js application with secure headers

57 lines (54 loc) 1.84 kB
import nosecone, { defaults as defaults$1 } from 'nosecone'; export { default, default as nosecone, withVercelToolbar } from 'nosecone'; /** * Nosecone Next.js defaults. */ const defaults = { ...defaults$1, contentSecurityPolicy: { directives: { ...defaults$1.contentSecurityPolicy.directives, scriptSrc: [ ...defaults$1.contentSecurityPolicy.directives.scriptSrc, ...nextScriptSrc(), ], styleSrc: [ ...defaults$1.contentSecurityPolicy.directives.styleSrc, ...nextStyleSrc(), ], }, }, }; function nonce() { return `'nonce-${btoa(crypto.randomUUID())}'`; } function nextScriptSrc() { return process.env.NODE_ENV === "development" ? // Next.js hot reloading relies on `eval` so we enable it in development [nonce, "'unsafe-eval'"] : [nonce]; } function nextStyleSrc() { return ["'unsafe-inline'"]; } /** * Create Next.js middleware that sets secure headers on every request. * * @param options * Configuration to provide to Nosecone. * @returns * Next.js middleware that sets secure headers. */ function createMiddleware(options = defaults) { return async () => { const headers = nosecone(options); // Setting this specific header is the way that Next.js implements // middleware. See: // https://github.com/vercel/next.js/blob/5c45d58cd058a9683e435fd3a1a9b8fede8376c3/packages/next/src/server/web/spec-extension/response.ts#L148 // Note: we don't create the `x-middleware-override-headers` header so // the original headers pass through headers.set("x-middleware-next", "1"); return new Response(null, { headers }); }; } export { createMiddleware, defaults };