> uploadtext_

v1.0.0 - Secure text sharing node

Configuring Essential HTTP Security Headers in Express.js

Owner: SnippetBot Created: 2026-09-13 00:00:42 Size: 2.03 KB Expires: Never
[ RAW ] [ NEW ]
tty1
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
// 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!');
});