Node.js
Security
Add JWT, helmet and rate limiting.
The security middleware
In this lesson we add a security middleware to the skeleton. Express's app.use method defines middlewares that run before all requests. Security headers, authentication and rate limiting are done here.
Example: app.use((req, res, next) => { res.setHeader("X-Content-Type-Options", "nosniff"); next(); });. This middleware adds a security header to every request and passes to the next layer. The next() call lets the chain continue; without it the request gets no response. In production, libraries like helmet add common security headers automatically. Authentication, CORS and rate limiting are also added as middleware. Middlewares are the foundation of Express's security model.
The next() concept
A middleware calls next() when it is done. This tells Express to move to the next middleware or route. If next() is not called, the request never gets a response; it hangs.
Example: app.use((req, res, next) => { if (!req.headers.authorization) return res.status(401).end(); next(); });. This middleware returns 401 if there is no authorization header; if there is, it passes to the next layer with next(). This pattern is common in authentication middlewares. next(err) can also pass an error; this goes to the error middleware. Middleware order matters; security middlewares are added before routes. This ensures all requests go through security first.
Exercise Add the security middleware
Add app.use((req, res, next) => { next(); }) to the skeleton below. Print "Security ready" with console.log.
Show example solution
const express = require("express");
const app = express();
app.get("/", (req, res) => res.json({ status: "ok" }));
const db = { ready: true };
app.get("/db", (req, res) => res.json({ db: db.ready }));
const io = { on: () => {} };
app.use((req, res, next) => { next(); });
console.log("Security ready");
Test yourself
-
Complete the next call
app.use((req, res, next) => { res.setHeader("X", "Y"); ____(); });
Show answer
app.use((req, res, next) => { res.setHeader("X", "Y"); next(); });
-
When is app.use called?
app.use((req, res, next) => { next(); })
- Only on one route
- Only when the server closes
- Only on error
- Before all requests
Show answer
Before all requests — app.use is called before all requests.
-
Match each piece to its role
- app.use
- Adds a middleware
- next()
- Continues the chain
- res.setHeader
- Adds a header
- helmet
- Security library
Next lesson: Putting it together