Built-in Middleware in Express.js
Built-in middleware is middleware functionality provided directly by Express.js to perform common tasks in web applications.
Express.js provides built-in middleware to parse incoming request data and serve static files. We can use these functions without installing separate packages for the same basic functionality.
In this tutorial, we will learn about
express.json(), express.urlencoded(),
and express.static() with practical examples.
1. What Is Built-in Middleware?
Built-in middleware refers to middleware functions included with Express.js. These functions help process requests or serve files without requiring us to write all the functionality from scratch.
const express = require('express');
const app = express();
// Built-in middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
In this example, the application registers three built-in middleware functions for JSON parsing, URL-encoded form parsing, and serving static files.
2. Types of Built-in Middleware
| Middleware | Purpose | Example Use |
|---|---|---|
express.json() |
Parses incoming JSON request bodies. | Receiving JSON data from an API client. |
express.urlencoded() |
Parses URL-encoded request bodies. | Processing HTML form submissions. |
express.static() |
Serves static files from a directory. | Serving HTML, CSS, JavaScript, and images. |
3. express.json() Middleware
The express.json() middleware parses incoming
requests containing JSON data. After parsing, the data becomes
available through req.body.
Example:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/user', (req, res) => {
console.log(req.body);
res.json({
message: 'User data received successfully',
user: req.body
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Send this JSON request:
{
"name": "Rahul",
"age": 25
}
Send a POST request to
http://localhost:3000/user with the
Content-Type: application/json header.
Example response:
{
"message": "User data received successfully",
"user": {
"name": "Rahul",
"age": 25
}
}
req.body may remain undefined for a JSON request.
Always validate incoming data before using it.
4. express.urlencoded() Middleware
The express.urlencoded() middleware parses
incoming request bodies encoded in the URL-encoded format.
This format is commonly used by HTML forms.
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.post('/register', (req, res) => {
const name = req.body.name;
const email = req.body.email;
res.send(`Name: ${name}, Email: ${email}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Example HTML form:
<form action="/register" method="POST">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button type="submit">Register</button>
</form>
When the form is submitted, Express parses the submitted
form values and makes them available through
req.body.
extended: true option
allows the URL-encoded parser to support rich objects and arrays.
Use the setting appropriate for your application.
5. express.static() Middleware
The express.static() middleware serves static files
such as HTML, CSS, JavaScript, images, and other public assets.
Example folder structure:
myapp/
│
├── app.js
└── public/
├── index.html
├── style.css
└── script.js
Express application:
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server running on port 3000');
});
With this configuration, a file named
public/index.html can be requested at
http://localhost:3000/index.html.
If you want the home URL / to return the
index.html file, place that file in the
configured static directory.
public is a common convention. You can use a
different directory name if needed.
6. How Built-in Middleware Works
Client Request
Browser or API client sends a request
Built-in Middleware
Parses request data or serves static files
Route Handler
Processes the request when applicable
Response
Server sends the result to the client
The exact flow depends on the middleware. For example, static middleware may serve a file directly without reaching a route handler.
7. Complete Example Using Built-in Middleware
The following example combines JSON parsing, URL-encoded form parsing, and static file serving in one application.
const express = require('express');
const app = express();
// Parse JSON request bodies
app.use(express.json());
// Parse URL-encoded form bodies
app.use(express.urlencoded({ extended: true }));
// Serve static files from the public directory
app.use(express.static('public'));
app.post('/api/message', (req, res) => {
res.json({
message: 'Request processed successfully',
data: req.body
});
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Save the code in app.js, install Express with
npm install express, and run it using
node app.js.
Important Points to Remember
express.json()parses JSON request bodies.express.urlencoded()parses URL-encoded form data.express.static()serves files from a directory.- Register middleware before routes that depend on it.
- Parsed request body data is accessed through
req.body. - Validate user input before processing or saving it.
- Static middleware may send a response without reaching a route handler.
Summary
Express.js provides built-in middleware for common web application tasks. The JSON parser reads JSON request bodies, the URL-encoded parser processes form submissions, and the static middleware serves public files.
Understanding these functions helps you build Express.js applications that handle incoming data and static resources correctly.