Node.js REST API Best Practices: Structure, Validation, Security & Errors
An API that works in a demo is easy. One that stays reliable under real traffic and real mistakes needs consistent structure, validation and error handling. These are the practices I apply to every Node.js and Express backend.
1. Separate routes, controllers and services
Routes map URLs to controllers. Controllers handle HTTP details. Services hold business logic and talk to the database. This keeps code testable and stops route files turning into thousand-line monoliths.
2. Validate every input
Never trust request bodies, params or query strings. Validate with a schema library such as Zod or Joi and reject bad input with a 400 and a clear message before it reaches your logic.
3. Use consistent error handling
Create one error-handling middleware that turns thrown errors into a predictable JSON shape with a status code, a machine-readable code and a human message. Never leak stack traces to clients.
4. Use proper HTTP semantics
- GET reads, POST creates, PUT or PATCH updates, DELETE removes.
- Return 201 for created, 204 for no content, 401 for unauthenticated and 403 for forbidden.
- Use plural nouns for resources, such as /users/42/orders.
5. Secure the basics
- Hash passwords with bcrypt or argon2.
- Use short-lived access tokens and refresh tokens, stored safely.
- Add helmet, CORS rules and rate limiting.
- Keep secrets in environment variables, never in the repository.
6. Paginate and filter
Never return unbounded lists. Support limit and cursor or page parameters and index the fields you filter by so response time stays flat as data grows.
7. Log and monitor
Use structured logs with a request ID, add a health-check endpoint and track error rates. You cannot fix what you cannot see.