Node.js January 3, 2025 Aditya Rawas

app.use vs app.all in Express.js: Key Differences Explained

When working with Express.js, app.use and app.all are two commonly used methods that can look similar at first glance. But they serve fundamentally different purposes. Understanding the distinction will help you structure your Express applications correctly.


What is app.use?

app.use mounts middleware functions — functions that run before the request reaches a route handler. You can apply middleware globally (for all routes) or selectively (for a specific path prefix).

Key characteristics:

Syntax:

app.use([path], middleware);

Example:

app.use('/user', (req, res, next) => {
  console.log('Middleware triggered for any /user path');
  next(); // Pass control to the next middleware or route handler
});

This middleware runs for any request whose path starts with /user.


What is app.all?

app.all defines a route handler that responds to all HTTP methods (GET, POST, PUT, DELETE, PATCH, etc.) for a specific path. Unlike app.use, it’s for request handling — not middleware logic.

Key characteristics:

Syntax:

app.all(path, handler);

Example:

app.all('/user', (req, res) => {
  res.send('Handles all HTTP methods for exactly /user');
});

Side-by-Side Comparison

Featureapp.useapp.all
PurposeMount middlewareHandle all HTTP methods for a route
Path matchingPartial (prefix match)Exact match only
HTTP methodsAll methods (unless restricted)All HTTP methods
Execution orderRuns before route handlersHandles the request directly
Calls next()?Usually yes (passes control)Usually no (sends a response)

When to Use Which

Use app.use when you want to:

// Apply JSON body parsing to all routes
app.use(express.json());

// Apply auth middleware to all /api routes
app.use('/api', authMiddleware);

Use app.all when you want to:

app.all('/health', (req, res) => {
  res.status(200).json({ status: 'ok' });
});

Execution Order

When both are defined for overlapping paths:

  1. app.use middleware runs first.
  2. app.all handles the request after middleware.
app.use('/user', (req, res, next) => {
  console.log('Middleware: runs first');
  next();
});

app.all('/user', (req, res) => {
  res.send('Route handler: runs second');
});

FAQs

Q: Can I use app.all to apply middleware? A: No. app.all is for route handling. Use app.use for middleware logic.

Q: Does app.use work for all HTTP methods? A: Yes, unless the middleware explicitly checks and restricts the method.

Q: Can app.all match subpaths like app.use? A: No. app.all('/user', handler) only matches exactly /user.

Q: What’s the difference when both handle the same path? A: app.use middleware runs first. If it calls next(), control passes to app.all (or the next matching handler).

Q: Should I use app.use or app.all for logging? A: Use app.use — logging is middleware that should run for every request before reaching any route.


Key Takeaways