Node.js REST API Interview Questions
Answers written to be said out loud in an interview — each with a common follow-up question and a link to the tutorial that explains it in depth.
- Beginner
- 6
- Intermediate
- 12
- Experienced
- 7
01What is a REST API?Beginner
An API that exposes resources at URLs and uses HTTP methods (GET, POST, PUT, PATCH, DELETE) and status codes to operate on them, with stateless requests usually exchanging JSON.
02PUT vs PATCH?Beginner
PUT replaces the entire resource with the request body and is idempotent. PATCH applies a partial update to some fields.
03How do you design REST URLs?Beginner
Use nouns for resources and HTTP methods for actions: GET /api/products, POST /api/products, GET /api/products/42, PATCH /api/products/42, DELETE /api/products/42. Nest only for true ownership (/api/orders/7/items) and use plural, lowercase names.
04How do you set up an Express API project?Beginner
npm init, install express, add "type": "module", create app.js that builds and exports the app (with express.json(), routes and an error handler) and server.js that calls listen. Keeping them separate makes the app testable.
05Which HTTP methods are safe and which are idempotent?Beginner
Safe methods (GET, HEAD, OPTIONS) do not change data. Idempotent methods give the same result when repeated: GET, PUT, DELETE and the safe ones. POST is neither; PATCH is not guaranteed to be.
06What is a controller in an Express API?Beginner
A module of request handlers for one resource. It reads input from req, calls a service, and turns the result into a status code and JSON. Business rules and SQL live in services and repositories, not in controllers.
07How do you validate request bodies in Express?Intermediate
Define a schema with a library such as zod or Joi, parse req.body in a middleware or handler, and return 400 with field-level errors on failure. Never trust client input.
08How do you implement pagination?Intermediate
Accept page/size (offset pagination) or a cursor, clamp the size to a maximum, return the data plus metadata (total, page, next cursor). Cursor pagination is more stable and efficient for large, changing datasets.
09How do you prevent SQL injection with MySQL in Node?Intermediate
Use parameterised queries with placeholders (pool.execute("… WHERE id = ?", [id])) so values are never concatenated into SQL. Validate identifiers like sort columns against an allow-list.
10How does CORS work in an Express API?Intermediate
The browser sends an Origin header (and a preflight OPTIONS request for non-simple requests). The server must respond with Access-Control-Allow-Origin for allowed origins. Use the cors middleware with an explicit origin list, and credentials: true for cookies.
11How do async errors reach the error handler in Express 5?Intermediate
Express 5 forwards rejected promises from async handlers to the error-handling middleware automatically. In Express 4 you had to call next(err) or use a wrapper such as express-async-errors.
12How should an API return errors?Intermediate
Use the right status code and a consistent JSON body, such as { error: { code, message, details } } or RFC 9457 problem+json. Return field-level details for 400s, never stack traces or SQL errors, and log the full error server-side with a request id.
13How do you implement a CRUD API with MySQL?Intermediate
A router maps the five endpoints to a controller; the service validates and applies rules; the repository runs parameterised queries through a pool. Return 201 with Location on create, 204 on delete, and 404 when affectedRows is 0.
14Offset vs cursor pagination?Intermediate
Offset (LIMIT 20 OFFSET 40) is simple and allows jumping to page N but slows down on deep pages and can skip or repeat rows as data changes. Cursor (WHERE id > lastId LIMIT 20) is fast and stable but only moves forward.
15How do you implement safe search and sorting?Intermediate
Bind search terms as parameters (LIKE ? with %term%), whitelist sortable columns and directions in a map instead of interpolating them, cap page sizes and index the columns you filter on.
const sortable = { name: 'name', price: 'price', newest: 'created_at' };
const column = sortable[req.query.sort] ?? 'name';
const dir = req.query.dir === 'desc' ? 'DESC' : 'ASC';
const [rows] = await pool.query(
`SELECT id, name, price FROM products WHERE name LIKE ? ORDER BY ${column} ${dir} LIMIT ?`,
[`%${term}%`, 20],
);
16Session cookies vs JWTs for API authentication?Intermediate
Sessions keep state on the server and send an opaque id in a cookie — easy to revoke. JWTs are self-contained signed tokens — stateless and good across services, but hard to revoke before expiry, so keep them short-lived with refresh tokens.
17What makes a password policy secure?Intermediate
A minimum length (12+), checking against breached-password lists, no forced complex rules or periodic resets, bcrypt or argon2 hashing, rate limiting and lockout on login, and a reset flow with single-use, expiring tokens.
18How do you document a Node.js API?Intermediate
Write an OpenAPI document (by hand, with JSDoc comments via swagger-jsdoc, or generated from zod schemas) and serve Swagger UI or Scalar at /docs. Keep it in sync by generating it from the same schemas used for validation.
19How would you implement role-based authorization?Experienced
Authenticate first (JWT or session) and attach the user and roles to req. Then use middleware like requireRole("admin") on routes, returning 403 when the role is missing. Keep permission checks on the server for every request.
20Why and how do you rate-limit an API?Experienced
To protect against brute-force attacks, scraping and accidental overload. Use middleware such as express-rate-limit with a stricter limit on auth routes, and a shared store (Redis) when running multiple instances.
21How do you test API endpoints manually and automatically?Experienced
Manually with Postman, Insomnia, Bruno or VS Code .http files, saving collections in the repo. Automatically with supertest + Vitest against the app and a seeded test database, covering success, validation, auth and not-found cases.
22What are the OWASP API security risks you check first?Experienced
Broken object-level authorization (checking ownership on every id), broken authentication, excessive data exposure, missing rate limits, mass assignment, security misconfiguration and injection.
23How do you prepare a Node API for production?Experienced
Validated environment config, helmet, strict CORS, rate limiting, structured logs, a /health endpoint, graceful shutdown on SIGTERM, a process manager or container, HTTPS at the proxy and database migrations run in the deployment pipeline.
24How does a React app consume your Node API?Experienced
In development a Vite proxy forwards /api to the API so no CORS is needed. In production serve both from one origin or configure CORS with the exact origin and credentials, send cookies with credentials: "include" and centralise fetch calls in an API client.
25How do you log requests without leaking data?Experienced
Log method, path, status, duration and a request id; redact authorization headers, cookies, passwords and tokens; never log full bodies; ship JSON logs to a central store and alert on error rates.