Top 30 Middleware Interview Questions and Answers
30 multiple-choice questions on Middleware, drawn from 30 bites out of the 49 tagged Middleware on Tezvyn. Answer them here or read straight down. Every question carries the correct option, why it is correct, and a link to the bite it came from.
30 questions. Pick an answer, or open “Show the answer” to read it.
Answers are graded in your browser. Nothing is saved, and no XP or streak is earned here. The app keeps score.
Question 1 of 30
In classic Express 4, how should an error from an awaited database call inside async middleware reach the error handler?
Show the answer
Answer: c · Catch it and pass it to next(err) so the error-handling middleware runs
Express 4 does not auto-catch async throws, so you must catch and forward with next(err) to trigger the four-argument error handler. Throwing alone leaves the request hanging.
Read the full bite: Handling async errors in Express middleware
Question 2 of 30
Which task is the most appropriate use case for a SvelteKit server hook?
Show the answer
Answer: b · Initializing a database connection pool that is shared across all server-side requests.
The card explicitly states that "startup behavior (code at the top level of a hooks file) is ideal for initializing singletons like a database connection pool." This makes initializing a shared resource like a DB pool a primary use case for server hooks. While hooks can handle custom routing (like option A), defining standard API endpoints is typically done using dedicated +server.js files, whereas hooks are more for intercepting and modifying requests or handling non-standard routing.
Read the full bite: SvelteKit Hooks: Intercepting Requests and Events
Question 3 of 30
Why is express.static(path.join(__dirname, 'public')) preferred over express.static('public')?
Show the answer
Answer: c · A bare relative path resolves against the variable working directory and can break
A relative path is resolved against the current working directory, which varies by launch context, so the absolute __dirname-based path is reliable. Both forms set caching headers and serve at the same speed.
Question 4 of 30
Where must app.use(express.json()) be registered for req.body to be available in a POST handler?
Show the answer
Answer: a · Before the route handlers, so the body is parsed when they run
Middleware runs in registration order, so the parser must be mounted before the routes to populate req.body in time. Express does not reorder middleware, and registering it after the routes leaves req.body undefined.
Question 5 of 30
Why must auth middleware return after sending res.status(401) when the key is invalid?
Show the answer
Answer: b · To stop execution so it does not also call next and trigger a double response
Without returning, the function would continue and could call next, sending a second response and causing a headers-already-sent error. The return simply halts the handler; it does not free memory or reset status.
Question 6 of 30
What distinguishes an Express error-handling middleware from a regular one?
Show the answer
Answer: a · It has four parameters (err, req, res, next), and Express detects this signature
Express identifies error handlers by their four-argument arity and routes errors to them. The name is irrelevant, there is no app.error method, and it is still registered with app.use.
Question 7 of 30
In an Express middleware, what is the consequence of neither sending a response nor calling next?
Show the answer
Answer: a · The request hangs indefinitely because nothing advances or ends it
A middleware must either end the response or call next; doing neither leaves the request stalled forever. Express does not auto-advance, run the next handler, or throw on its own.
Question 8 of 30
Why must asynchronous API calls live in middleware rather than directly inside a Redux reducer?
Show the answer
Answer: d · Reducers must remain pure and synchronous, returning new state without side effects
Reducers must be pure and synchronous so state transitions stay predictable and replayable; side effects belong in middleware. Middleware does not run on a separate thread, making that distractor wrong.
Question 9 of 30
A teammate posts JSON to your endpoint but req.body is undefined. The route is defined and the client sets Content-Type correctly. What is the most likely cause?
Show the answer
Answer: a · express.json() was registered after the route definition
Middleware runs in registration order, so a parser added after the route never touches that request. body-parser is not required since express.json() is built in.
Read the full bite: Parse JSON and URL-encoded bodies in Express
Question 10 of 30
Your logging middleware prints correctly but every request to the server eventually times out with no response. What did the middleware most likely fail to do?
Show the answer
Answer: a · Call next() to pass control to the next handler
A middleware must either send a response or call next(); omitting next() leaves the request hanging. console is global and needs no import, and middleware need not return Promises.
Read the full bite: Write a request-logging middleware in Express
Question 11 of 30
You want authentication to apply only to routes under /admin without touching public routes. Which approach scopes it correctly?
Show the answer
Answer: d · router.use(requireAuth) on the admin Router, mounted at /admin
Router-level middleware on a Router mounted at /admin runs only for that group. A global app.use would protect every route, and res has no use() method.
Read the full bite: Application-level vs router-level middleware
Question 12 of 30
You wrote an error handler as (req, res, next) and errors passed via next(err) never reach it. What is the fix?
Show the answer
Answer: b · Declare four parameters: (err, req, res, next)
Express identifies error handlers by their four-argument arity; three params make it a regular middleware that skips error propagation. Position alone does not fix the signature.
Read the full bite: Express error-handling middleware signature
Question 13 of 30
Auth middleware sets the current user so the route handler can use it. What is the correct, concurrency-safe place to store that user?
Show the answer
Answer: a · On the req object, e.g. req.user
req is unique per request and flows through the chain, so req.user is safe under concurrency. A shared module-level variable would leak one user's data into another simultaneous request.
Read the full bite: Middleware execution order and sharing data via req
Question 14 of 30
You want an XML parser to run only for application/xml requests, with the condition kept out of the parser's own code. Which is the cleanest approach?
Show the answer
Answer: d · Use express.text({ type: 'application/xml' }) or a wrapper that checks req.is() then delegates
The type option and a req.is() wrapper keep the matching logic declarative and outside the parser, exactly what the question asks; embedding the check inside the parser is the disallowed approach.
Read the full bite: Conditionally apply middleware by request property
Question 15 of 30
What is the consequence if an Express middleware function neither calls next() nor sends a response?
Show the answer
Answer: a · The client's request will hang indefinitely, awaiting a response.
The card states, "If a middleware does neither, the request hangs." This means the client will wait indefinitely for a response. Calling next() is explicitly required for the request to proceed to the next function in the chain, making option C incorrect.
Read the full bite: Express Middleware: The Chain of Command for Requests
Question 16 of 30
In which situation is it generally more appropriate to handle an error directly within an Express route handler rather than relying on global error middleware?
Show the answer
Answer: c · A request for a specific resource (e.g., a user by ID) finds no matching entry.
The card specifies that global error handlers are for unexpected or system-level errors. Expected, non-exceptional business logic failures, such as a 'user not found' scenario, are cleaner to handle directly within the route handler with a specific status code.
Read the full bite: Express Error Middleware: Your App's Safety Net
Question 17 of 30
A pre('save') hook hashes the password every time without checking isModified('password'). What goes wrong when a user later updates only their email?
Show the answer
Answer: b · The already-hashed password is hashed again, so login stops working
Without an isModified guard, any save re-hashes the stored hash, so the password no longer matches on login. Guarding with this.isModified('password') runs hashing only when the password actually changed.
Read the full bite: Mongoose pre('save') hooks for password hashing
Question 18 of 30
What is the primary outcome if an Express middleware function completes its execution without calling next() or sending a response?
Show the answer
Answer: a · The client's request will remain open, eventually timing out without a response.
The card states that if next() is not called and no response is sent, 'the request will hang and eventually time out,' meaning the client waits indefinitely. The server does not automatically terminate or redirect the request; it simply waits for the middleware to complete its cycle.
Read the full bite: Express Middleware: Intercepting Requests Before Your Route Handler
Question 19 of 30
What is the consequence if a Redux middleware fails to call next(action)?
Show the answer
Answer: d · The action is silently prevented from reaching any further middleware or the reducers.
The card explicitly states that forgetting to call next(action) is a "footgun" that "silently blocks the action." This means the action will not proceed through the middleware chain or reach the reducers, and no error will be thrown.
Read the full bite: Redux Middleware: Intercepting Actions Before Reducers
Question 20 of 30
When a browser-based frontend on "app.com" fetches data from an Express API on "api.com", what is the `cors` middleware's primary function?
Show the answer
Answer: b · To add a specific header to the API's response, signaling to the browser that "app.com" can access the data.
The `cors` middleware's primary role is to add the `Access-Control-Allow-Origin` header to the API response, which acts as a permission slip for the browser to allow the frontend script to access the data. It does not block requests; the browser's Same-Origin Policy is what prevents access if the header is missing.
Read the full bite: CORS Middleware: Unlocking Cross-Origin Requests in Express
Question 21 of 30
Which logging task is NOT a primary use case for Morgan in an Express application?
Show the answer
Answer: c · Tracking internal application events like database connection failures.
Morgan is purpose-built for logging HTTP requests and responses, providing visibility into traffic patterns. It is explicitly stated that Morgan is not a general-purpose application logger and should not be used for internal application events like database errors, which require dedicated logging libraries.
Read the full bite: Morgan: One-Line Request Logging for Express
Question 22 of 30
In a Passport local strategy verify callback, what is the correct way to signal a successful authentication?
Show the answer
Answer: d · return done(null, user)
done(null, user) means no error and supplies the authenticated user, which Passport attaches to req.user. done(null, true) passes a boolean instead of the user object, so the session would lack a usable identity.
Read the full bite: Securing Express with Passport local strategy
Question 23 of 30
Where should the role used by an RBAC middleware come from to remain secure?
Show the answer
Answer: c · The verified token payload or database lookup, set by auth middleware
The role must derive from a trusted source the client cannot forge, namely the verified token or a server-side lookup populated during authentication. Client-controlled headers, body, or query params can be spoofed to escalate privileges.
Read the full bite: Role-based access control middleware in Express
Question 24 of 30
When cookie-parser with a secret detects a tampered signed cookie, what happens?
Show the answer
Answer: d · The cookie's value is set to false within the req.signedCookies object.
The card explicitly states that a cookie failing signature validation will have its value set to false in req.signedCookies. This allows the application to detect tampering and decide how to proceed, rather than cookie-parser automatically rejecting the request or throwing an error.
Read the full bite: cookie-parser: From Header String to Usable Object
Question 25 of 30
What is the main advantage of a validate(schema) factory middleware over validating inside each controller?
Show the answer
Answer: a · It centralizes and reuses validation, keeping controllers free of input checks
A schema-driven middleware factory lets you declare rules once and reuse them across routes, so controllers receive already-validated data. It does not change parsing speed, eliminate 400s, or encrypt anything.
Read the full bite: Reusable schema validation middleware with Zod or Joi
Question 26 of 30
Where should you place a start-time variable in FastAPI middleware to measure total request latency?
Show the answer
Answer: c · Before await next(request), then compute elapsed after the call returns
You must record the start time before await next(request) and calculate latency afterward, because the endpoint executes during that call. Option B would yield near-zero milliseconds since the timer starts after processing completes, and Option D incorrectly assumes both middleware blocks run before the path operation.
Read the full bite: Purpose of await next(request) in FastAPI middleware and timing effects
Question 27 of 30
Which sequence correctly adds an X-Process-Time header in FastAPI HTTP middleware while preserving route-level headers?
Show the answer
Answer: a · Record start time, await call_next(request) to get the response, assign the elapsed time to response.headers, and return the same response object.
The correct pattern awaits call_next(request) to obtain the response produced by downstream handlers, then mutates that response's headers directly so existing cookies and status codes remain intact. Instantiating a new Response object drops all route-level headers and cookies set by the path operation, which is why option C is wrong.
Read the full bite: Write a FastAPI middleware that adds X-Process-Time header
Question 28 of 30
What is a primary challenge when configuring API rate limiting for public services?
Show the answer
Answer: c · Accurately identifying individual users when multiple users share an IP address.
The card states that a 'main footgun' is misconfiguration that blocks legitimate users, 'especially those behind a shared network... that makes many users appear to come from a single IP address.' This directly describes the challenge of identifying individual users behind shared IPs. While storing counts across instances (A) is a consideration for scaling, the card notes it's solvable with external stores, and it's not highlighted as the 'main footgun' for blocking legitimate users.
Read the full bite: API Rate Limiting: Protecting Your Express Endpoints
Question 29 of 30
A React app sends a PUT request with an Authorization header to a FastAPI backend. The origin is allowed, but the browser blocks it. What else must be configured?
Show the answer
Answer: c · allow_methods must include PUT and allow_headers must include Authorization
Browsers require explicit permission for non-simple methods and custom headers during the preflight handshake, so allow_methods must include PUT and allow_headers must include Authorization. Option A is wrong because FastAPI's CORSMiddleware automatically handles OPTIONS responses, and option B confuses expose_headers—which governs readable response headers—with the allow_headers required for preflight approval.
Question 30 of 30
Why is a contextvars.ContextVar preferred over a module-level global for storing a per-request correlation ID in async FastAPI?
Show the answer
Answer: a · ContextVars are isolated per asyncio task, so concurrent requests do not overwrite each other's value as a shared global would
ContextVars give each asyncio task its own copy, preventing concurrent requests from clobbering one another. A shared global is visible to every in-flight request and would mix correlation IDs under load.
Read the full bite: Propagating a correlation ID without parameter passing
Could you explain these out loud?
That is what an interview actually tests. Tezvyn gives you questions like these with what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.