Custom API key auth middleware
writing middleware with the req, res, next contract.
read the header from req, on missing or invalid send res.status(401) and return, on valid call next, mount before protected routes.
What's really being asked
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.
The full answer
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.
The mistakes people make
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.
What usually comes next
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.
A 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.
Interview question
Why must auth middleware return after sending res.status(401) when the key is invalid?
- a.Because res.status throws unless followed by return
- b.To stop execution so it does not also call next and trigger a double responseCorrect
- c.To reset the response status back to 200
- d.To free the API key from memory immediately
Why? this is the answer
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.
Just read this? Test yourself on what you have been reading.
Read the original → expressjs.com
- #express
- #middleware
- #authentication
- #api-key
- #http-headers
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
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.
We are hiring for this. Open roles that interview on express — each one lists the topics its interview covers.
See open roles