SyntaxStudy
Sign Up
Express.js Built-in and Third-Party Middleware
Express.js Beginner 1 min read

Built-in and Third-Party Middleware

Express 4.16+ ships with three built-in middleware functions: `express.json()` parses `application/json` request bodies, `express.urlencoded()` parses HTML form submissions, and `express.static()` serves files from a directory. These cover the most common needs without additional dependencies. `express.static()` is especially powerful — it takes a root directory path and optional options for cache control, index file, dotfile handling, and more. Placing static middleware early in the chain means asset requests never hit route handlers. For everything else, npm has a rich ecosystem: `cors` for cross-origin headers, `multer` for multipart file uploads, `express-rate-limit` for IP-based throttling, `express-validator` for input validation, and `cookie-parser` for cookie handling. These all follow the same middleware interface, so integration requires only `app.use(package(options))`.
Example
const express      = require('express');
const cors         = require('cors');
const rateLimit    = require('express-rate-limit');
const cookieParser = require('cookie-parser');
const path         = require('path');
const app          = express();

// ── CORS ──────────────────────────────────────────────────────
app.use(cors({
    origin: ['https://example.com', 'http://localhost:3000'],
    methods: ['GET','POST','PUT','DELETE'],
    credentials: true,
}));

// ── Static files ──────────────────────────────────────────────
app.use('/static', express.static(path.join(__dirname, 'public'), {
    maxAge: '1d',
    etag:   true,
}));

// ── Body parsers ──────────────────────────────────────────────
app.use(express.json({ limit: '512kb' }));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser(process.env.COOKIE_SECRET));

// ── Rate limiting (100 req / 15 min per IP) ───────────────────
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use('/api/', limiter);

app.get('/api/test', (req, res) => {
    res.json({ cookie: req.signedCookies });
});

app.listen(3000);