tezvyn:

Custom API key auth middleware

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

writing middleware with the req, res, next contract.

OUTLINE

read the header from req, on missing or invalid send res.status(401) and return, on valid call next, mount before protected routes.

WHAT THIS TESTS This checks your command of the middleware signature and the discipline of either ending the response or calling next, but never both, which is the leading cause of headers-already-sent errors.

A GOOD ANSWER COVERS A middleware is a function with the signature (req, res, next). To guard on an API key you read the header, noting that Express lowercases header names, so req.headers['x-api-key'] or req.get('X-API-Key'). If the header is absent or does not equal the expected key, you respond with res.status(401).json or .send and then return to halt execution, ensuring the request never reaches downstream handlers. If the key is valid, you call next() with no arguments to pass control to the next middleware or route handler. You mount this middleware before the routes you want to protect, either globally with app.use or on a specific router. The critical rule is exactly one outcome per request: either you terminate the response or you call next, never both.

COMMON WRONG ANSWERS Calling next after sending the 401, causing a headers-already-sent crash. Forgetting to return after res.status(401), so code continues. Reading the header with the wrong casing and always failing. Comparing the key insecurely, though for the exercise a simple equality is acceptable.

LIKELY FOLLOW-UPS Why is returning after the 401 important. How do you avoid timing attacks comparing secrets. How would you scope this to one router instead of globally.

ONE CONCRETE EXAMPLE function requireApiKey(req, res, next) { const key = req.get('X-API-Key'); if (!key || key !== process.env.API_KEY) { return res.status(401).json({ error: 'Unauthorized' }); } next(); }. Mounted with app.use(requireApiKey), a request lacking the header gets a 401 and stops, while a valid key flows through to the handlers.

Read the original → expressjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.