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');
});

Built an Express app and want to deploy it?

We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.

Deploy your Express app on Railway in minutes

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

More Express Tutorials