Skip to content

Instantly share code, notes, and snippets.

@nsdevaraj
Created August 5, 2024 14:11
Show Gist options
  • Save nsdevaraj/015fa9664baeaa7cc8c13ff17557b044 to your computer and use it in GitHub Desktop.
Save nsdevaraj/015fa9664baeaa7cc8c13ff17557b044 to your computer and use it in GitHub Desktop.
Prevention of Cross-Site Scripting (XSS) Attacks
import express from 'express';
import helmet from 'helmet';
const app = express();
// Use helmet to set various HTTP headers
app.use(helmet());
// Set a custom Content Security Policy
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
},
}));
app.get('/hello', (req, res) => {
const name = req.query.name;
// Ensure proper encoding when rendering user input
res.send(`<h1>Hello ${encodeURIComponent(name as string)}!</h1>`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment