Learn / Frameworks / Express / Helmet, CORS and Rate Limits

Express · Lesson 9 of 15

Helmet, CORS and Rate Limits

Secure headers, an origin allow-list and brute-force protection on login.

  • Intermediate
  • 15 min read
  • 3 objectives

Before this lessonLesson 8: File Uploads with Multer

What you will learn

  • Add helmet
  • Configure CORS
  • Rate-limit /login

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Three packages cover a surprising amount of production hygiene: Helmet for headers, cors for browsers, express-rate-limit for brute force.

Helmet and CORS

import helmet from "helmet";
import cors from "cors";

app.use(helmet());
app.use(cors({
  origin: ["https://app.example.com"],
  credentials: true,
  methods: ["GET", "POST", "PATCH", "DELETE"],
}));

Rate limits

import rateLimit from "express-rate-limit";

const loginLimiter = rateLimit({
  windowMs: 60_000,
  limit: 5,
  standardHeaders: "draft-7",
  legacyHeaders: false,
});
app.post("/login", loginLimiter, loginHandler);

app.use("/api", rateLimit({ windowMs: 60_000, limit: 100 }));

Body size

app.use(express.json({ limit: "32kb" }));
Up next · Lesson 10Testing with SupertestHit your app with supertest, isolate the database and assert on status and body.