Custom middleware in Node JS

Middleware in Node JS is called before the request is handled by the router function. They stand between the router and the request. Middlewares are great when it comes to processing and validating request values before they reach the route.

Make sure you have downloaded and installed Node JS in your system first. You can download Node JS from here.

We are going to create a simple middleware that will add a new field “email” with the request.

# open terminal at desktop
# following command will create a folder
> mkdir nodejs-middleware

# open the folder in command prompt
> cd nodejs-middleware

# create a file named "server.js" in that folder
# following command will initialize the project
> npm init

# install express module
> npm install express

# start the server
> node server.js

Now in our server.js file, we will first start the server.

// server.js

// include express module
const express = require("express")

// create instance of express module
const app = express()

// get the port number if already set, or 3000 otherwise
const port = process.env.PORT || 3000

// start the server at specified port
app.listen(port)

// test in browser
// http://localhost:3000

Make sure to restart the server using “node server.js” command. Now we will create our custom middleware.

// create a custom middleware
const myMiddleware = function (request, result, next) {
	// add "email" field with the request object
  	request.email = "support@adnan-tech.com"
  
  	// continue with the request
	next()
}

The following code will add the middleware to all the requests.

// attach middleware to all requests
app.use(myMiddleware)

The following code will add the middleware to specific requests only.

// attach middleware to specific request
app.get("/", myMiddleware, function (request, result) {
	// display "email" value on browser
  	result.send(request.email)
})

Restart the server and check in your browser: http://localhost:3000

External middleware in Node JS

You can create your middleware in a separate file as well in your Node JS server. Create a file named “external-middleware.js” at the root of your project and write the following code in it:

module.exports = function (request, result, next) {
	request.email = "adnan@gmail.com"
	next()
}

Then in your “server.js” file, use the middleware like the following:

const externalMiddleware = require("./external-middleware")
app.use(externalMiddleware)

To test this middleware, remove or comment out the previous middleware and refresh your browser again. Check out our android application’s tutorial we created on Node JS.