How to automate Request Trimming in Express 🤔??
Remove extra spaces from your requests like a pro
Recently I came across a bug 🐞, in which the user sent some information with extra white spaces in the end. In the backend, I forgot to trim that data. But why should I trim every string that I receive every time? so I created an NPM package that can trim all the requests and I can live a worry-free life.
You can install the package with the following command
npm i request_trimmer
Let's see it in action first:
Here we are just trimming the request body (and request query) and sending the request body back to the user.
💪 Trimming is done recursively. so It doesn’t matter how deep is your request body or any other object.
This package provides 4 express middlewares and 1 utility function.
- trim_all: This middleware trims the request body and request query. How to use it:
app.use(trim_all);
- trim_params: This middleware trims the request params. Remember that params are only available after route match. How to use it:
app.post("\posts\:id",trim_params,(req,res) => {...});
- trim_body: This middleware trims the request body.
- trim_query: This middleware trims the request query.
- trim_util: This function can trim any object. You can use this when you receive data from third-party API or you are converting your excel to JSON and then you want to trim your whole excel data.
One thing you have to remember is, You have to use express.json() middleware before using these trimming middleware as express.json() middleware only add body and query fields to request object.
I hope you find this post and this package useful. 😍