The `app.use()` Function in Express

Nov 16, 2020

Express apps have a use() function. This function adds a new middleware to the app.

For example, suppose you want to print the HTTP method (get, post, etc.) and the URL of every request. Here's how you can add a new middleware that prints the HTTP method and URL of every request:

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

app.use((req, res, next) => {
  // For example, a GET request to `/test` will print "GET /test"
  console.log(`${req.method} ${req.url}`);

  next();
});

app.get('/test', (req, res, next) => {
  res.send('ok');
});

// Test the above app using Axios
const server = await app.listen(3000);

const axios = require('axios');
// Prints "get /test"
const res = await axios.get('http://localhost:3000/test');

The Middleware Stack

In Express, everything is middleware. Internally, an Express app has a middleware stack, and calling use() adds a new layer to the stack. Functions that define route handlers, like get() and post() also add layers to the stack. Express executes the middleware stack in order, so the order in which you call use() matters.

For example, one of the most common middleware functions is the cors middleware, which attaches CORS headers to your Express HTTP responses. Make sure you call app.use(cors()) before defining any route handlers or anything else that sends an HTTP response, otherwise you won't get CORS headers!

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

// This response will **NOT** have CORS headers, because order matters.
// Express will run the CORS middleware _after_ this route handler.
app.get('/nocors', (req, res) => {
  res.send('ok');
});

app.use(require('cors')());

// This response will have CORS headers, because this route handler
// is after the CORS middleware in the middleware list.
app.get('/cors', (req, res) => {
  res.send('ok');
});

Another common middleware function is Express' body parser. This middleware is responsible for parsing the request body and setting the req.body property. Make sure you call app.use(express.json()) before using req.body, otherwise it will be undefined!

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

// `body` will always be `undefined` in the HTTP response, because
// Express will run the JSON body parser _after_ this route handler.
app.post('/nobody', (req, res) => {
  res.json({ body: req.body });
});

app.use(express.json());

// `body` will contain the inbound request body.
app.post('/body', (req, res) => {
  res.json({ body: req.body });
});

The path Parameter

Although the use() function is typically called with only 1 parameter, you can also pass it a path that tells Express to only execute the given middleware when it receives a request for a URL that starts with the given path.

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

app.use('/cors', require('cors')());

// This response will **NOT** have CORS headers, because the path '/nocors'
// doesn't start with '/cors'
app.get('/nocors', (req, res) => {
  res.send('ok');
});

// This response will have CORS headers
app.get('/cors', (req, res) => {
  res.send('ok');
});

// This response will also have CORS headers, because '/cors/test' starts
// with '/cors'
app.get('/cors/test', (req, res) => {
  res.send('ok');
});

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials