Express
85 bites tagged Express — interview questions with model answers, and 60-second explainers.
Modularize routes with express.Router
Create a Router per resource in its own file, define routes on it, export it, and mount with app.use('/products', router). structuring a growing app.
Status codes for successful POST and GET
201 Created for a successful POST (ideally with a Location header), 200 OK for a successful GET returning data. correct 2xx semantics. returning 200 for every success or 204 when a body is sent.
req.params vs req.query vs req.body in Express
Req.params holds named route segments, req.query holds the URL query string, req.body holds the parsed payload. where request data lives. confusing query with params, or expecting req.body without a body parser.
Design an Express route to create a user
POST to a collection URL like /users, read the payload from req.body via express.json(), return 201 with the created resource. REST conventions for creation. using GET to create or putting data in the URL.
Conditionally apply middleware by request property
Use express.text({ type: 'application/xml' }) or a guard wrapper that checks req.is() then calls the parser or next(). knowing helpers and the type option exist.
Write a JWT authentication middleware
Read the header, strip Bearer, jwt.verify with the secret, set req.user and next(), else send 401. extracting a Bearer token, verifying it, and gating access. calling next() after sending 401, or trusting an unverified token.
Middleware execution order and sharing data via req
Middleware runs top-down in registration order; each calls next(); attach data like req.user that later handlers read. the sequential pipeline and shared req object. assuming parallel execution or using globals to pass state.
Express error-handling middleware signature
(err, req, res, next) with err first, identified by arity, placed last after all routes. recognizing the four-argument signature. omitting the err parameter or registering it before the routes it should catch.
Application-level vs router-level middleware
App.use() binds to the app and runs everywhere; router.use() binds to a Router and runs only for that router's routes. scoping of middleware. claiming they are interchangeable or that scope does not matter.
Write a request-logging middleware in Express
Read req.method, log with a timestamp, then call next() to continue. the (req, res, next) signature and calling next(). forgetting next() so the request hangs, or ending the response prematurely.
Parse JSON and URL-encoded bodies in Express
Express.json() for JSON, express.urlencoded() for form data, both registered via app.use(). knowledge of built-in body parsers. reaching for the deprecated body-parser package or forgetting extended option.
What is Express middleware
Middleware are functions in a chain with req, res, next, they inspect or modify request and response, then call next to continue or send a response to end. the core Express request pipeline.
Centralized error-handling middleware
Error middleware takes four args err, req, res, next, is defined last, and runs when next(err) is called or sync errors throw. Express error flow. omitting the err parameter so Express treats it as normal middleware.
Custom API key auth middleware
Read the header from req, on missing or invalid send res.status(401) and return, on valid call next, mount before protected routes. writing middleware with the req, res, next contract.
Modularizing routes with express.Router
Create a Router instance in users.js, attach routes to it, export it, then mount it under a base path with app.use in the main file. structuring a growing app. duplicating the base path on every route instead of mounting.
Express route order and matching
Express checks routes in definition order, /items/new matches the literal route first, if /:id came first new would be captured as an id. top-down route matching. thinking Express picks the most specific route automatically.
res.send vs res.json vs res.end
Send is flexible and sets content type by type, json serializes and sets JSON content type, end is the raw http terminator with no body helpers. how Express sends responses. using res.end to return an object or claiming they.
Parsing JSON bodies with express.json
Register express.json via app.use so it reads the request stream and populates req.body before handlers run, place it before routes. why req.body needs a body parser. expecting req.body to work without any parser.
Query params vs route params in Express
Query string values via req.query.q, named path segments via req.params.id, query is optional, route params are part of the matched pattern. distinguishing two ways to pass data in a URL. mixing up req.query and req.params.
Serving static files in Express
App.use with express.static pointing at the public directory, files served relative to that root, often combined with an absolute path. knowing the built-in static middleware.
Minimal Express Hello World server
Import express, create an app, define app.get on the root sending a response, call app.listen on a port. basic Express setup fluency. forgetting app.listen or confusing the require with the app instance.
Handling async errors in Express middleware
Await inside try/catch and call next(err) on failure, or wrap the handler in an async error adapter; never let a rejected Promise go uncaught. routing async errors into Express.
Layered structure for a scalable Express API
Routes map URLs, controllers handle HTTP, services hold business logic, data layer talks to the DB; keep each layer ignorant of HTTP except controllers. separation of concerns and testability.
express-validator: Validate at the Edge
express-validator stops garbage before it hits your logic. Use it on any route that accepts user input like form data, query strings, or JSON payloads. The biggest mistake is validating but forgetting to check validationResult, so invalid requests pass.
Get Express bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.