0% found this document useful (0 votes)
15 views1 page

Thecodeblocks Com Middleware in Expressjs

This document provides an overview of middleware in Express.js. It defines middleware as functions that sit between a request and response in Express apps. There are three levels of middleware: application-level middleware which runs on every request, router-level middleware which runs on requests to a specific router, and route-level middleware which runs on a specific route. Examples are given of logging, authentication and other middleware. Built-in middleware like json parsing and serving static files are also discussed.

Uploaded by

Hamza Javeed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views1 page

Thecodeblocks Com Middleware in Expressjs

This document provides an overview of middleware in Express.js. It defines middleware as functions that sit between a request and response in Express apps. There are three levels of middleware: application-level middleware which runs on every request, router-level middleware which runs on requests to a specific router, and route-level middleware which runs on a specific route. Examples are given of logging, authentication and other middleware. Built-in middleware like json parsing and serving static files are also discussed.

Uploaded by

Hamza Javeed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 1

Home Topics Tools Support Us thecodeblocks Sign in Subscribe

NODEJS

A Gentle Introduction of
Middleware in Expressjs
Kevin Durant
Feb 16, 2023 5 min

Express.js is a popular web application framework for Node.js. It provides a simple


and robust way to create web applications and APIs. One of the key features of
Express.js is its middleware system. Middleware is a function that sits between a
request and a response and can be used to perform various tasks, such as logging,
authentication, and error handling. In this blog, we will take a deep dive into
middleware in Express.js.

What is Middleware?
Middleware is a function that receives a request and a response object, and
optionally a third argument, usually called next. The middleware function can then
modify the request and/or response objects, and call the next function to pass
control to the next middleware in the chain.

Middleware functions can be used to perform a wide range of tasks, such as:

Logging

Authentication

Authorization
Error handling

Request parsing

Response formatting

Caching

In Express.js, middleware functions can be defined at the application level, the


router level, or the route level. Let's take a closer look at each of these levels.

Application-level Middleware
Application-level middleware functions are executed for every incoming request to
the application. They can be defined using the app.use() method or any of its aliases,
such as app.all(), app.get(), app.post(), etc.

Here's an example of a simple application-level middleware that logs the URL and
HTTP method of each incoming request:

const express = require('express')


const app = express()

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


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

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


res.send('Hello, world!')
})

app.listen(3000, () => {
console.log('Server started on port 3000')
})

In this example, the app.use() method is used to define the middleware function. The
middleware function logs the URL and HTTP method of each incoming request using
console.log(), and then calls the next function to pass control to the next
middleware in the chain.

Router-level Middleware
Router-level middleware functions are executed for every incoming request to a
specific router. They can be defined using the router.use() method or any of its
aliases, such as router.all(), router.get(), router.post(), etc.

Here's an example of a router-level middleware that checks if the user is


authenticated before allowing access to a protected route:

const express = require('express')


const app = express()
const router = express.Router()

const isAuthenticated = (req, res, next) => {


if (req.user) {
next()
} else {
res.status(401).send('Unauthorized')
}
}

router.use(isAuthenticated)

router.get('/profile', (req, res) => {


res.send(`Welcome, ${req.user.username}!`)
});

app.use('/api', router)

app.listen(3000, () => {
console.log('Server started on port 3000')
});

In this example, the router.use() method is used to define the middleware function.
The middleware function checks if the user is authenticated by checking if the
req.user property is set, and then either calls the next function to pass control to
the next middleware in the chain, or sends a 401 Unauthorized response if the user
is not authenticated.

Route-level Middleware
Route-level middleware functions are executed for a specific route. They can be
defined using the router.METHOD() method, where METHOD is the HTTP method of
the request, such as router.get(), router.post(), etc.

Here's an example of a route-level middleware that logs the IP address of the client
making the request:

const express = require('express')


const app = express()
const router = express.Router()

const logIP = (req, res, next) => {


console.log(`Request from ${req.ip}`)
next()
}

router.get('/hello', logIP, (req, res) => {


res.send('Hello, world!')
});

app.use('/api', router)

app.listen(3000, () => {
console.log('Server started on port 3000')
});

In this example, the router.get() method is used to define the route and the route-
level middleware function. The middleware function logs the IP address of the client
making the request using console.log(), and then calls the next function to pass
control to the route handler, which sends the response "Hello, world!".

Built-in Middleware
Express.js comes with a number of built-in middleware functions that can be used
out of the box. Here are some examples:

express.json(): This middleware function parses incoming JSON payloads and


makes them available on the req.body property.

express.urlencoded(): This middleware function parses incoming URL-encoded


payloads and makes them available on the req.body property.

express.static(): This middleware function serves static files from a directory on


the file system.

express.compress(): This middleware function compresses the response body


using gzip or deflate.

Here's an example of using the express.static() middleware function to serve static


files:

const express = require('express')


const app = express()

app.use(express.static('public'))

app.listen(3000, () => {
console.log('Server started on port 3000')
});

In this example, the app.use() method is used to define the express.static()


middleware function, which serves static files from the "public" directory on the file
system. This means that any file in the "public" directory can be accessed via a URL
that matches the file's path relative to the "public" directory. For example, a file
named "index.html" in the "public" directory can be accessed via the URL
http://localhost:3000/index.html

Third-Party Middleware
In addition to built-in middleware functions, Express.js supports the use of third-
party middleware functions. There are many third-party middleware functions
available for Express.js, and they can be installed using npm.

Here are some examples of popular third-party middleware functions:

body-parser: This middleware function parses incoming request bodies in various


formats and makes them available on the req.body property.

cookie-parser: This middleware function parses incoming cookies and makes


them available on the req.cookies property.

helmet: This middleware function adds various security-related HTTP headers to


the response.

morgan: This middleware function logs incoming requests and outgoing


responses.

Expressjs proxy: library to design api gateway in expressjs

Here's an example of using the body-parser middleware function to parse JSON


payloads:

const express = require('express')


const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.json());

app.post('/api/users', (req, res) => {


console.log(req.body)
res.send('User created')
});

app.listen(3000, () => {
console.log('Server started on port 3000')
});

In this example, the app.use() method is used to define the body-parser middleware
function, which parses incoming JSON payloads and makes them available on the
req.body property. The parsed JSON payload is then logged to the console, and a
response of "User created" is sent back to the client.

Conclusion
In this blog, we have explored the world of middleware in Express.js. We have
learned what middleware is, how it works, and how it can be used to perform a wide
range of tasks. We have also looked at the different types of middleware that are
available in Express.js, including built-in middleware functions and third-party
middleware functions.

We have seen how to define middleware functions at the application level and at the
route level, and we have looked at some examples of how middleware functions can
be used to perform tasks such as logging, parsing request bodies, and serving static
files.

In addition to the middleware functions that we have discussed, there are many
other middleware functions available in the Express.js ecosystem. Some of these
middleware functions are designed to handle specific tasks, such as authentication
or validation, while others are more general-purpose and can be used for a wide
range of tasks.

If you are building an application with Express.js, it is worth taking the time to
explore the different middleware functions that are available, and to choose the
functions that are best suited to your needs.

READ NEXT

Reverse Number lookup


Reverse number lookup, also known as a reverse phone lookup or reverse phone number search,
is the process of finding out who owns a phone number by searching public records or a…

NICHOLAS DEC 21, 2022

Understanding the Basics, Types, Features, and Benefits of API Gateway


Introduction API gateways are a crucial component of modern microservices architectures.
They act as a reverse proxy and provide a single entry point for external consumers to access t…
KEVIN DURANT JAN 27, 2023

What is namespace and room in webscoket (Socket.IO)


WebSockets are a powerful technology for building real-time, bidirectional communication
between a server and one or many clients. When building a WebSocket application, it's…
NICHOLAS JAN 19, 2023

COMMENTS (0)

Start the conversation


Become a member of thecodeblocks to start commenting.

Sign up now

Already a member? Sign in

Subscribe to thecodeblocks
Don't miss out on the latest news and tutorials

Subscribe now

Sign up privacy & policy

   

Copyright by @ thecodeblocks

You might also like