Created
August 5, 2024 14:11
-
-
Save nsdevaraj/015fa9664baeaa7cc8c13ff17557b044 to your computer and use it in GitHub Desktop.
Prevention of Cross-Site Scripting (XSS) Attacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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