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.
Request body transformation in 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.
app.post('/user', (req, res) => {
const body = req.body;
body.name = body.name.trim();
res.send(body);
});app.post('/date', (req, res) => {
const body = req.body;
body.date = new Date(body.date);
res.send(body);
});app.post('/clean', (req, res) => {
const { password, ...safeData } = req.body;
res.send(safeData);
});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.
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'); });
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.
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.