Education

Mastering Express Middleware: From Logging to Authentication

Express.js is one of the most favoured frameworks for building web servers in JavaScript. It is simple, flexible, and powerful. One of its best features is middleware. Middleware is like a set of building blocks. Each one handles a small part of the request and response process. When you put them together, you get a complete and working web server.

In this blog, we will explore what middleware is, how it works in Express, and how you can use it to add features like logging, verification, and error handling to your application. We will explain each concept in simple terms with easy examples.

If you’re learning backend development through a full stack java developer training, understanding Express middleware is a must. It helps you build secure, maintainable, and clean backend code for your web apps.

What is Middleware?

Middleware in Express is a function that works between the time a request is received and the time a response is delivered. Middleware can do many things, such as:

  • Logging information
  • Checking if a user is logged in
  • Parsing request data
  • Handling errors

You can think of middleware as a pipeline. Each middleware does something with the request or response and then passes it to the next one.

A Simple Example

const express = require(‘express’);

const app = express();

app.use((req, res, next) => {

  console.log(‘This middleware runs for every request’);

  next(); // go to the next middleware

});

app.get(‘/’, (req, res) => {

  res.send(‘Hello, world!’);

});

app.listen(3000);

In the example above, the middleware logs a message for every request. It then calls next() to continue to the route handler.

Types of Middleware

There are different types of middleware in Express:

  1. Application-level middleware
  2. Router-level middleware
  3. Error-handling middleware
  4. Built-in middleware
  5. Third-party middleware

Each type serves a different purpose. Let’s go over them one by one.

1. Application-Level Middleware

This is the most common type. You attach it to the app using app.use() or app.METHOD() (like app.get()).

Example:

app.use((req, res, next) => {

  console.log(`Request URL: ${req.url}`);

  next();

});

This runs for every request.

2. Router-Level Middleware

You can also attach middleware to a router instead of the whole app. This helps organize your code.

Example:

const router = express.Router();

router.use((req, res, next) => {

  console.log(‘Router-level middleware’);

  next();

});

router.get(‘/dashboard’, (req, res) => {

  res.send(‘Dashboard page’);

});

app.use(‘/user’, router);

Now, this middleware will run for any route that starts with /user.

3. Error-Handling Middleware

This type handles errors in the app. It has four arguments: (err, req, res, next).

Example:

app.use((err, req, res, next) => {

  console.error(‘Error:’, err.message);

  res.status(500).send(‘Something went wrong!’);

});

If any error occurs in your routes, Express will pass it to this middleware.

4. Built-in Middleware

Express also comes with some built-in middleware:

  • express.json() – parses JSON data
  • express.urlencoded() – parses form data

You can use them like this:

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

This allows your app to read data from forms and JSON requests.

5. Third-Party Middleware

There are many popular middleware packages you can install and use. Examples:

  • morgan – for logging
  • cors – for handling cross-origin requests
  • cookie-parser – for reading cookies

Install with npm:

npm install morgan

Use it in your app:

const morgan = require(‘morgan’);

app.use(morgan(‘tiny’));

This logs details about each request.

Common Use Cases

Now, let’s look at how you can use middleware for real-world tasks like logging and authentication.

Logging Requests

Logging helps you keep track of what users are doing on your site.

You can write your own logging middleware:

app.use((req, res, next) => {

  console.log(`${req.method} ${req.url}`);

  next();

});

Or use morgan, a ready-to-use logger:

const morgan = require(‘morgan’);

app.use(morgan(‘dev’));

Both will show useful request info in the terminal.

Handling Authentication

Middleware is very useful for checking if a user is logged in.

function checkAuth(req, res, next) {

  if (req.headers[‘authorization’]) {

    next(); // user is allowed

  } else {

    res.status(401).send(‘Not authorized’);

  }

}

app.get(‘/private’, checkAuth, (req, res) => {

  res.send(‘Secret info’);

});

This middleware checks for an authorization header before showing protected data.

This kind of logic is very common in apps you build during a full stack developer classes program. You’ll often create dashboards or APIs that should only work for logged-in users.

Custom Middleware for Timing

You can measure how long a request takes using custom middleware.

app.use((req, res, next) => {

  const start = Date.now();

  res.on(‘finish’, () => {

    const duration = Date.now() – start;

    console.log(`Request took ${duration}ms`);

  });

  next();

});

This logs how long each request takes from start to finish.

Error Handling in Real Apps

When something goes wrong, your app should handle it properly. Error-handling middleware helps you do that.

app.get(‘/error’, (req, res) => {

  throw new Error(‘This is an example error’);

});

app.use((err, req, res, next) => {

  console.error(‘Caught Error:’, err.message);

  res.status(500).send(‘Server Error’);

});

This catches the error and responds with a friendly message instead of crashing the app.

Middleware Order Matters

Middleware runs in the order you define it. If you write them in the wrong order, some might not work.

Example:

app.use(middleware1);

app.use(middleware2);

app.get(‘/’, routeHandler);

In this case:

  1. middleware1 runs first
  2. Then middleware2
  3. Finally, the route handler

If you forget to call next() in a middleware, the request will stop there.

Combining Multiple Middleware

You can also use multiple middleware functions for a single route:

function step1(req, res, next) {

  console.log(‘Step 1’);

  next();

}

function step2(req, res, next) {

  console.log(‘Step 2’);

  next();

}

app.get(‘/multi’, step1, step2, (req, res) => {

  res.send(‘All steps done!’);

});

This gives you full control over how requests move through your app.

Final Thoughts

Express middleware is a powerful tool that every backend developer should learn. It allows you to organize your code into small pieces that are easy to manage and reuse. From simple logging to advanced authentication, middleware can help you build apps that are secure, fast, and reliable.

Let’s quickly review what you’ve learned:

  • Middleware runs between the request and response
  • You can use it to log data, handle errors, check users, and more
  • Built-in and third-party middleware make your job easier
  • Middleware runs in the order it is written
  • You can create custom middleware to fit your project’s needs

If you’re enrolled in a full stack java developer course, mastering middleware will make you a stronger backend developer. You’ll be able to build real-world web apps that follow best practices and are easy to update as your app grows.

Start small, try building your own middleware, and soon you’ll be creating powerful backends with confidence.

Contact Us:

Name: ExcelR – Full Stack Developer Course in Hyderabad

Address: Unispace Building, 4th-floor Plot No.47 48,49, 2, Street Number 1, Patrika Nagar, Madhapur, Hyderabad, Telangana 500081

Phone: 087924 83183