0
0
Expressframework~5 mins

Request body transformation in Express

Choose your learning style9 modes available
Introduction

Request body transformation helps change the data sent by a user before your app uses it. This makes it easier to work with or safe to store.

When you want to change date strings into JavaScript Date objects.
When you need to rename or remove some fields from the incoming data.
When you want to add default values if some data is missing.
When you want to clean or format user input before saving it.
When you want to validate and transform data in one step.
Syntax
Express
app.use(express.json());

app.post('/path', (req, res) => {
  const transformedBody = transformFunction(req.body);
  // use transformedBody for your logic
  res.send(transformedBody);
});

Use express.json() middleware to parse JSON request bodies first.

Transformation happens inside the route handler after parsing.

Examples
Trim spaces from the name field before using it.
Express
app.post('/user', (req, res) => {
  const body = req.body;
  body.name = body.name.trim();
  res.send(body);
});
Convert date string to a Date object for easier date handling.
Express
app.post('/date', (req, res) => {
  const body = req.body;
  body.date = new Date(body.date);
  res.send(body);
});
Remove sensitive password field before sending response.
Express
app.post('/clean', (req, res) => {
  const { password, ...safeData } = req.body;
  res.send(safeData);
});
Sample Program

This Express app listens for POST requests at /transform. It changes the request body by trimming the name, turning age into a number, and converting the joined date string into a Date object. Then it sends back the transformed data as JSON.

Express
import express from 'express';

const app = express();
app.use(express.json());

app.post('/transform', (req, res) => {
  const { name, age, joined } = req.body;

  // Transform: trim name, convert age to number, convert joined to Date
  const transformed = {
    name: name.trim(),
    age: Number(age),
    joined: new Date(joined)
  };

  res.json(transformed);
});

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

Always parse JSON body with express.json() before transforming.

Be careful with data types; converting strings to numbers or dates helps avoid bugs.

Transformation can also help improve security by removing unwanted fields.

Summary

Request body transformation changes incoming data to a better format.

It happens after parsing the JSON body in Express.

Use it to clean, convert, or remove data before using it in your app.