</>
Skip to content
Node.js lessons (35/44)

Node.js — Middleware

What is Middleware?

Middleware functions have access to request, response, and next.

app.use((req, res, next) => {
    console.log('Middleware executed');
    next();
});

Built-in Middleware

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));

Custom Middleware

// Logger
const logger = (req, res, next) => {
    console.log(`${req.method} ${req.url} - ${Date.now()}`);
    next();
};

// Auth
const auth = (req, res, next) => {
    if (!req.headers.authorization) {
        return res.status(401).json({ error: 'Unauthorized' });
    }
    next();
};

app.use(logger);
app.use('/api', auth);

Route-Level Middleware

app.get('/admin', auth, adminHandler);
app.post('/api', [auth, validate], apiHandler);

Error Handling Middleware

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: 'Something went wrong!' });
});

Third-Party Middleware

const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');

app.use(cors());
app.use(helmet());
app.use(morgan('combined'));

Mini Practice

  1. Create a logger middleware
  2. Add authentication middleware
  3. Handle errors with middleware
  4. Use third-party middleware

Up Next

Continue with Authentication — user authentication.

Related Topics

Frequently Asked Questions about Middleware

What is Middleware in Node.js?

Middleware is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Middleware?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Middleware.

Why is Middleware important in Node.js?

Middleware is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.