0
0
ExpressHow-ToBeginner · 3 min read

How to Use app.use in Express: Middleware Setup Explained

In Express, app.use adds middleware functions that run for every request or specific paths. It helps handle tasks like parsing data, logging, or serving static files before reaching route handlers.
📐

Syntax

The app.use method takes one or more middleware functions and an optional path. Middleware functions run in order for matching requests.

  • app.use(path, middleware): Runs middleware only if the request URL starts with path.
  • app.use(middleware): Runs middleware for all requests.

Middleware functions receive req, res, and next to process requests and pass control.

javascript
app.use([path], middlewareFunction)

// Example:
app.use('/api', (req, res, next) => {
  console.log('API middleware');
  next();
});
💻

Example

This example shows how to use app.use to log every request and serve static files from a folder named public. It demonstrates middleware running before route handlers.

javascript
import express from 'express';

const app = express();
const port = 3000;

// Middleware to log request method and URL
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// Middleware to serve static files from 'public' folder
app.use(express.static('public'));

// Simple route
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
Output
Server running on http://localhost:3000 GET /
⚠️

Common Pitfalls

Common mistakes when using app.use include:

  • Not calling next() inside middleware, which stops request processing.
  • Placing middleware after routes, so it never runs.
  • Using app.use without a path when you want it to run only on specific routes.
javascript
import express from 'express';
const app = express();

// Wrong: middleware does not call next(), request hangs
app.use((req, res) => {
  console.log('Middleware without next');
  // next() missing here
});

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

// Correct way:
app.use((req, res, next) => {
  console.log('Middleware with next');
  next();
});
📊

Quick Reference

app.use is used to add middleware functions that process requests before routes. Use it to:

  • Log requests
  • Parse JSON or URL-encoded data
  • Serve static files
  • Handle authentication

Remember to call next() to continue the request cycle.

UsageDescription
app.use(middleware)Runs middleware for all requests
app.use('/path', middleware)Runs middleware only for requests starting with '/path'
Middleware function signature(req, res, next) => { ... }
Call next()Pass control to next middleware or route

Key Takeaways

Use app.use to add middleware that runs before route handlers.
Always call next() inside middleware to continue processing requests.
app.use can apply middleware globally or to specific URL paths.
Middleware order matters: place app.use calls before routes.
Use app.use to serve static files and parse request data easily.