Skip to content

2.2 Examples

Different type of middleware is shown below.

1. πŸ§‘β€πŸ’» Basic Logging Middleware

Logging middleware captures each incoming request and logs the HTTP method and URL.

const express = require('express');
const app = express();
// Basic logging middleware
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Pass to the next middleware or route handler
});
// Sample route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • Every request logs the method and URL.
  • next() ensures that the request proceeds to the next handler.

2. πŸ§‘β€πŸ’» JSON Body Parsing Middleware

When handling requests with JSON data, we need express.json() to parse the body and make it available as req.body.

const express = require('express');
const app = express();
app.use(express.json()); // Middleware to parse JSON bodies
app.post('/data', (req, res) => {
console.log(req.body); // The parsed JSON data
res.send('Received JSON data');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • The express.json() middleware automatically parses incoming JSON data and makes it available in req.body.

3. πŸ§‘β€πŸ’» URL-Encoded Form Data Parsing Middleware

For handling application/x-www-form-urlencoded data (like HTML form submissions), use express.urlencoded().

const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true })); // Middleware to parse form data
app.post('/form', (req, res) => {
console.log(req.body); // Parsed form data
res.send('Received form data');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • This middleware parses the data sent via HTML forms and makes it available in req.body.

extended option – what’s the difference?

The extended option controls how the incoming data is parsed.

βœ… extended: true
  • Uses the qs library, which can parse nested objects.
  • Example:
    Terminal window
    name=John&details[age]=30
    Becomes:
    { name: 'John', details: { age: '30' } }
❌ extended: false
  • Uses the querystring library, which only parses flat key-value pairs.
  • Same example:
    Terminal window
    name=John&details[age]=30
    Becomes:
    { name: 'John', 'details[age]': '30' }

4. πŸ§‘β€πŸ’» Authentication Middleware (Custom Middleware)

You can create custom middleware for authentication. Here’s a simple one that checks for an Authorization header.

const express = require('express');
const app = express();
// Custom authentication middleware
function checkAuth(req, res, next) {
const authHeader = req.headers['authorization'];
if (!authHeader || authHeader !== 'Bearer mysecrettoken') {
return res.status(401).send('Unauthorized');
}
next(); // Proceed to the next middleware/route
}
app.use('/private', checkAuth); // Apply to all routes under /private
app.get('/private/data', (req, res) => {
res.send('Private Data: You are authorized!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • The checkAuth middleware checks the Authorization header in the request.
  • If the header is missing or incorrect, it sends a 401 Unauthorized error.
  • If the header is valid, it allows the request to continue.

5. πŸ§‘β€πŸ’» Error Handling Middleware

Express allows you to create custom error-handling middleware. It’s used to catch errors from route handlers or other middleware.

const express = require('express');
const app = express();
// Sample route that throws an error
app.get('/error', (req, res, next) => {
const error = new Error('Something went wrong!');
next(error); // Pass error to the error handler
});
// Custom error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error
res.status(500).send('Something went wrong!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • When an error is thrown in the /error route, it’s passed to the error-handling middleware.
  • The error-handling middleware logs the error and sends a 500 status code with a message.

6. πŸ§‘β€πŸ’» Static File Serving Middleware

You can use express.static() to serve static files (like images, CSS, or JavaScript files) in your app.

const express = require('express');
const path = require('path');
const app = express();
// Middleware to serve static files
app.use(express.static(path.join(__dirname, 'public')));
// Example route
app.get('/', (req, res) => {
res.send('<h1>Home Page</h1><img src="/images/logo.png" alt="Logo">');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • Files inside the public folder are served directly when requested.
  • For example, public/images/logo.png will be available at /images/logo.png.

7. πŸ§‘β€πŸ’» Route-Specific Middleware

Middleware can be applied to specific routes only.

const express = require('express');
const app = express();
// Route-specific middleware
app.get('/admin', (req, res, next) => {
console.log('Admin route accessed');
next(); // Proceed to the next route handler
}, (req, res) => {
res.send('Welcome to the Admin Page');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • The middleware logs when the /admin route is accessed.
  • Only the /admin route uses this middleware, not others.

8. πŸ§‘β€πŸ’» Middleware for Performance (CORS)

CORS (Cross-Origin Resource Sharing) middleware helps handle cross-origin requests.

const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
// Sample route
app.get('/data', (req, res) => {
res.json({ message: 'Data from server' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

What happens?

  • CORS middleware allows requests from different origins (domains).
  • In this case, it’s enabling cross-origin requests from any domain.