Using next() in Express.js – Middleware, Error Handling Examples

In this tutorial, you will learn how to use the next function in Express js and also discuss how it plays a crucial role for developing effective Express js applications. We will explore the usage of next() function with advanced use-cases and dive into in-depth details using examples.   What is Middleware in Express.js Middleware…

By.

•

min read

In this tutorial, you will learn how to use the next function in Express js and also discuss how it plays a crucial role for developing effective Express js applications. We will explore the usage of next() function with advanced use-cases and dive into in-depth details using examples.

 

What is Middleware in Express.js

Middleware is a function which has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. A middleware can execute any code snippet and also make changes to the request and response objects. Then call the next middleware functions in the stack.

In case the current middleware functions do no end the request and response objects then it must call the next() to pass the control to the next defined function. If we fail to handle that, the request will keep handing in between.

 

Importance of ‘Next’ in Express.js

Let’s have a quick look on the importance of middleware and also the next() functions we use in it:

The next function passes the control to the next middleware function in the stack.

Middlewares plays and important role in error handling in express js. If we pass an argument to the ‘next’ function other than the string ‘route’, the express will regard the current request as in error and skip any remaining non-error handling routing and middleware functions.

Here is a simple example:

const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

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

app.listen(3000);

In above example, the middleware function logs the time of the request and then passes control to the next middleware function using next which is the route handler in this case .

 

More Examples of ‘Next’ in Express.js

Let’s look at some practical examples of using next in Express.js:

 

Simple Example on using Multiple Middlewares

Here we have two middleware functions which are loging a message and then pass control to the next middleware function using next:

const express = require('express');
const app = express();

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

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

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

app.listen(3000);

 

Using ‘Next’ for Error Handling

Lets have a look how to use the middleware function which passes an error to the next middleware function using next.

The second middleware function is an error-handling middleware function which is loging the error and sending a response to the client.

const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log('Middleware 1');
  next(new Error('Something went wrong'));
});

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

app.listen(3000);

 

Not calling ‘next’ in a middleware function.

If a middleware function does not end the request-response cycle, it must call ‘next’ to pass control to the next middleware function. Otherwise, the request will be left hanging.

It is always a good practice to handle errors in your Express.js applications. We can pass errors to the next middleware function using next whihc allows to centralize error handling in our application.

Leave a Reply

Your email address will not be published. Required fields are marked *