6 د قراءة
تصميم وأمان واجهات Node.js
Node.js وExpress: تسمية الموارد والتحقق والمصادقة ومحددات المعدل والأخطاء.
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
Pagination: cursor example
Offset pagination (?page=47) is fine for admin tables with modest data. For mobile feeds and audit logs that grow daily, cursor pagination avoids skipped/duplicate rows when data changes under the user.
Response shape I reuse:json { "data": [ /* items */ ], "page": { "nextCursor": "eyJpZCI6IjAxSFpY…", "hasMore": true } } Encoding is usually an opaque base64 of (sortKey, id) — not raw SQL offsets exposed to clients.```ts
import { z } from “zod”;
const ListQuery = z.object({ limit: z.coerce.number().int().min(1).max(50).default(20), cursor: z.string().optional(), });
app.get(“/appointments”, async (req, res) => {
const { limit, cursor } = ListQuery.parse(req.query);
const page = await listAppointmentsForTenant({
businessId: req.user.businessId,
limit,
cursor,
});
return res.json(page);
});
```Pitfall: sorting only by createdAt when values collide — always tie-break with a stable id.
Idempotency keys for writes
Mobile clients retry POSTs. Without idempotency, you double-charge or double-book. For payment-like routes, require Idempotency-Key (client-generated UUID) and store the first successful response.```ts
import type { Request, Response, NextFunction } from “express”;
const seen = new Map<string, { status: number; body: unknown }>(); // use Redis in production
export function idempotencyMiddleware(req: Request, res: Response, next: NextFunction) {
const key = req.header(“Idempotency-Key”);
if (!key) {
return res.status(400).json({ code: “idempotency_key_required” });
}
const cacheKey = ${req.user?.id ?? "anon"}:${req.path}:${key};
const cached = seen.get(cacheKey);
if (cached) {
return res.status(cached.status).json(cached.body);
}
const originalJson = res.json.bind(res);
res.json = (body: unknown) => {
if (res.statusCode >= 200 && res.statusCode < 300) {
seen.set(cacheKey, { status: res.statusCode, body });
}
return originalJson(body);
};
next();
}
## CORS in production (not `*`)
CORS is a browser contract. Server-to-server calls ignore it, but your Next.js admin and Expo web builds do not.```ts
import cors from "cors";
const allowlist = [
"https://app.example.com",
"https://admin.example.com",
];
if (process.env.NODE_ENV !== "production") {
allowlist.push("http://localhost:5173", "http://localhost:8081");
}
app.use(
cors({
origin(origin, callback) {
if (!origin || allowlist.includes(origin)) {
return callback(null, true);
}
return callback(new Error("cors_not_allowed"));
},
credentials: true,
methods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "Idempotency-Key"],
maxAge: 600,
}),
);
```**When not to lean on CORS alone:** never treat `Origin` as authentication. Always validate the token or session.
## Logging redaction
Structured logs help; leaking tokens does not. Before logging request metadata:
- Strip `Authorization`, cookies, OTP bodies and password fields
- Log `userId` / `businessId` hashes or opaque IDs, not national IDs or full card numbers
- Cap body size in debug logs (truncate JSON above a few KB)
- Never log raw SQL with interpolated user input```ts
function redactHeaders(headers: Record<string, unknown>) {
const copy = { ...headers };
delete copy.authorization;
delete copy.cookie;
return copy;
}
```Pair `requestId` across API, worker and outbound provider logs so support can trace one failure without replaying secrets in Slack.
## 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 `fetch` calls 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 (unknown fields rejected where needed)
- [ ] Authn + per-resource authz with cross-tenant tests
- [ ] Cursor or keyset pagination on high-volume list routes
- [ ] Idempotency keys on financial / booking writes
- [ ] Rate limits on auth, OTP and write routes
- [ ] CORS allowlist matches real admin and web origins
- [ ] Secure cookies / token storage choices documented
- [ ] Logs redacted; no secrets or full PII in log streams
- [ ] Request IDs end to end (API → worker → provider webhook)
- [ ] Timeouts and bounded retries on outbound calls
- [ ] Health and readiness routes for deploy pipelines (see [CI/CD with GitHub Actions](/ar/blog/posts/github-actions-ci-cd-pipeline/))
## When not to build a bespoke REST layer yet
- You are still renaming core entities weekly — stabilise the domain model first
- The only client is your own Next.js app on the same codebase — a modular monolith or server actions *might* suffice until mobile arrives
- You need heavy reporting across tenants before you have indexed list endpoints — fix reads before adding GraphQL complexity
## Related reading
- [Modern web application architecture](/ar/blog/posts/modern-web-app-architecture/) — where APIs sit in the stack
- [Lessons from building SaaS platforms](/ar/blog/posts/building-saas-lessons/) — tenancy and multi-role APIs
- [Pin GitHub Actions to a commit SHA](/ar/blog/posts/pin-github-actions-commit-sha/) — supply-chain hygiene for API repos
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.