EthicsComputerCourses
Join training +91 90532 10052

Security Checklist for MERN

MERN Stack · Lesson 16 of 20 Intermediate 12 min read Updated

By the end of this lesson you will have taken TaskBoard through a security review, the way a team does before launch. You will rate-limit the login, tighten Helmet's Content Security Policy, prove that NoSQL injection cannot get through, choose between short sessions and refresh tokens, audit your packages, and check that no secret can leak through Git.

What you should know first: Login, Protected Routes & Sessions and Testing the MERN App, because this lesson adds tests to that suite. General Node.js advice is in Security Best Practices and OWASP API Security Top 10. Versions checked: express-rate-limit 8.7.4, helmet 8.3.0, Express 5.3.0 and Mongoose 9.12.1. Every output below comes from a real run.

What earlier lessons already did

Think of a bank branch in Rohtak before opening day. The guard and the lockers are in place, but the manager still walks through with a checklist, because one open window undoes the rest. Much of TaskBoard's security was built lesson by lesson:

ThreatDefence already in TaskBoard
Leaked password databaseArgon2id hashes, never sent to clients
Token theft through XSSJWT in an HttpOnly, Secure, SameSite=Strict cookie
Other sites reading the APICORS allow-list
Bad or huge inputZod schemas and a 10 KB body limit
Leaking stack tracesOne error handler
Harmful uploadsSize and type checks, private folder

Five gaps remain: password guessing, Helmet's unreviewed defaults, untested injection defences, unaudited packages and unchecked secrets.

Step 1: Rate-limit the login

A rate limit caps how many requests one client may send in a time window. A railway ticket counter that sells each person only a few tickets stops one tout from buying the whole train. Without a limit, a script can try thousands of passwords against priya@example.com.

Install express-rate-limit into the server workspace from the top folder:

Terminal
npm install express-rate-limit -w server

Create server/src/middleware/rateLimits.js with two limiters:

JavaScript
import { rateLimit } from "express-rate-limit";
import { HttpError } from "../utils/httpError.js";

// Sends the usual { error: { message } } shape instead of the library's plain text.
function tooMany(message) {
  return (req, res, next, options) => next(new HttpError(options.statusCode, message));
}

// Every /api request: generous, only there to stop floods and runaway scripts.
export const apiLimiter = rateLimit({
  windowMs: 60 * 1000,
  limit: 300,
  standardHeaders: "draft-8",
  legacyHeaders: false,
  handler: tooMany("Too many requests. Please slow down."),
});

// Login: 10 failed tries per IP address in 15 minutes. Successful logins are not counted.
export const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  limit: 10,
  skipSuccessfulRequests: true,
  standardHeaders: "draft-8",
  legacyHeaders: false,
  handler: tooMany("Too many failed logins. Try again in 15 minutes."),
});

windowMs is the window length and limit the requests allowed in it. skipSuccessfulRequests uncounts 2xx replies, so correct logins use none of the allowance. standardHeaders: "draft-8" sends the IETF draft's RateLimit headers instead of the older X-RateLimit-* ones. The handler gives a 429 Too Many Requests reply the usual error shape.

Mount them. In app.js, add app.use("/api", apiLimiter); right after app.use(requestLogger);. In auth.routes.js, put the login limiter first:

JavaScript
authRouter.post("/login", loginLimiter, validateBody(loginSchema), login);

We sent eleven wrong passwords, then the right one:

Output
try  1: {"error":{"message":"Email or password is incorrect"}} 401
...
try 10: {"error":{"message":"Email or password is incorrect"}} 401
try 11: {"error":{"message":"Too many failed logins. Try again in 15 minutes."}} 429

HTTP/1.1 429 Too Many Requests
RateLimit: "300-in-1min"; r=287; t=42
RateLimit: "10-in-15min"; r=0; t=895
Retry-After: 895
{"error":{"message":"Too many failed logins. Try again in 15 minutes."}}

(Tries 2 to 9 and most headers are left out.) The last request had the correct password and was still refused: guessing has stopped. In each RateLimit line, r is the requests left and t the seconds until the window resets.

Add server/test/rateLimit.test.js, a separate file because Vitest gives each file a fresh in-memory counter:

JavaScript
it("blocks the 11th failed login from one address, even with the right password", async () => {
  const login = (password) => request(app).post("/api/auth/login").send({ email: "priya@example.com", password });
  for (let i = 1; i <= 10; i++) await login(`guess-${i}`).expect(401);
  const res = await login(PASSWORD).expect(429);
  expect(res.body.error.message).toBe("Too many failed logins. Try again in 15 minutes.");
  expect(res.headers["retry-after"]).toBeDefined();
}, 30_000); // eleven Argon2 checks are slow on purpose

Our first version had no 30_000 and failed with Test timed out in 5000ms, because eleven slow Argon2 checks take longer than Vitest's default. With it, all 12 server tests passed.

Know two limits. The counter is per IP address, and the whole staff room shares one public address on its Wi-Fi, so one person's typos count for all. And the default store lives in memory, so it resets on restart and is not shared between server processes; bigger apps use a shared store such as Redis. The demo below runs the same rule in your browser.

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const LIMIT = 10;

function RateLimitDemo() {
  const [hits, setHits] = useState({}); // ip -> failed logins in this window
  const [log, setLog] = useState([]);

  function tryLogin(ip, label) {
    const used = hits[ip] ?? 0;
    const reply = used >= LIMIT ? "429 Too many failed logins" : "401 Email or password is incorrect";
    if (used < LIMIT) setHits({ ...hits, [ip]: used + 1 });
    setLog((l) => [...l.slice(-5), `${label} (${ip}): ${reply}`]);
  }

  return (
    <div>
      <button onClick={() => tryLogin("198.51.100.20", "Staff room Wi-Fi")}>Wrong password from Wi-Fi</button>{" "}
      <button onClick={() => tryLogin("203.0.113.7", "Phone on mobile data")}>Wrong password from phone</button>{" "}
      <button onClick={() => setHits({})}>15 minutes pass</button>
      <p>Failed tries used: {Object.entries(hits).map(([ip, n]) => `${ip} = ${n}/${LIMIT}`).join(", ") || "none"}</p>
      <pre>{log.join("\n")}</pre>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<RateLimitDemo />);

Click the Wi-Fi button eleven times: the eleventh reply is 429, yet the phone still gets normal replies because it has its own address. "15 minutes pass" resets every counter.

Step 2: Review Helmet and the CSP

A review means reading what helmet() actually sends. These are the main headers from GET /api/health, after the change below:

Output
Content-Security-Policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'none';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self';upgrade-insecure-requests
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN

A Content Security Policy (CSP) tells the browser where a page may load scripts, styles, images and frames from. It is the best second defence against XSS: even if an attacker slips a <script> into a page, the browser refuses code the policy does not allow. For JSON replies it does little, but in Deploying a MERN App the same server will also send the React app's index.html.

So check the policy against the built client. Vite's index.html loads one script and one CSS file from /assets/, with no inline code, and images come from /api/... on the same origin. That allows two tighter settings:

JavaScript
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        "style-src": ["'self'"], // the built CSS is a file; no inline styles needed
        "frame-ancestors": ["'none'"], // no site may show TaskBoard inside a frame
      },
    },
  })
);

Helmet keeps its other defaults and replaces only these two. The default style-src also allowed https: and 'unsafe-inline', which TaskBoard does not need. frame-ancestors 'none' stops other sites loading TaskBoard in a hidden frame to trick a teacher into clicking, called clickjacking. We served the production build with this policy and logged in as Kabir in Chrome: the console showed no CSP violation, only the expected 401 from /api/auth/me before login.

Step 3: Prove NoSQL injection is blocked

NoSQL injection means sending a MongoDB operator where the server expects a plain value, such as a login with {"email": {"$ne": null}} ("any email that is not null"). TaskBoard has three layers against it.

  1. Zod checks types first. email must be a string that looks like an email.
  2. Express 5 parses query strings simply. ?status[$ne]=done arrives as a key named status[$ne], which the query schema ignores.
  3. Mongoose's sanitizeFilter is a safety net for any route that forgets layer 1.

Here are the first two layers answering real attacks:

Output
POST /api/auth/login {"email":{"$ne":null},"password":{"$ne":null}}
  400 {"error":{"message":"Validation failed","details":[{"field":"email","message":"Enter a valid email address"},{"field":"password","message":"Password is required"}]}}
GET  /api/tasks?status[$ne]=done
  200 (all three tasks: the unknown key was dropped)

For the third layer, add one line to server/src/models/index.js, which every controller and test already imports:

JavaScript
import mongoose from "mongoose";

// Defence in depth: an object with $ keys in a query filter is treated as a plain value.
mongoose.set("sanitizeFilter", true);

To see why it helps, we ran a script that copies a careless route: it passes { $ne: null } straight into User.findOne({ email }), once without the setting and once with it:

Output
without sanitizeFilter: kabir@example.com
with sanitizeFilter:    CastError Cast to string failed for value "{ '$ne': null }" (type Object) at path "email" for model "User"

Without the setting, "any email" returned the first user: in a login route, that means logging in as Kabir. With it, Mongoose wraps the object in $eq, so it must match literally, and the String schema rejects it (the error handler turns the CastError into a 400). Operators written in your own code still work; mongoose.trusted() marks a filter as safe.

Short sessions or refresh tokens?

The auth UI lesson promised this discussion. TaskBoard uses one JWT that lasts two hours. Many apps use two tokens instead. An access token is short-lived (often 5 to 15 minutes) and goes with every request. A refresh token lasts days, goes only to one refresh route, and is exchanged there for a new access token. The server stores refresh tokens, so it can cancel them.

QuestionOne 2-hour session (TaskBoard)Access + refresh tokens
How long a stolen token worksUp to 2 hoursAccess token: minutes. Refresh token: until revoked
Log out everywhere at onceNot possible until exp, without extra workDelete the user's refresh tokens
Teacher signs in againEvery 2 hoursEvery few days
Extra codeNoneRefresh route, token table, rotation, a client retry

For a staff room where people log in each morning, one short session is simpler and safe enough. Refresh tokens pay off when users expect to stay signed in for weeks, or an admin must cut off a stolen laptop at once. If you add them, keep the refresh token in its own HttpOnly cookie, store only its hash, issue a new one on every use (rotation), and treat reuse of an old one as theft. TaskBoard already reads the user from the database on every request, so deleting a user takes effect at once.

Step 4: Audit your dependencies

TaskBoard runs code from over 300 npm packages. npm audit compares your lock file with a database of known vulnerabilities:

Terminal
npm audit
npm audit --omit=dev
npm outdated
Output
found 0 vulnerabilities
found 0 vulnerabilities
Package       Current  Wanted  Latest  Location                   Depended by
oxlint         1.93.0  1.94.0  1.94.0  node_modules/oxlint        client@0.0.0
react-router    8.5.1   8.5.1  7.18.5  node_modules/react-router  client@0.0.0

--omit=dev audits only what runs in production. In the npm outdated list, react-router shows 7.18.5 as "Latest" because react-router 8 needs Node.js 22.22 or newer and the test machine runs 22.14. Read version advice before following it. When npm audit reports a problem, update the direct dependency that pulls it in and run the tests; avoid npm audit fix --force, which can jump major versions. Commit package-lock.json and install on servers with npm ci, which installs exactly the locked versions.

Step 5: Keep secrets out of Git and logs

A secret is any value that gives power to whoever holds it, such as JWT_SECRET or the password inside MONGODB_URI. Ask Git whether the real .env is protected:

Terminal
git check-ignore -v server/.env server/uploads/x.png
Output
.gitignore:3:.env	server/.env
.gitignore:8:server/uploads/	server/uploads/x.png

Git names the rule that ignores each file. Then:

  • Use different secrets for development, tests and production.
  • Never log secrets or whole request bodies; the request logger prints only the method, path and status.
  • If a secret reaches a commit, deleting the file is not enough, because history keeps it. Rotate it: a new JWT_SECRET signs everyone out, which is what you want.
  • Give the database user only readWrite on taskboard, as in Set Up Your MERN Environment.

Common mistakes

  • Rate-limiting behind a proxy without trust proxy. Every visitor then shares the proxy's address and one counter; the deployment lesson fixes this.
  • express-mongo-sanitize on Express 5. It crashes every request; use validation and sanitizeFilter.
  • Turning off the CSP because something broke. Find the blocked source in the console and allow only that.

Interview questions

1. How would you protect a login endpoint against password guessing?

Use slow hashing such as Argon2id, the same message for unknown emails and wrong passwords, and a rate limit on failed attempts per IP that returns 429 with Retry-After. Larger systems add per-account checks and a shared store such as Redis.

2. What is NoSQL injection, and how do you prevent it in a MERN app?

It is sending operators such as $ne inside JSON or query strings so a filter matches more than intended. Validate types with a schema before any query, keep Express 5's simple query parser, and enable Mongoose's sanitizeFilter as a safety net. Never pass req.body straight into a filter.

3. What does a Content Security Policy protect against?

It limits where a page may load scripts, styles, images and frames from, so injected scripts usually cannot run and clickjacking frames are blocked. It is a second layer after output escaping, not a replacement.

Key points

  • loginLimiter allows 10 failed logins per IP in 15 minutes, then replies 429; apiLimiter caps every /api route.
  • Read Helmet's headers; TaskBoard tightens the CSP with style-src 'self' and frame-ancestors 'none'.
  • Zod types, Express 5's simple query parser and sanitizeFilter block NoSQL injection.
  • One short session is simpler; refresh tokens add long sign-ins and instant revocation for more code.
  • Run npm audit, commit the lock file and deploy with npm ci.
  • Keep secrets in ignored .env files, separate per environment, and rotate any that leak.

Exercise

Add a limiter for attachment uploads: at most 20 files per signed-in user in 10 minutes, counted per user rather than per IP address, so teachers on the shared Wi-Fi do not affect each other. Use the keyGenerator option, decide where it must sit so that req.user exists, and test that the 21st upload gets 429.

Show solution
JavaScript
// rateLimits.js
export const uploadLimiter = rateLimit({
  windowMs: 10 * 60 * 1000,
  limit: 20,
  keyGenerator: (req) => req.user.id, // one counter per signed-in user
  standardHeaders: "draft-8",
  legacyHeaders: false,
  handler: tooMany("Too many uploads. Try again in a few minutes."),
});

// tasks.routes.js: the router is mounted behind requireAuth, so req.user exists here
tasksRouter.post("/:id/attachments", uploadLimiter, uploadOneFile, addAttachment);

The limiter must come after requireAuth, which guards the whole router, and before multer, so a blocked user's file is never read. Refused uploads count too: in our test, Priya's first 5 uploads got 201 and the next 15 got 409 (a task holds at most 5 files), then the 21st got 429. Kabir could still upload, because the key is the user id.

Quick Quiz

1. A teacher types the correct password after ten failed tries from the same Wi-Fi. What does TaskBoard reply?

2. Why did TaskBoard drop 'unsafe-inline' from style-src?

3. What does mongoose.set("sanitizeFilter", true) do with { email: { $ne: null } } in a filter?

4. Which command installs exactly the versions in package-lock.json on a server?

Learn MERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call