6 Built-in Express Middlewares

Mayank Choubey
Tech Tonic
7 min readMay 27, 2024

--

Express is an integral part of any Node.js application. Express was and is the most popular framework for the Node world. In this beginner article, we’ll go over the 6 built-in middlewares that are provided by Express. The deprecated middlewares are not covered.

Introduction

In Express, a middleware is a function that has access to the entire request and response object, as well as the next function in the application’s request-response cycle. Middlewares are used to perform various tasks such as authentication, logging, parsing, and more. They are called in the order they are defined, and each middleware can either call the next middleware in the stack or terminate the request-response cycle.

Middlewares are a powerful feature of Express, allowing developers to modularize and reuse code, and to perform complex tasks in a flexible and efficient way. They can be used to:

  • Parse and validate request data
  • Authenticate and authorize requests
  • Log and monitor requests
  • Compress and encrypt responses
  • Handle errors and exceptions

Built-in Express Middlewares

Here is a list of 6 built-in Express middlewares:

  • express.json(): parses JSON bodies
  • express.urlencoded(): parses URL-encoded bodies
  • express.text(): parses text bodies
  • express.raw(): parses raw buffer bodies
  • express.query(): parses query strings
  • express.static(): serves static assets

Let’s go through each of the 6 middleware one by one.

express.json

The express.json() middleware is a built-in middleware in Express that parses incoming requests with JSON payloads. It parses the JSON data from the request body and populates the req.body object with the parsed data.

How it works

When a request is made to an Express route, the express.json() middleware is called. It checks the Content-Type header of the request to ensure it is set to application/json . If it is, the middleware attempts to parse the request body as JSON. If the parsing is successful, the parsed data is stored in the req.body object.

Code Sample

Here’s an example of how to use the express.json() middleware:

const express = require('express');
const app = express();

// Mount the json middleware
app.use(express.json());

// Define a route to handle JSON data
app.post('/api/data', (req, res) => {
console.log(req.body); // prints the parsed JSON data
res.send('JSON data received!');
});

// Test code ---- Send a JSON request to the route

const jsonData = { name: 'John', age: 30 };
fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(jsonData),
});

In this example, the express.json() middleware is mounted as a global middleware using app.use(). When a POST request is made to the /api/data route, the middleware parses the JSON data from the request body and populates the req.body object.

Note: Make sure to mount the express.json() middleware before defining your routes, as it needs to parse the request body before the route handlers are called.

Internally, express.json is just an alias:

exports.json = bodyParser.json

express.urlencoded

The express.urlencoded() middleware is a built-in middleware in Express that parses incoming requests with URL-encoded data. It parses the URL-encoded data from the request body and populates the req.body object with the parsed data.

How it works

When a request is made to an Express route, the express.urlencoded() middleware is called. It checks the Content-Type header of the request to ensure it is set to application/x-www-form-urlencoded. If it is, the middleware attempts to parse the request body as URL-encoded data. If the parsing is successful, the parsed data is stored in the req.body object.

Code Sample

Here’s an example of how to use the express.urlencoded() middleware:

const express = require('express');
const app = express();

// Mount the urlencoded middleware
app.use(express.urlencoded({ extended: true }));

// Define a route to handle URL-encoded data
app.post('/api/data', (req, res) => {
console.log(req.body); // prints the parsed URL-encoded data
res.send('URL-encoded data received!');
});

// Test code --- Send a URL-encoded request to the route

const formData = new FormData();
formData.append('name', 'John');
formData.append('age', 30);
fetch('/api/data', {
method: 'POST',
body: formData,
});

In this example, the express.urlencoded() middleware is mounted as a global middleware using app.use(). The { extended: true } option is used to enable support for nested objects and arrays. When a POST request is made to the /api/data route, the middleware parses the URL-encoded data from the request body and populates the req.body object.

Internally, express.urlencoded is just an alias:

exports.urlencoded = bodyParser.urlencoded

express.text

The express.text() middleware is a built-in middleware that parses incoming requests with plain text data. It parses the text data from the request body and populates the req.body object with the parsed data.

How it works

When a request is made to an Express route, the express.text() middleware is called. It checks the Content-Type header of the request to ensure it is set to text/plain. If it is, the middleware attempts to parse the request body as plain text. If the parsing is successful, the parsed data is stored in the req.body object as a string.

Code Sample

Here’s an example of how to use the express.text() middleware:

const express = require('express');
const app = express();

// Mount the text middleware
app.use(express.text());

// Define a route to handle plain text data
app.post('/api/data', (req, res) => {
console.log(req.body); // prints the parsed plain text data
res.send('Plain text data received!');
});

// Test code ---- Send a plain text request to the route

const textData = 'Hello, World!';
fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: textData,
});

In this example, the express.text() middleware is mounted as a global middleware using app.use(). When a POST request is made to the /api/data route, the middleware parses the plain text data from the request body and populates the req.body object.

Again, express.text is just an alias:

exports.text = bodyParser.text

express.raw

The express.raw() middleware is a built-in middleware that parses incoming requests with raw buffer data. It parses the raw buffer data from the request body and populates the req.body object with the parsed data.

How it works

When a request is made to an Express route, the express.raw() middleware is called. It checks the Content-Type header of the request to ensure it is set to application/octet-stream. If it is, the middleware attempts to parse the request body as raw buffer data. If the parsing is successful, the parsed data is stored in the req.body object as a Buffer.

Code Sample

Here’s an example of how to use the express.raw() middleware:

const express = require('express');
const app = express();

// Mount the raw middleware
app.use(express.raw({ type: 'application/octet-stream' }));

// Define a route to handle raw buffer data
app.post('/api/data', (req, res) => {
console.log(req.body); // prints the parsed raw buffer data
res.send('Raw buffer data received!');
});

// Test code --- Send a raw buffer request to the route

const bufferData = Buffer.from('Hello, World!', 'utf8');
fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: bufferData,
});

In this example, the express.raw() middleware is mounted as a global middleware using app.use(). The { type: 'application/octet-stream' } option is used to specify the content type for which the middleware should parse the request body. When a POST request is made to the /api/data route, the middleware parses the raw buffer data from the request body and populates the req.body object.

Internally, this is also an alias:

exports.raw = bodyParser.raw

express.query

The express.query() middleware is a built-in middleware that parses the query string from the request URL and populates the req.query object with the parsed data.

How it works

When a request is made to an Express route, the express.query() middleware is called. It takes the query string from the request URL, parses it, and stores the parsed data in the req.query object.

Code Sample

Here’s an example of how to use the express.query() middleware:

const express = require('express');
const app = express();

// Mount the query middleware
app.use(express.query());

// Define a route to handle query data
app.get('/api/data', (req, res) => {
console.log(req.query); // prints the parsed query data
res.send('Query data received!');
});

// Test code --- Send a GET request with query string to the route
fetch('/api/data?name=John&age=30', {
method: 'GET',
});

In this example, the express.query() middleware is mounted as a global middleware using app.use(). When a GET request is made to the /api/data route with a query string, the middleware parses the query string and populates the req.query object.

Note: The req.query object is an object with key-value pairs, where the keys are the query parameter names and the values are the query parameter values. In the example above, the req.query object would be { name: 'John', age: '30' }.

Also, note that the express.query() middleware is enabled by default in Express, so you don't need to mount it explicitly unless you want to customize its behavior.

This time, the middleware is provided by Express (but internally uses qs):

exports.query = require('./middleware/query');

express.static

The express.static() middleware is a built-in middleware in Express that serves static assets such as images, stylesheets, and JavaScript files. It allows you to serve files from a specified directory without having to write separate routes for each file.

How it works

When a request is made to an Express route, the express.static() middleware is called. It checks if the requested file exists in the specified directory and serves it if it does. If the file does not exist, it calls the next middleware in the stack.

Code Sample

Here’s an example of how to use the express.static() middleware:

const express = require('express');
const app = express();

// Serve static files from the 'public' directory
app.use(express.static('public'));

// Define a route to handle requests for non-static files
app.get('*', (req, res) => {
res.send('This is not a static file!');
});

// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});

In this example, the express.static() middleware is mounted as a global middleware using app.use(). It serves files from the public directory. When a request is made for a file that exists in the public directory, the middleware serves the file. If the file does not exist, it calls the next middleware in the stack, which in this case is the route handler for non-static files.

Note: The express.static() middleware is often used to serve files such as images, stylesheets, and JavaScript files that are used by web applications. It is a convenient way to serve files without having to write separate routes for each file.

Also, note that you can specify options to the express.static() middleware, such as setting the maxAge option to control caching, or setting the index option to specify the default file to serve when a directory is requested.

Internally, this is provided by a separate NPM package:

exports.static = require('serve-static');

That’s all about it. Thanks for reading!

--

--