Securing your API

Topic 4 of 4 in Authentication & security9 min readIntermediateFree course

Overview

An API on the internet is probed by automated scanners within minutes of going live. You don’t need to be a security expert to stop the vast majority of attacks — you need to consistently apply a set of well-known defences, each covering gaps the others leave.

Layers of defence from the outside in: HTTPS and a reverse proxy with body size limits and timeouts; rate limiting against brute force and scraping; helmet and CORS for safe headers and allowed sites; authentication; authorisation for each record; validation; safe data access with parameterised SQL and a least-privilege database user; and secrets and dependencies kept in environment variables, audited and updated. No single layer is perfect.

You’ve already built several layers: validation (Validating input), parameterised SQL (PostgreSQL with node-postgres), password hashing, sessions and JWTs. This topic adds the rest.

Security headers with helmet

Terminal
npm install helmet
JavaScript
import helmet from 'helmet';
app.use(helmet());
app.disable('x-powered-by'); // don't advertise "Express"

helmet sets a collection of HTTP headers that tell browsers to behave more safely — for example Strict-Transport-Security (always use HTTPS), X-Content-Type-Options: nosniff (don’t guess file types), and a Content-Security-Policy that limits where scripts may load from. It’s one line and should be in every Express app.

CORS

Browsers block a page on one origin (say app.academy.com) from reading responses from another (api.academy.com) unless the API says it’s allowed. That permission system is CORS (Cross-Origin Resource Sharing).

The browser on app.academy.com first sends OPTIONS /courses with an Origin header. The API responds 204 with Access-Control-Allow-Origin naming that origin. The browser then sends the real POST /courses, and the API responds 201 with the Allow-Origin header. CORS is enforced by browsers only; it is not authentication for your API.

Terminal
npm install cors
JavaScript
import cors from 'cors';

const allowedOrigins = ['https://app.academy.com', 'http://localhost:5173'];

app.use(cors({
  origin: allowedOrigins,      // exact list — never reflect any origin
  credentials: true,           // allow cookies
  methods: ['GET', 'POST', 'PATCH', 'DELETE'],
}));

Two important points:

  • Don’t use origin: '*' with credentials, or a function that allows every origin. That lets any website make authenticated requests on your users’ behalf.
  • CORS is not access control. It only restrains browsers. curl, scripts and servers ignore it completely — your API must still authenticate and authorise every request.

Rate limiting

Without limits, one client can hammer your login endpoint with millions of password guesses, scrape your whole catalogue, or simply overload your server.

Terminal
npm install express-rate-limit
JavaScript
import { rateLimit } from 'express-rate-limit';

// A general limit for the whole API
app.use(rateLimit({
  windowMs: 15 * 60 * 1000,   // 15 minutes
  limit: 300,                 // requests per IP per window
  standardHeaders: 'draft-8', // send RateLimit headers
  legacyHeaders: false,
}));

// Much stricter for sensitive endpoints
const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 10 });
app.use('/auth/login', authLimiter);
app.use('/auth/forgot-password', authLimiter);

Clients that exceed the limit receive 429 Too Many Requests. Two production details:

  • With several app instances, use a shared store (such as Redis, via rate-limit-redis) so the limit applies across all of them.
  • Behind a load balancer, set app.set('trust proxy', 1) so limits use the real client IP, not the proxy’s.

Limit sizes and time

  • Body size: express.json({ limit: '100kb' }) (the default) — raise it only on routes that need it.
  • Uploads: set file size and count limits (see File uploads).
  • Pagination: cap limit on every list endpoint.
  • Timeouts: Node’s HTTP server has requestTimeout and headersTimeout; set database statement timeouts and fetch timeouts too, so slow requests can’t pile up.

Don’t leak information

  • Generic 500 messages to clients; full details only in logs (see Error handling in Express).
  • Same error for “unknown email” and “wrong password”.
  • Return 404, not 403, for records a user isn’t allowed to know exist.
  • Never send password hashes, tokens or internal IDs you don’t need to. Shape responses explicitly instead of returning whole database rows.

The OWASP API Security Top 10

The Open Worldwide Application Security Project maintains a list of the most common API vulnerabilities. The top few cause most real breaches:

Risk What goes wrong Defence
Broken object-level authorisation /orders/1234 returns someone else’s order scope every query to the current user
Broken authentication weak tokens, no rate limit on login, long-lived tokens the previous three topics
Broken property-level authorisation a user sets role: admin via the request body, or sees fields they shouldn’t validation that strips unknown fields; explicit response shapes
Unrestricted resource consumption huge pages, uploads or request floods limits and rate limiting
Broken function-level authorisation normal users can call admin endpoints role checks on every admin route
Server-side request forgery (SSRF) your server fetches a URL the attacker chose, reaching internal services allow-list destinations; never fetch arbitrary user URLs

Secrets and dependencies

  • Secrets in environment variables or a secrets manager — never in code or Git.
  • Use a least-privilege database user: the app doesn’t need permission to drop tables.
  • Keep Node and dependencies updated; run npm audit in CI and act on runtime vulnerabilities.
  • Run the app as a non-root user (you’ll do this in the Docker topic).

Injection beyond SQL

Any time user input becomes part of a command or query, injection is possible:

  • Shell commands — use execFile with an argument array, never exec with a string built from input (see Child processes).
  • File paths — resolve and check them against an allowed folder (see Paths and URLs).
  • HTML — if you render HTML, escape user content; template engines do this by default.
  • NoSQL queries — validation stops objects like { "$gt": "" } sneaking into MongoDB filters.

A secure baseline

JavaScript
const app = express();
app.disable('x-powered-by');
app.set('trust proxy', 1);

app.use(helmet());
app.use(cors({ origin: config.corsOrigins, credentials: true }));
app.use(rateLimit({ windowMs: 15 * 60_000, limit: 300, standardHeaders: 'draft-8', legacyHeaders: false }));
app.use(express.json({ limit: '100kb' }));
app.use(cookieParser());

app.use('/auth', authLimiter, authRouter);
app.use('/api/v1', requireAuth, apiRouter);  // every API route authenticated by default

app.use(notFound);
app.use(errorHandler);

Making authentication the default — and explicitly marking the few public routes — is much safer than remembering to add it to each private route.

Security is a habit, not a feature. Review new endpoints with one question: what happens if someone sends something I didn’t expect, for a record that isn’t theirs, a thousand times a second?

Exercise

Harden an app

Add these to an Express app in the right order: helmet(), CORS allowing only origins listed in CORS_ORIGINS (comma-separated) with credentials, a JSON body limit of 50 kb, a general rate limit of 100 requests per 15 minutes, and a stricter limit of 5 per 15 minutes on POST /auth/login. Disable the X-Powered-By header and trust one proxy.

JavaScript
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import { rateLimit } from 'express-rate-limit';

const app = express();

Summary

  • Security is layers: HTTPS, rate limits, headers, CORS, authentication, authorisation, validation and safe queries.
  • helmet() sets protective headers; CORS should list exact allowed origins.
  • Rate-limit everything, and especially login, sign-up and password reset.
  • Limit body sizes, set timeouts, and never leak stack traces or internal errors.
  • Most API breaches come from broken authorisation — check ownership on every object you return or change.