Security

Input Sanitization

Escape HTML in request bodies, query strings and route params with sanitize(), escapeHtml() and sanitizeObject() from @axiljs/security to reduce XSS risk.

4 min readUpdated DocumentationEdit this page
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.

❯npm install @axiljs/security
❯pnpm add @axiljs/security
❯yarn add @axiljs/security
❯bun add @axiljs/security
TypeScript
TS
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": "&lt;script&gt;alert(1)&lt;&#x2F;script&gt;" }
10  res.created(req.body)
11})

What gets escaped

CharacterBecomes
&&amp;
<&lt;
>&gt;
"&quot;
'&#x27;
/&#x2F;

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.

OptionTypeDefaultDescription
bodybooleantrueEscape every string in req.body, at any depth, with sanitizeObject()
querybooleantrueEscape req.query values that are strings or arrays of strings (top level only)
paramsbooleanfalseEscape route params. Off by default because params are usually IDs
TypeScript
TS
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:

TypeScript
TS
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.

TypeScript
TS
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.

TypeScript
TS
1import { sanitizeObject } from '@axiljs/security'
2
3sanitizeObject({ user: { bio: '<i>hi</i>' }, tags: ['<b>'], age: 30 })
4// { user: { bio: '&lt;i&gt;hi&lt;&#x2F;i&gt;' }, tags: ['&lt;b&gt;'], 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 &amp;lt;. Do not escape again on output data that was escaped on input, and do not run sanitize() twice on one request.
  • / is escaped. A URL such as https://example.com/a is stored as https:&#x2F;&#x2F;example.com&#x2F;a, which breaks links, redirects and URL validation. Validate URL fields before sanitizing, or exclude those routes.
  • Lengths change. < is one character, &lt; 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 &amp; 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.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY