Third-Party Middleware

Add popular packages like morgan for logging and cors for cross-origin requests.

Syntaxapp.use(morgan('dev'))

The npm ecosystem has thousands of middleware packages. You install them, then plug them in with app.use(). Two very common ones:

  • morgan — logs every request in a readable format, great for development.
  • cors — adds the headers that let browsers on other domains call your API.

Install both with npm install morgan cors.

Example

Example · javascript
const morgan = require('morgan');
const cors = require('cors');

app.use(morgan('dev'));   // log requests
app.use(cors());          // allow cross-origin requests

app.get('/', (req, res) => res.json({ ok: true }));

When to use it

  • A production Express app uses morgan to write structured access logs to stdout that a log aggregator can parse.
  • A developer installs cors middleware to allow a React app running on localhost:5173 to call the API on localhost:3000.
  • A team uses helmet to set secure HTTP response headers on every response, hardening the app against common web vulnerabilities.

More examples

HTTP request logging with morgan

Registers morgan in 'dev' mode to print coloured request logs including method, URL, status, and response time.

Example · js
const express = require('express');
const morgan = require('morgan');
const app = express();

app.use(morgan('dev'));

app.get('/', (req, res) => res.send('Logged!'));
app.listen(3000);

CORS for cross-origin requests

Configures the cors middleware to allow only the specified frontend origin and a set of HTTP methods.

Example · js
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors({
  origin: 'https://myfront.example.com',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
}));

app.get('/api/data', (req, res) => res.json({ data: [] }));
app.listen(3000);

Helmet security headers

Registers Helmet with default settings to add headers like Content-Security-Policy, X-Frame-Options, and HSTS.

Example · js
const express = require('express');
const helmet = require('helmet');
const app = express();

app.use(helmet()); // sets 11+ security headers automatically

app.get('/', (req, res) => res.send('Secure response'));
app.listen(3000);

Discussion

  • Be the first to comment on this lesson.