Input Sanitization
Escape HTML in request bodies, query strings and route params with sanitize(), escapeHtml() and sanitizeObject() from @axiljs/security to reduce XSS risk.
On this page6
@axiljs/security escapes HTML special characters so that user input rendered into a page shows up as text instead of running as markup. It gives you three tools: the sanitize() middleware for whole requests, sanitizeObject() for nested data, and escapeHtml() for single strings.
1import { Application } from '@axiljs/core'
2import { sanitize } from '@axiljs/security'
3
4const app = new Application()
5app.use(sanitize())
6
7app.post('/comments', (req, res) => {
8 // body { "text": "<script>alert(1)</script>" }
9 // arrives as { "text": "<script>alert(1)</script>" }
10 res.created(req.body)
11})What gets escaped
| Character | Becomes |
|---|---|
& | & |
< | < |
> | > |
" | " |
' | ' |
/ | / |
Nothing is removed: tags and attributes stay in the string, but as inert text. This is escaping, not an HTML allow-list sanitizer, so it cannot keep "safe" tags such as <b> while dropping <script>.
sanitize(options?)
Middleware that escapes request data in place, before your handlers see it.
| Option | Type | Default | Description |
|---|---|---|---|
body | boolean | true | Escape every string in req.body, at any depth, with sanitizeObject() |
query | boolean | true | Escape req.query values that are strings or arrays of strings (top level only) |
params | boolean | false | Escape route params. Off by default because params are usually IDs |
app.use(sanitize({ body: true, query: true, params: true }))Object keys are never escaped, only values. Numbers, booleans and null pass through unchanged. Route params are already set when global middleware runs, so params: true works with app.use().
To protect only some routes, pass it as route middleware instead of registering it globally:
app.post('/comments', sanitize(), createComment)escapeHtml(str)
Escapes one string. This is the safest place to escape: at output, right where user data is placed into HTML.
1import { escapeHtml } from '@axiljs/security'
2
3app.get('/hello', (req, res) => {
4 const name = escapeHtml(String(req.query.name ?? 'guest'))
5 res.html(`<h1>Hello, ${name}</h1>`)
6})sanitizeObject(value)
Returns a sanitized copy of any value: strings are escaped, arrays and plain objects are walked recursively, and other types are returned as they are. Use it on data that did not come through a request, such as a queue message or a webhook payload you stored.
1import { sanitizeObject } from '@axiljs/security'
2
3sanitizeObject({ user: { bio: '<i>hi</i>' }, tags: ['<b>'], age: 30 })
4// { user: { bio: '<i>hi</i>' }, tags: ['<b>'], age: 30 }A __proto__ key in the input is copied as an ordinary own property, so a crafted JSON body cannot replace the prototype of the result.
sanitizeObject() is meant for JSON-shaped data. Class instances such as Date are walked like plain objects and come back as {}.
Things to know before enabling it globally
Escaping on input changes the data you store. Keep these effects in mind:
- It is not idempotent. Escaping twice gives
&lt;. Do not escape again on output data that was escaped on input, and do not runsanitize()twice on one request. /is escaped. A URL such ashttps://example.com/ais stored ashttps://example.com/a, which breaks links, redirects and URL validation. Validate URL fields before sanitizing, or exclude those routes.- Lengths change.
<is one character,<is four. Run validation length checks with that in mind. - Non-HTML consumers see entities. Mobile apps, CSV exports and emails in plain text show
&literally.
Tip
For most APIs, the cleaner rule is: validate on input, store the raw value, and escape on output with escapeHtml() (or let your template engine or frontend framework escape it). Use sanitize() when the data will be rendered as HTML by consumers you do not control.
Note
Escaping HTML does nothing against SQL injection. Use parameterised queries, which the ORM query builder does for you.
Related
- Validation middleware
- Helmet security headers: a Content-Security-Policy is the second line of defence against XSS
- CSRF protection
- Rate limiting
Was this page helpful?