What is the difference between app.use and app.get in Express

· Category: Node.js

Short answer

app.use() mounts middleware that can match any HTTP method and often a path prefix, while app.get() defines a route handler specifically for GET requests at an exact path.

Key differences

  • Matching: app.use('/api', handler) matches /api, /api/users, and /api/users/1. app.get('/api', handler) matches only GET requests to exactly /api.
  • Execution: app.use() runs for all HTTP methods unless restricted. app.get() only handles GET.
  • Purpose: app.use() is for middleware like logging and authentication. app.get() is for defining endpoints that return data or render pages.

When to use each

  • Use app.use() when you need cross-cutting functionality like parsing request bodies or serving static files.
  • Use app.get(), app.post(), and other method-specific handlers when you are building API endpoints.
  • Mount routers with app.use('/base', router) to namespace a group of routes.