Configure comprehensive security headers including CSP, HSTS, and other protections for production Next.js applications.
# Security Headers for Google Antigravity
Implementing proper security headers is essential for protecting web applications. This guide covers security header configuration optimized for Google Antigravity and Next.js applications.
## Next.js Security Headers Configuration
Configure comprehensive security headers in next.config.js:
```typescript
// next.config.ts
import type { NextConfig } from "next";
const securityHeaders = [
{
key: "X-DNS-Prefetch-Control",
value: "on",
},
{
key: "Strict-Transport-Security",
value: "max-age=63072000; includeSubDomains; preload",
},
{
key: "X-Frame-Options",
value: "SAMEORIGIN",
},
{
key: "X-Content-Type-Options",
value: "nosniff",
},
{
key: "X-XSS-Protection",
value: "1; mode=block",
},
{
key: "Referrer-Policy",
value: "strict-origin-when-cross-origin",
},
{
key: "Permissions-Policy",
value: "camera=(), microphone=(), geolocation=(), interest-cohort=()",
},
];
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
img-src 'self' data: https: blob:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://*.supabase.co wss://*.supabase.co https://www.google-analytics.com;
frame-src 'self' https://www.youtube.com;
media-src 'self' https://www.youtube.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'self';
upgrade-insecure-requests;
`;
const nextConfig: NextConfig = {
async headers() {
return [
{
source: "/(.*)",
headers: [
...securityHeaders,
{
key: "Content-Security-Policy",
value: ContentSecurityPolicy.replace(/\s{2,}/g, " ").trim(),
},
],
},
];
},
};
export default nextConfig;
```
## Dynamic CSP with Nonces
Implement nonce-based CSP for inline scripts:
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import 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' data: https:;
font-src 'self';
connect-src 'self' https://*.supabase.co;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`;
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-nonce", nonce);
const response = NextResponse.next({
request: { headers: requestHeaders },
});
response.headers.set(
"Content-Security-Policy",
cspHeader.replace(/\s{2,}/g, " ").trim()
);
return response;
}
// components/Script.tsx - Using nonce in components
import { headers } from "next/headers";
import Script from "next/script";
export async function NonceScript({ src }: { src: string }) {
const headersList = await headers();
const nonce = headersList.get("x-nonce") || "";
return <Script src={src} nonce={nonce} />;
}
```
## Security Headers Utility
Create a utility for managing security headers:
```typescript
// lib/security/headers.ts
interface SecurityHeadersConfig {
enableHSTS?: boolean;
hstsMaxAge?: number;
enableCSP?: boolean;
reportUri?: string;
additionalDirectives?: Record<string, string>;
}
export function generateSecurityHeaders(
config: SecurityHeadersConfig = {}
): Record<string, string> {
const {
enableHSTS = true,
hstsMaxAge = 63072000,
enableCSP = true,
reportUri,
additionalDirectives = {},
} = config;
const headers: Record<string, string> = {
"X-DNS-Prefetch-Control": "on",
"X-Frame-Options": "SAMEORIGIN",
"X-Content-Type-Options": "nosniff",
"X-XSS-Protection": "1; mode=block",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": [
"camera=()",
"microphone=()",
"geolocation=()",
"interest-cohort=()",
].join(", "),
};
if (enableHSTS) {
headers["Strict-Transport-Security"] =
`max-age=${hstsMaxAge}; includeSubDomains; preload`;
}
if (enableCSP) {
const directives = {
"default-src": "'self'",
"script-src": "'self' 'unsafe-inline'",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data: https:",
"font-src": "'self'",
"connect-src": "'self'",
"frame-ancestors": "'self'",
"base-uri": "'self'",
"form-action": "'self'",
...additionalDirectives,
};
if (reportUri) {
directives["report-uri"] = reportUri;
}
headers["Content-Security-Policy"] = Object.entries(directives)
.map(([key, value]) => `${key} ${value}`)
.join("; ");
}
return headers;
}
// Apply headers in API routes
export function withSecurityHeaders(
handler: (req: Request) => Promise<Response>
) {
return async (req: Request): Promise<Response> => {
const response = await handler(req);
const securityHeaders = generateSecurityHeaders();
Object.entries(securityHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
};
}
```
## Best Practices
When configuring security headers in Antigravity projects, start with strict CSP and relax as needed, use report-only mode during development, implement nonces for inline scripts, regularly audit and update policies, test headers with security scanners, document all CSP exceptions, and monitor CSP violation reports in production.This Security prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their security implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Security projects, consider mentioning your framework version, coding style, and any specific libraries you're using.