Must-Have Middleware

While Express comes with minimal built-in middleware, the ecosystem provides a vast array of tools to add common functionality.

1. Morgan (Logging)

Morgan is used to log incoming requests to your terminal for debugging and monitoring.

const morgan = require('morgan');
app.use(morgan('dev'));

2. CORS (Cross-Origin Resource Sharing)

Essential when your frontend (e.g., React on port 3000) tries to talk to your backend (Express on port 5000).

const cors = require('cors');
app.use(cors());

3. Cookie-Parser

Parses Cookie headers and populates req.cookies with an object keyed by the cookie names.

const cookieParser = require('cookie-parser');
app.use(cookieParser());

// Accessing a cookie
app.get('/', (req, res) => {
  console.log('Cookies:', req.cookies);
});

4. Compression

Gzip compression can significantly decrease the size of the response body and hence increase the speed of a web app.

const compression = require('compression');
app.use(compression());
Best Practice: Always put cors() and morgan()at the very top of your app.js middleware stack.