Express routes and middleware
Express gives structure to routing, parsing and error handling.
What you will be able to do
- Use express.json() with a size limit before routes that read JSON.
- Keep route handlers small; move business logic into modules.
- Register an error handler with four arguments at the end.
In plain English
Middleware is a function that can inspect a request, end the response or call next. Put cross-cutting concerns such as authentication, logging and validation in middleware instead of repeating them in every route.
import express from 'express'
const app = express()
app.use(express.json({ limit: '16kb' }))
function requireKey(request, response, next) {
if (request.get('x-api-key') !== process.env.API_KEY) {
return response.status(401).json({ error: 'UNAUTHORIZED' })
}
next()
}
app.get('/health', (_request, response) => {
response.json({ ok: true })
})
app.post('/api/notes', requireKey, (request, response) => {
response.status(201).json({ id: crypto.randomUUID(), text: request.body.text })
})
app.use((error, _request, response, _next) => {
console.error(error)
response.status(500).json({ error: 'INTERNAL' })
})Your turn
MediumAdd an API key guard
Write middleware that returns 401 when x-api-key does not match process.env.API_KEY, otherwise calls next.
JS · starter
function requireKey(request, response, next) {
next()
}Check your understanding before moving on.
Knowledge checkQuestion 1
How does Express identify an error-handling middleware?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.