Learn Express Middleware Tutorial

Middleware in Express are functions that execute during the request-response cycle.

They are used to perform various tasks such as logging, authentication, validation, and more.

Create a Express basic server like we did in the previous tutorials.

What is Middleware?

  1. Middleware functions have access to the request req and response res objects and the next function.
  2. They can modify the request, response, or terminate the request-response cycle.

Using Built-in Middleware

  1. Express provides built-in middleware like express.static() for serving static files and express.json() for parsing JSON data.
// Serve static files
app.use(express.static('public'));

// Parse JSON data
app.use(express.json());
    

Creating Custom Middleware

  1. Create custom middleware functions and use them in routes.
function myMiddleware(req, res, next) {
    console.log('Custom Middleware Executed');
    next();
    }

    app.use(myMiddleware);

    app.get('/route', (req, res) => {
    res.send('Response from Route');
});
  

Middleware Execution Order

  1. The order of middleware execution matters.
app.use((req, res, next) => {
    console.log('First Middleware');
    next();
  });
  
  app.use((req, res, next) => {
    console.log('Second Middleware');
    next();
  });
  
  app.get('/route', (req, res) => {
    res.send('Response from Route');
  });
  

Error Handling Middleware

  1. Middleware can handle errors using next(err).
app.use((err, req, res, next) => {
    console.error(err.message);
    res.status(500).send('Internal Server Error');
  });
  
  app.get('/error', (req, res, next) => {
    const error = new Error('This is an error');
    next(error);
  });