3 min de lecture
Conception et sécurité des API Node.js
Node.js et Express : ressources, validation, auth, rate limits et erreurs en production.
A Node.js API is often the contract between web apps, mobile apps and everything else. When that contract is vague or insecure, every client inherits the mess. This is the checklist I use when I design or review Express (and similar) services for SaaS products.
Design the resources, not the screens
Name endpoints after domain nouns, not after current UI buttons.text Good: POST /appointments Bad: POST /createAppointmentFromMobileWizardStep3 Screens change. Resources endure. Version only when you break a contract (/v1/... or explicit deprecation headers) — not for every cosmetic tweak.
Validate at the boundary
Never trust body, query or headers. I validate with a schema library (Zod is my default in TypeScript) before business logic runs.```ts import { z } from “zod”;
const CreateAppointment = z.object({ serviceId: z.string().min(1), startsAt: z.string().datetime(), notes: z.string().max(500).optional(), });
app.post(“/appointments”, async (req, res) => {
const parsed = CreateAppointment.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ code: “validation_error”, details: parsed.error.flatten() });
}
// …create with parsed.data only
});
```Reject unknown fields in strict mode when clients should not smuggle privileges (role: "admin").
Authentication vs authorisation
Authentication answers who is calling. Authorisation answers whether they may perform this action on this resource.
Patterns that hold up:
- Short-lived access tokens + refresh rotation for mobile
- HttpOnly secure cookies for first-party web when it fits the threat model
- Server-side session store (Redis) when you need instant revocation
Always re-check resource ownership:ts const appointment = await db.appointments.findById(id); if (!appointment || appointment.businessId !== req.user.businessId) { return res.status(404).json({ code: "not_found" }); // avoid leaking existence } Returning 404 instead of 403 for cross-tenant probes reduces enumeration.
Security headers and transport
- TLS everywhere in production
helmet(or equivalent) for baseline headers- Strict CORS allowlists — not
*with credentials - Disable
x-powered-by
Rate limits and abuse
Public auth and OTP endpoints need tighter limits than authenticated reads. I place rate limits at the reverse proxy and in the app for sensitive routes. Log and monitor 429 spikes; they are product signals, not only attacks.
Secrets and configuration
- Secrets in environment or a secret manager — never in the repo
- Different credentials per environment
- Rotate when people leave the project
- Pin CI actions to commit SHAs (see my supply-chain article) so pipelines cannot silently change
Error responses that help without leaking```json
{
“code”: “inventory_unavailable”,
“message”: “This service slot is no longer available.”,
“requestId”: “req_01HZX…”
}
```Do not return stack traces, SQL fragments or file paths to clients. Keep those in structured logs keyed by requestId.
Dependency and runtime hygiene
- Run
npm audit/ Dependabot, but triage with context - Keep Node LTS updated
- Run the process as non-root in containers
- Set timeouts on outbound
fetchcalls to payment and SMS providers
Testing what matters
Unit-test validators and policy functions. Add a few integration tests that prove:
- unauthenticated requests fail
- user A cannot read user B’s resources
- invalid payloads never touch the database
Those three catch more production incidents than decorative coverage percentages.
Checklist before calling an API “done”
- Resource-oriented URLs and consistent status codes
- Schema validation on input
- Authn + per-resource authz
- Rate limits on auth and write routes
- Secure cookies / token storage choices documented
- No secrets in logs
- Request IDs end to end
- Timeouts on outbound calls
APIs are products. Treat them with the same care as the UI that depends on them — because every mobile crash screenshot eventually points back here.