0
0
Expressframework~5 mins

Sanitization methods in Express

Choose your learning style9 modes available
Introduction

Sanitization methods clean user input to keep your app safe and working well.

When you get data from a user form to avoid harmful code.
Before saving user input to a database to prevent errors or attacks.
When displaying user input on a webpage to stop unwanted scripts.
To make sure email or phone inputs have the right format.
When you want to remove extra spaces or unwanted characters from input.
Syntax
Express
body('fieldName').trim().escape()
Use chains like body() or query() from express-validator middleware.
Chain sanitization methods like trim(), escape(), or normalizeEmail().
Examples
Removes spaces before and after the username input.
Express
body('username').trim()
Converts special characters to safe HTML entities to prevent scripts.
Express
body('comment').escape()
Formats the email input to a standard form.
Express
body('email').normalizeEmail()
Sample Program

This Express app cleans user inputs for username, email, and comment using sanitization methods before using them.

Express
import express from 'express';
import { body, validationResult } from 'express-validator';

const app = express();
app.use(express.urlencoded({ extended: true }));

app.post('/submit', [
  body('username').trim().escape(),
  body('email').normalizeEmail(),
  body('comment').trim().escape()
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send(`Cleaned input:\nUsername: ${req.body.username}\nEmail: ${req.body.email}\nComment: ${req.body.comment}`);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
OutputSuccess
Important Notes

Sanitization helps protect your app from harmful input like scripts or bad data.

Always sanitize inputs before saving or displaying them.

Use libraries like express-validator for easy sanitization in Express.

Summary

Sanitization cleans user input to keep apps safe.

Use methods like trim(), escape(), and normalizeEmail().

Sanitize before saving or showing data.