0
0
Expressframework~5 mins

Third-party middleware installation in Express

Choose your learning style9 modes available
Introduction

Middleware helps your Express app do extra tasks like parsing data or logging. Third-party middleware is ready-made code you can add easily.

You want to handle JSON data sent by users.
You need to log every request to your server.
You want to add security features like helmet.
You want to compress responses to make them faster.
You want to handle cookies in your app.
Syntax
Express
npm install middleware-package-name

const middleware = require('middleware-package-name');
app.use(middleware(options));
First, install the middleware package using npm.
Then, import it in your app and add it with app.use().
Examples
This installs and uses morgan to log requests in a short format.
Express
npm install morgan

const morgan = require('morgan');
app.use(morgan('tiny'));
This installs and uses cors to allow cross-origin requests.
Express
npm install cors

const cors = require('cors');
app.use(cors());
This installs and uses helmet to add security headers.
Express
npm install helmet

const helmet = require('helmet');
app.use(helmet());
Sample Program

This program installs morgan middleware to log every request in a developer-friendly format. When you visit the homepage, it shows a message and logs the request in the console.

Express
const express = require('express');
const morgan = require('morgan');

const app = express();

// Use morgan middleware to log requests
app.use(morgan('dev'));

app.get('/', (req, res) => {
  res.send('Hello, middleware!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always install middleware packages before using them.

Order matters: place middleware before routes to affect requests properly.

Some middleware needs options to work correctly; check their docs.

Summary

Third-party middleware adds useful features to Express apps easily.

Install with npm, then add with app.use().

Use middleware before your routes to handle requests properly.