Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 43 ยท Security and Auth

Security Best Practices

Harden an Express app: helmet headers, CORS allow lists, rate limiting, input handling, injection, XSS, CSRF, trust proxy, HTTPS and dependency audits.

Express gives you very little security by default. It does not set protective headers, limit how often a client can call you, or clean the data that arrives. That is a deliberate part of its minimal design, and it means the checklist in this lesson is your job. The good news is that most of it is a handful of middleware and a few habits.

Security is also layered. No single package makes an app safe. You combine safe defaults (headers, HTTPS, cookies), limits (rate limits, body sizes) and careful code (parameterized queries, output escaping, authorization checks). Real packages appear below as read-only code, because npm is not available on this site. Each idea also has a runnable stand-in built on our mini Express, so you can see the mechanism work.

The hardening checklist

Headers helmet sets safe defaults.
CORS Allow only origins you trust.
Rate limits Slow down abuse and guessing.
Input and output Validate in, escape out.

Each layer catches what the others miss.

1 / 2

Security headers with helmet

Response headers tell the browser what it may do with your page. helmet sets a sensible bundle in one call:

JavaScript
import express from 'express';
import helmet from 'helmet';

const app = express();
app.disable('x-powered-by'); // helmet also removes it
app.use(helmet());

The most important headers it sends are Content-Security-Policy (which scripts and images may load), Strict-Transport-Security (always use HTTPS for this host), X-Content-Type-Options: nosniff (do not guess file types) and Referrer-Policy. Helmet's default CSP is strict. If your pages load images from a CDN or use inline scripts, you must adjust the policy deliberately instead of switching it off.

The mechanism is just res.setHeader. Here is a hand-written mini version, together with a check that the framework header is gone:

Node.js What helmet does: safer default headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real Helmet sends more headers, picks well-tested values and keeps up with browser changes. Treat the sketch as an explanation, not a replacement.

CORS: an allow list, not a wildcard

CORS controls which web pages in a browser may read your API's responses. Use an explicit list of origins:

JavaScript
import cors from 'cors';

app.use(cors({
  origin: ['https://app.example.com'],
  credentials: true, // only with an explicit origin list, never with '*'
}));

Remember the limits: CORS does not stop curl, scripts or other servers, so it never replaces authentication. See Common Third-Party Middleware for the preflight details.

Rate limiting

Without limits, one client can hammer a login route to guess passwords or exhaust your CPU. The standard package is express-rate-limit:

JavaScript
import rateLimit from 'express-rate-limit';

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  limit: 10,                // 10 attempts per window per client
  standardHeaders: true,
});

app.use('/api', rateLimit({ windowMs: 60_000, limit: 100 }));
app.post('/login', loginLimiter, loginHandler);

Use a strict limit on login, password reset and signup, and a looser one on the rest of the API. In memory (the default) counters are per process, so with several servers you need a shared store such as Redis. A fixed-window counter is easy to write:

Node.js A fixed-window rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Alice's fourth request gets 429 Too Many Requests, while Bob has his own counter. The key here is a header only to keep the demo deterministic; real limiters use req.ip.

Trust proxy and the real client address

Behind nginx, a load balancer or a CDN, every connection comes from the proxy, so req.ip would be the same for everyone and a rate limiter would block all users together. Tell Express how many proxies to trust:

JavaScript
app.set('trust proxy', 1); // one proxy in front of the app

Express then reads X-Forwarded-For and X-Forwarded-Proto, so req.ip and req.secure are correct. Set the number to your actual hop count. Using true trusts any client-supplied header, and attackers can fake their address.

Injection and input handling

Injection happens when user data is mixed into a command. For SQL, the fix is always parameterized queries: the database receives the statement and the values separately, so data can never become code.

JavaScript
// UNSAFE: the email becomes part of the SQL text
db.query(`SELECT * FROM users WHERE email = '${req.body.email}'`);

// SAFE: placeholder plus values
db.query('SELECT * FROM users WHERE email = $1', [req.body.email]);

MongoDB has a similar trap: an object such as { "$ne": null } sent as a password can match every document. Validate that fields are plain strings before using them (see Validating Input). Never pass req.body straight into a query, and never build shell commands from request data.

Validate everything at the edge: types, lengths, allowed values. Keep body sizes small with express.json({ limit: '100kb' }). Validation answers "is this acceptable?"; it is not the same as escaping, which is about output.

Cross-site scripting (XSS)

XSS happens when user text is put into HTML without escaping, so a visitor's browser runs an attacker's script. Template engines escape by default, so the usual mistakes are raw output tags and hand-built HTML strings. The rule is to escape at the point of output:

Node.js Escaping output prevents XSS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first response contains a live <script> tag. The second turns it into harmless text. Pair escaping with a strict Content-Security-Policy and with httpOnly cookies so a script that slips through cannot read the session (Cookies and Headers).

CSRF in one paragraph

Cross-site request forgery tricks a logged-in user's browser into sending a request to your site, with their cookies attached. Cookie-based sessions need protection: SameSite=Lax or Strict on the session cookie stops most cases, and a per-session CSRF token checked on every state-changing request closes the rest (see Sessions and Login). APIs that use an Authorization header instead of cookies are not exposed to classic CSRF, because browsers do not attach that header automatically.

HTTPS and dependencies

Serve everything over HTTPS. In production, a reverse proxy or platform usually terminates TLS (see Deployment and Production); your app then redirects plain HTTP and sets HSTS through Helmet. Cookies carrying sessions must have the secure flag.

Your dependencies are your attack surface too. Run npm audit regularly, update promptly, commit the lockfile, avoid abandoned packages and never run npm install with untrusted scripts on a production box. A smaller dependency list is a smaller risk.

Never put secrets (database passwords, signing keys, API tokens) in the code or the repository. Read them from environment variables, and make error responses generic: log the details on the server, and send the client only a short message.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the correct defense against SQL injection?

    Placeholders send the SQL text and the values separately, so data can never be interpreted as SQL.
  2. 2. Why must you set "trust proxy" when Express runs behind nginx?

    Without it, every request appears to come from the proxy, which breaks per-client rate limits and secure-cookie checks.
  3. 3. A fixed-window limiter allows 3 requests per minute. What should the 4th request in that minute receive?

    429 is the status for rate limiting, usually with a Retry-After header.
  4. 4. Does CORS protect your API from curl or other servers?

    CORS headers instruct browsers. Other clients ignore them, so authentication is still required.
  5. 5. Where should user text be escaped to prevent XSS?

    Escaping depends on the output context, so do it where the text is inserted into HTML.

Summary

  • Express is unsafe-by-silence: you add headers, limits and validation yourself.
  • helmet() sets protective headers; cors with an allow list controls browser access.
  • Rate-limit all APIs, and strictly limit login and signup. Use a shared store with several servers.
  • Set trust proxy to the real number of proxies so client addresses are right.
  • Use parameterized queries, validate input, escape output, and protect cookie sessions from CSRF.
  • Use HTTPS, keep secrets in the environment and audit dependencies regularly.

Next: Databases with Express.