Add a Web Application Firewall to Your Node.js API in Five Minutes
Most Node.js APIs go to production with no request filtering at all. Input validation catches malformed data, but it is not built to spot a SQL injection hidden in a search box, a path traversal trying to read system files, or an automated scanner probing every route. That is the job of a Web Application Firewall (WAF). When I went looking for one for my own Node.js projects, I was surprised by…
A Web Application Firewall (WAF) is essential for Node.js APIs, but finding a suitable one can be challenging. The author created mini-waf, a lightweight WAF that runs as middleware inside the app, with zero runtime dependencies. It supports Express, Fastify, NestJS, and other frameworks. To install mini-waf, use the command "npm install mini-waf".
When using mini-waf, the body parser must be placed before the WAF to ensure the body is available. The WAF operates by evaluating each request against an ordered list of rules. These rules have conditions and actions, such as blocking the request, allowing it, or logging the match. Presets are available for common security concerns like SQL injection (sqli), cross-site scripting (xss), and others. You can choose from protection levels: low, balanced (default), high, or paranoid.
To set up mini-waf for Express, first import the necessary modules and create an Express app. Register the necessary body parsers before the WAF. Then, add the WAF with the desired presets and level. For Fastify, use the "fastifyWaf" plugin and configure it similarly. In NestJS, install the "MiniWafModule" and "MiniWafMiddleware", then configure the WAF in the module's "forRoot" method.
After configuring mini-waf, protect your routes as usual. The WAF will automatically protect them by filtering out malicious requests. By integrating a WAF like mini-waf into your Node.js API, you can significantly improve its security with minimal effort.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.