// npm install express helmet const express = require('express'); const helmet = require('helmet'); const app = express(); const port = 3000; // Use Helmet middleware to secure HTTP headers app.use(helmet()); // You can customize specific headers if needed: // 1. Content Security Policy (CSP) // Prevents XSS attacks by controlling which resources the browser is allowed to load. app.use( helmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'unsafe-inline'", "cdn.example.com"], // Be very specific with script sources styleSrc: ["'self'", "'unsafe-inline'", "fonts.googleapis.com"], imgSrc: ["'self'", "data:", "images.example.com"], fontSrc: ["'self'", "fonts.gstatic.com"], objectSrc: ["'none'"], // No plugins/flash upgradeInsecureRequests: [], // Automatically upgrade HTTP requests to HTTPS }, }) ); // 2. X-Content-Type-Options: nosniff // Prevents browsers from MIME-sniffing a response away from the declared Content-Type. // This is enabled by default with helmet. // 3. X-Frame-Options: DENY or SAMEORIGIN // Prevents clickjacking by forbidding rendering the page in a frame (iframe, object, embed). // Enabled by default with helmet. // 4. Strict-Transport-Security (HSTS) // Forces communication over HTTPS. Set once, browser remembers. app.use( helmet.hsts({ maxAge: 31536000, // 1 year in seconds includeSubDomains: true, // Apply to subdomains too preload: true, // Optionally allow preloading to major browsers }) ); // 5. Referrer-Policy // Controls what referrer information is sent with requests. app.use(helmet.referrerPolicy({ policy: 'no-referrer' })); // 6. X-Permitted-Cross-Domain-Policies: none (for Flash/Acrobat) // Enabled by default with helmet. // Your routes app.get('/', (req, res) => { res.send('Hello Secure World!'); }); app.listen(port, () => { console.log(`Secure server listening at http://localhost:${port}`); console.log('Check your browser\'s network tab for security headers!'); });