feat(curriculum): add express middleware lessons (#67194)

Signed-off-by: Kolade Chris <65571316+Ksound22@users.noreply.github.com>
Co-authored-by: Naomi Carrigan <naomi@freecodecamp.org>
Co-authored-by: zaira <zairahira@gmail.com>
This commit is contained in:
Kolade Chris 2026-06-04 09:51:47 +01:00 committed by GitHub
parent c69fa6db9b
commit 696fab2044
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 846 additions and 0 deletions

View File

@ -7339,6 +7339,12 @@
"Test your knowledge of HTTP status codes, error handling, debugging, logging, health checks, and graceful shutdowns."
]
},
"lecture-express-middleware": {
"title": "Express Middleware",
"intro": [
"In these lessons, you will learn how middleware works in Express, including application-level, router-level, and error-handling middleware, as well as examples of built-in and third-party middleware."
]
},
"review-express-middleware": {
"title": "Express Middleware Review",
"intro": [

View File

@ -0,0 +1,163 @@
---
id: 69f42cd936da600a74a84926
title: What is Middleware and How Does it Work?
challengeType: 19
dashedName: what-is-middleware-and-how-does-it-work
---
# --description--
Middleware is an essential concept in Express, and it allows us to handle requests and responses between the client and server. Middleware functions have access to the request object, the response object, and the next function in the application's request-response cycle.
Let's break it down:
## What is Middleware?
Middleware is essentially a function that executes during the lifecycle of a request to the server. It performs various tasks such as logging requests, handling errors, parsing incoming requests, or serving static files.
Express provides a convenient way to define middleware that processes incoming requests before they reach route handlers.
How Middleware Works:
When a request is made to an Express application, middleware is executed in the order it is added. The flow looks like this:
* Request is sent to the server.
* Middleware functions process the request.
* If the middleware calls `next()`, it passes control to the next middleware or route handler.
* If the middleware doesn't call `next()`, the request-response cycle stops.
```js
const express = require('express')
const app = express()
// Simple middleware that logs request info
app.use((req, res, next) => {
console.log('Request URL:', req.url)
console.log('Request Method:', req.method)
next() // Passes control to the next middleware
})
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
```
`app.use()`: Adds middleware globally to your application.
In this example, the middleware logs request details and calls `next()` to proceed to the next middleware or route handler.
Middleware is a powerful feature in Express that allows you to intercept and modify requests at various points. You can use middleware to handle things like logging, authentication, or even modify request and response objects before they reach your route handlers.
# --questions--
## --text--
What does middleware in Express allow you to do?
## --answers--
Configure the server port number.
### --feedback--
Think about which functions execute during the lifecycle of a request to the server.
---
Modify the request and response objects.
---
Handle routes.
### --feedback--
Think about which functions execute during the lifecycle of a request to the server.
---
Start the server.
### --feedback--
Think about which functions execute during the lifecycle of a request to the server.
## --video-solution--
2
## --text--
What happens if middleware does not call `next()`?
## --answers--
The request will continue through to the next middleware.
### --feedback--
Think about the four steps involved in the lifecycle of a request.
---
The request-response cycle will stop.
---
An error will be thrown.
### --feedback--
Think about the four steps involved in the lifecycle of a request.
---
The request will be handled by the last route handler.
### --feedback--
Think about the four steps involved in the lifecycle of a request.
## --video-solution--
2
## --text--
Which of the following is true about middleware?
## --answers--
Middleware runs only after a route handler is executed.
### --feedback--
Think about how middleware can inspect, change, or pass along requests and responses.
---
Middleware can modify the request and response objects.
---
Middleware can only log requests.
### --feedback--
Think about how middleware can inspect, change, or pass along requests and responses.
---
Middleware only works with `POST` requests.
### --feedback--
Think about how middleware can inspect, change, or pass along requests and responses.
## --video-solution--
2

View File

@ -0,0 +1,146 @@
---
id: 69f42d414b7626e21a922792
title: What is Application-level Middleware?
challengeType: 19
dashedName: what-is-application-level-middleware
---
# --description--
Application-level middleware is middleware that is bound to an instance of an Express app. It is typically used to handle requests that require processing across multiple routes. It can be applied globally or to specific routes.
This middleware is registered using `app.use()` or specific route methods like `app.get()`, `app.post()`, etc. It executes for every incoming request unless it's restricted to specific routes.
```js
const express = require('express')
const app = express()
// Application-level middleware that logs all incoming requests
app.use((req, res, next) => {
console.log('Request received at:', new Date())
next(); // Passes control to the next middleware
})
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
```
* `app.use()`: This is application-level middleware. It logs every request made to the server, no matter the route.
* The middleware runs for every incoming request, providing the server with details like the current timestamp.
Application-level middleware is useful for tasks that need to be applied across many or all routes in the app. This could include logging, authentication, and error handling.
# --questions--
## --text--
How is application-level middleware applied?
## --answers--
It is applied to individual routes only.
### --feedback--
Focus on how application-level middleware affects the whole app request flow.
---
It is applied to the entire Express application.
---
It is only used for error handling.
### --feedback--
Focus on how application-level middleware affects the whole app request flow.
---
It only applies to `GET` requests.
### --feedback--
Focus on how application-level middleware affects the whole app request flow.
## --video-solution--
2
## --text--
Which method is used to add application-level middleware?
## --answers--
`app.route()`
### --feedback--
Focus on what allows you to register middleware for the whole app.
---
`app.use()`
---
`app.set()`
### --feedback--
Focus on what allows you to register middleware for the whole app.
---
`app.listen()`
### --feedback--
Focus on what allows you to register middleware for the whole app.
## --video-solution--
2
## --text--
What can application-level middleware be used for?
## --answers--
Handling requests for specific routes only.
### --feedback--
Think about how application level middleware can affect requests before they reach any route handler.
---
Modifying the request and response objects for all routes.
---
Only handling errors.
### --feedback--
THink about how application level middleware can affect requests before they reach any route handler.
---
Only serving static files.
### --feedback--
THink about how application level middleware can affect requests before they reach any route handler.
## --video-solution--
2

View File

@ -0,0 +1,150 @@
---
id: 69f42d414b7626e21a922793
title: What is Router-level Middleware?
challengeType: 19
dashedName: what-is-router-level-middleware
---
# --description--
Router-level middleware is similar to application-level middleware, but it is bound to an instance of `express.Router()` instead of the main app instance. It can be used to modularize your Express application by creating isolated route modules.
Router-level middleware works in the same way as application-level middleware but is applied to specific router instances. This makes it easier to apply middleware only to a set of routes rather than globally.
```js
const express = require('express')
const app = express()
const router = express.Router()
// Router-level middleware to log requests to '/menu' routes
router.use((req, res, next) => {
console.log('Request made to /menu route')
next() // Pass control to the next handler
})
// Define routes
router.get('/drinks', (req, res) => {
res.send('Welcome to the drinks menu!')
})
app.use('/menu', router) // Apply the router
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
```
* `router.use()`: This is router-level middleware, which is applied only to routes handled by router.
* `app.use('/menu', router)`: The middleware applies only to routes that start with `/menu` (e.g., `/menu/drinks`).
Router-level middleware allows you to break your app into modular components and apply middleware selectively to a group of routes. This helps with organization and code clarity.
# --questions--
## --text--
What is router-level middleware in Express?
## --answers--
Middleware applied globally across the entire app.
### --feedback--
Focus on where the middleware is attached, not what it does.
---
Middleware that is bound to a specific router instance.
---
Middleware that is used only for logging requests.
### --feedback--
Focus on where the middleware is attached, not what it does.
---
Middleware that is used for static files.
### --feedback--
Focus on where the middleware is attached, not what it does.
## --video-solution--
2
## --text--
How can router-level middleware be applied?
## --answers--
By using `app.use()`.
### --feedback--
Focus on the method used to attach middleware to a router.
---
By using `router.use()`.
---
By using `app.listen()`.
### --feedback--
Focus on the method used to attach middleware to a router.
---
By using `app.get()`.
### --feedback--
Focus on the method used to attach middleware to a router.
## --video-solution--
2
## --text--
Where do you apply router-level middleware?
## --answers--
To the app instance.
### --feedback--
Think about where the router middleware is attached.
---
To specific router instances.
---
To static files.
### --feedback--
Think about where the router middleware is attached.
---
To individual route handlers.
### --feedback--
Think about where the router middleware is attached.
## --video-solution--
2

View File

@ -0,0 +1,159 @@
---
id: 69f42d414b7626e21a922794
title: What is Error-handling Middleware?
challengeType: 19
dashedName: what-is-error-handling-middleware
---
# --description--
Error-handling middleware in Express is a special type of middleware used to handle errors that occur during the request-response cycle. It's essential for catching unexpected errors, logging them, and providing appropriate responses to the client.
As you saw in a previous lesson under error-handling, the Express error-handling middleware has four parameters: `err`, `req`, `res`, and `next`. This middleware is invoked when an error is passed to the `next()` function.
Here's a reminder of the syntax once more:
```js
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send("Internal Server Error");
});
```
And here's what that looks like in a basic Express app:
```js
const express = require('express')
const app = express()
// A simple route that throws an error
app.get('/', (req, res) => {
throw new Error('Something went wrong!')
})
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Logs the error stack
res.status(500).send('Something went wrong!')
})
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
```
* Route Handler: The route handler intentionally throws an error to simulate a problem.
* Error-handling Middleware: This middleware is registered with `app.use()`. It catches errors passed via `next(err)` and sends a 500 HTTP response to the client with a generic error message.
* `err`: This is the error object that gets passed to the middleware.
Error-handling middleware ensures that when something goes wrong in your application, users still get a proper response. It's important to always include this middleware at the end of your middleware stack to catch any errors.
# --questions--
## --text--
What does error-handling middleware do?
## --answers--
It processes requests and sends responses.
### --feedback--
Focus on what happens when something goes wrong during a request.
---
It handles errors that occur during the request-response cycle.
---
It serves static files.
### --feedback--
Focus on what happens when something goes wrong during a request.
---
It handles routing logic.
### --feedback--
Focus on what happens when something goes wrong during a request.
## --video-solution--
2
## --text--
Which of the following parameters are required in error-handling middleware?
## --answers--
`err`, `req`, `res`, `next`.
---
`req` and `res`.
### --feedback--
Think about the parameters Express uses to recognize error handlers.
---
`err` and `next`.
### --feedback--
Think about the parameters Express uses to recognize error handlers.
---
`err` and `req`.
### --feedback--
Think about the parameters Express uses to recognize error handlers.
## --video-solution--
1
## --text--
Where should error-handling middleware be placed in the middleware stack?
## --answers--
At the top, before other middleware.
### --feedback--
Think about where error handlers are placed in code that might fail.
---
In the middle of the stack.
### --feedback--
Think about where error handlers are placed in code that might fail.
---
At the bottom, after other middleware.
---
There is no specific place for it.
### --feedback--
Think about where error handlers are placed in code that might fail.
## --video-solution--
3

View File

@ -0,0 +1,192 @@
---
id: 69f42d414b7626e21a922795
title: What are Examples of Built-in and 3rd Party Middleware?
challengeType: 19
dashedName: what-are-examples-of-built-in-and-3rd-party-middleware
---
# --description--
Express provides a range of built-in middleware functions that help perform common tasks, such as serving static files, parsing JSON request bodies, and more. You can also use third-party middleware to add functionality.
**Here are some examples of built-in middleware**:
1. `express.json()`: A built-in middleware that parses incoming JSON payloads.
```js
app.use(express.json())
```
1. `express.static()`: A middleware for serving static files like images, CSS, and JavaScript files.
```js
app.use(express.static('public'))
```
1. `express.urlencoded()`: A middleware that parses incoming requests with URL-encoded payloads, the format typically sent by HTML forms. It makes the parsed data available on `req.body`.
```js
app.use(express.urlencoded({ extended: true }))
```
**Now, here are some examples of third-party middleware:**
1. `cors`: A popular third-party middleware to enable Cross-Origin Resource Sharing.
```bash
npm install cors
```
```js
const cors = require('cors')
app.use(cors())
```
1. `morgan`: A logging middleware for HTTP requests.
```bash
npm install morgan
```
```js
const morgan = require('morgan')
app.use(morgan('tiny'))
```
Now, let's look at an example of using both built-in and third-party middleware:
```js
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const app = express()
app.use(express.json()) // Built-in middleware to parse JSON
app.use(cors()) // Third-party middleware for CORS
app.use(morgan('tiny')) // Third-party middleware for logging
app.get('/', (req, res) => {
res.send('Hello, World!')
})
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
```
* The built-in middleware `express.json()` parses incoming JSON payloads.
* The third-party middleware `cors` allows cross-origin requests, and `morgan` logs incoming HTTP requests.
It is important to note that the middleware functions are added in the order they are called with `app.use()`.
Express provides essential built-in middleware for handling common tasks like JSON parsing and static file serving. You can also extend functionality with third-party middleware for additional capabilities.
# --questions--
## --text--
Which of the following is a built-in middleware in Express?
## --answers--
`express.json()`
---
`cors`
### --feedback--
Think about which middleware comes bundled with Express, without needing a separate install.
---
`morgan`
### --feedback--
Think about which middleware comes bundled with Express, without needing a separate install.
---
`helmet`
### --feedback--
Think about which middleware comes bundled with Express, without needing a separate install.
## --video-solution--
1
## --text--
What does the `express.static()` middleware do?
## --answers--
Parses incoming JSON data.
### --feedback--
Look out for what lets you serve files like images, CSS, and JavaScript directly.
---
Logs HTTP requests.
### --feedback--
Look out for what lets you serve files like images, CSS, and JavaScript directly.
---
Serves static files.
---
Enables cross-origin requests.
### --feedback--
Look out for what lets you serve files like images, CSS, and JavaScript directly.
## --video-solution--
3
## --text--
Which of the following is a third-party middleware?
## --answers--
`express.json()`
### --feedback--
Think about the middleware installed from an external package.
---
`express.static()`
### --feedback--
Think about the middleware installed from an external package.
---
`cors`
---
`express.Router()`
### --feedback--
Think about the middleware installed from an external package.
## --video-solution--
3

View File

@ -0,0 +1,29 @@
{
"isUpcomingChange": true,
"dashedName": "lecture-express-middleware",
"helpCategory": "Backend Development",
"blockLayout": "challenge-list",
"challengeOrder": [
{
"id": "69f42cd936da600a74a84926",
"title": "What is Middleware and How Does it Work?"
},
{
"id": "69f42d414b7626e21a922792",
"title": "What is Application-level Middleware?"
},
{
"id": "69f42d414b7626e21a922793",
"title": "What is Router-level Middleware?"
},
{
"id": "69f42d414b7626e21a922794",
"title": "What is Error-handling Middleware?"
},
{
"id": "69f42d414b7626e21a922795",
"title": "What are Examples of Built-in and 3rd Party Middleware?"
}
],
"blockLabel": "lecture"
}

View File

@ -73,6 +73,7 @@
"dashedName": "express-middleware",
"comingSoon": true,
"blocks": [
"lecture-express-middleware",
"workshop-express-middleware-by-building-a-submission-form",
"lab-data-sanitizer",
"review-express-middleware",