In Node.js with Express, app.use() is used to register middleware functions. It allows you to run code for every incoming request before it reaches a route or when matching a specific path.
✅ Why We Use app.use():
-
Apply Middleware Globally
app.use(express.json()); // parse incoming JSON requests -
Serve Static Files
app.use(express.static('public')); // serve HTML, CSS, JS from /public -
Mount Middleware for Specific Paths
app.use('/api', apiRoutes); // all routes inside apiRoutes will start with /api -
Error Handling
app.use((err, req, res, next) => { res.status(500).send('Something broke!'); });
🔁 Summary:
app.use() is a flexible way to plug in middleware or sub-routers, helping you handle requests, parse data, serve static files, and manage errors effectively.