Most Node.js APIs get attacked the same way: someone probes an endpoint, finds a missing check, and walks away with data they should never see. To secure a Node.js API you run in production, you do not need exotic tooling. You need a short list of checks, applied to every route, and a habit of verifying them before each deploy. This checklist covers the twelve that matter most, in the order you should tackle them.
How to secure a Node.js API, step by step
Work through the list top to bottom. The first four stop the most common attacks. The rest close the gaps that show up once an API has real users and real data. If you are building a REST API with Node.js and Express, apply these checks as you add each route, not after the whole API is done. Retrofitting security onto finished routes takes longer and misses more.
1. Authentication comes first
Every route that touches user data needs to know who is calling. Use a proven method: JWT authentication with short-lived access tokens, or session cookies with the HttpOnly and Secure flags. Never roll your own token format. Never trust a user ID that arrives in a request body or a query string. Check the token on every protected route, in middleware, before any handler runs. Public routes should be the exception, and each one should be a deliberate choice, not a forgotten default.
2. Authorisation is a separate check
Authentication answers who the caller is. Authorisation answers what they may do. A logged-in user asking for another user’s order history must get a 403, not the data. Check ownership on every read, write, and delete, even when the frontend only shows the user their own records. Frontends hide buttons. Attackers call endpoints directly. Put the ownership check in the route handler or a service layer, and test it with a second account, not just the account that owns the record.
3. Validate every input
Validate every input that arrives from outside your code: body fields, query strings, route parameters, and headers you read. Reject what does not match the shape you expect, and reject it early, before it reaches the database or a file path. Use a schema validator such as Zod or Joi so the rules live in one place and get reused. Check types, lengths, and allowed values. A field that should be an integer must not accept a string, and a field that should be one of three values must not accept a fourth. Validation is also where you stop the classic injection attacks, because malformed input never gets a chance to run.
4. Rate limit your endpoints
Rate limit your endpoints so one client cannot flood your server or brute-force a login form. Login and password-reset routes get strict limits, a handful of attempts per minute. Public read routes get looser ones. Return a 429 status with a Retry-After header when the limit is hit, and log repeated hits so you can spot a brute-force attempt while it is happening. Rate limiting is cheap insurance against both abuse and accidents, like a client stuck in a retry loop.
5. Keep secrets out of code and logs
Database passwords, API keys, and signing secrets belong in environment variables or a secret manager, never in source code and never in a committed .env file. Rotate a secret the moment you suspect it leaked. Also keep secrets out of logs: an error log that prints a full request body will eventually print a token. When you need to store API keys and secrets safely, treat the storage rules as part of the checklist, not as a separate chore.
6. Security headers in place
Put security headers in place with a middleware such as Helmet. The useful ones for an API are Strict-Transport-Security, X-Content-Type-Options, and a tight Content-Security-Policy on any HTML you serve. Headers will not fix a broken auth check, but they remove whole classes of browser-based attacks for almost no effort. Check the headers your API actually sends with a curl request, because a middleware that is installed but misconfigured sends nothing.
7. Lock down CORS
Cross-Origin Resource Sharing decides which websites may call your API from a browser. Allow only the origins you control, and only the methods and headers those frontends need. Never use a wildcard origin together with credentials. A permissive CORS policy is an open door for any malicious site your users happen to visit, and it is one of the easiest settings to get wrong because a loose policy makes development feel smoother.
8. Return safe errors
Error responses must not reveal internals. A database error message that reaches the client can name tables, columns, and query structure. Return a generic message and a stable error code, and write the detail to your server logs where only your team sees it. Consistent error shapes also make life easier for the clients consuming your API, because they can handle a known format instead of guessing what went wrong.
9. Keep dependencies patched
Most Node.js APIs run hundreds of transitive dependencies, and a known vulnerability in any one of them is a known way in. Run an audit on a schedule, not only when something breaks. Pin versions in production, review major updates before applying them, and remove packages you no longer use. A dependency you deleted cannot be exploited. Set up automated alerts so a new vulnerability in a package you use reaches you the same week it is published.
10. HTTPS everywhere, no exceptions
Serve the API over HTTPS in every environment that real users touch, including staging. Redirect plain HTTP to HTTPS, and set the HSTS header so browsers remember to use the secure version. Tokens and cookies sent over plain HTTP can be read by anyone on the same network. If you deploy a Node.js app to a VPS, terminate TLS at your reverse proxy and make sure the proxy forwards the real client IP, so your rate limiter sees actual clients instead of one shared proxy address.
11. Set timeouts and size limits
A request that never ends ties up a worker. Set timeouts on incoming requests, on outgoing calls to other services, and on database queries. Cap request body size to what your endpoints actually need, a few hundred kilobytes for most JSON APIs. These limits stop slow-loris style attacks and accidental resource exhaustion from a client sending a 50 MB payload to an endpoint that expects a short form.
12. Log security events, and read the logs
Log failed logins, authorisation failures, rate-limit hits, and validation errors with enough context to investigate: time, IP, route, and user ID where known. Do not log passwords or tokens. Then actually look at the logs. A weekly five-minute review catches patterns, like one IP probing every endpoint, long before they become incidents. Logging without review is just disk usage.
Run the checklist before every deploy
Turn these twelve points into a short review step in your deploy process. One person reads the diff, another checks the list. New routes get auth, validation, and rate limits before they ship. Old routes get re-checked when they change. Security work feels slow until the week it saves you, and by then the checklist has already paid for itself many times over.