Menu

  • Home
  • Javascript (JS)
  • Node JS
  • React JS
  • React Native
  • More
    • Electron JS
    • WordPress
    • About
    • Code Examples
  • Contact Us
  • Our Services
  • +237 673917344
  • info@alljavascript.net
  • New Content Weekly
Beyond JavaScript Beyond JavaScript
  • Home
  • Javascript (JS)
  • Node JS
  • React JS
  • React Native
  • More
    • Electron JS
    • WordPress
    • About
    • Code Examples
  • Contact Us
  • Our Services
  • July 21, 2022
  • admin
  • 0 Comments
  • 205 Views
  • 1 Likes
  • Node JS

Introduction To Express Middleware

What is an Express Middleware ?

Usually as developers, we feel it’s a pain in the “ass” to have a seat and read about concepts, architectures or some framework or programming language related theory. But it’s worth it and very necessary because opens you up to the entire concept of how the framework or language works, thus equipping the developer to write cleaner code and saves time.
In this tutorial, we will discuss express Middleware(s).- I presume you have seen the word “Middleware” before, perhaps in a documentation or video tutorial and have been using middleware without the proper understanding of how it works.
We are going to cover what a middleware is all about and discuss some types of middleware with examples.
Now Lets dive in:-

Well, we are not gonna be building a big super huge fancy project, but learn what you must know in order to build that dream project you got in mind.

Prerequisite

  • Basic knowledge on Node JS and Express JS.
  • Have Node JS and Express JS installed.

What are express middleware?

have a look at this piece of code below

app.get ('/', (req, res)=>{
    console.log('Hello')
})

From the code above, you can notice two major keywords; req (which stands for request) and res(which stands for response). That’s basically how websites work right?…A request is made by the client and then the server gives a response and the cycle continues as a user continues navigating through a website.

A middleware is therefore a function that has access, can make changes, execute code and even stop the request and response cycle. In other words, a middleware is a function or functions that have access to the request and response object (req, res). A middleware can also call another middleware using the next keyword.
Do you get it?

We all know Express JS is a server side web framework right…From the definition of middleware above, it’s quiet noting that express applications then are just combinations of middleware functions.

Now, lets look at some types of middleware and examples:-

From the code above, you can notice two major keywords; req (which stands for request) and res(which stands for response). That’s basically how websites work right?…A request is made by the client and then the server gives a response and the cycle continues as a user continues navigating through a website.

A middleware is therefore a function that has access, can make changes, execute code and even stop the request and response cycle. In other words, a middleware is a function or functions that have access to the request and response object (req, res). A middleware can also call another middleware using the next keyword.
Do you get it?

We all know Express JS is a server side web framework right…From the definition of middleware above, it’s quiet noting that express applications then are just combinations of middleware functions.

Now, lets look at some types of middleware and examples:-

Types Of Middleware

We have the;

  • Application level middleware,
  • Router level middleware,
  • Error-handling middleware,
  • Built-in middleware and
  • Third-party middleware
    ….according to the Express JS!.

Interesting right..?
Lets have a look at them;

  1. Application level middlewares are those functions usually bound to the instance of the app object (const app = express() //the app object) using either the syntax;
    app.use(…//function) or app.METHOD(…//function). Method here refers to the HTTP (GET, PUT, POST, DELETE).
    Below is an example of application level middleware.

create an app.js file and add:-

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

//new middleware
app.use ((req, res)=>{
    console.log('Hello, I am an Application Level Middleware');
})

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

The code above prints ‘Hello, I am an Application Level Middleware’ on the console when you open your browser and access http://localhost:3000/.

The app.use() middleware simply interferes during the all the request-response cycles and executes the function passed. Therefore, this is not specific to a route path (like ‘/about’ for example).
The logic is equally similar when a middleware is created using app.METHOD as seen below, but the difference is just the addition of a route.
Note that, these use cases here are not standard. Hence you can customize your middleware based on your needs.

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

//first middleware
app.use ((req, res, next)=>{
    console.log('Hello, I am an Application Level Middleware');
    next()
})

//another middleware (the home route)
app.get('/',(req, res)=>{
    console.log('the home page');
    res.send('HOME PAGE')
})

app.get('/about',(req, res)=>{
    console.log('the about page');
    res.send('ABOUT PAGE')
})

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

Two more middleware (routes) have been added which works as explained earlier. Notice the next and next() key words in the first middleware (app.use), which enables the execution to the subsequent middleware else the code blocks after the first middleware has been executed.
You can try removing the ‘next, next()’ and see your application’s behavior.
Also, notice the appearance of the first middleware’s text twice on the console as we accessed the home and the about route in the browser. This is just to remind you that app.use() runs for every request operation irrespective of the route.

  1. Router level middleware got practically the same logic as the application level middleware but with just a little difference in syntax. This middleware function is rather bound to the express.Router() instance.
const express = require ('express');
const app = express ();
const router = express.Router();

//enable the use of the router instace, since express doesn't use this by default
app.use('/', router);

//first middleware
router.use ((req, res, next)=>{
    console.log('Hello, I am an Application Level Middleware');
    next()
})

//another middleware (the home route)
router.get('/',(req, res)=>{
    console.log('the home page');
    res.send('HOME PAGE')
})

router.get('/about',(req, res)=>{
    console.log('the about page');
    res.send('ABOUT PAGE')
})

app.listen(3000,()=>{
    console.log('code running on port 3000');
})
  1. Error-handling middleware as the name implies is very useful in handling errors in an express application. We will not cover code examples in this tutorial since we already understand the logic behind the operation of middlewares.
  2. Built-in middlewares are simply some middlewares included in Express JS by default. For example; express.static(), express.json() and more. You can check them out on the Express JS documentation link at the bottom of this article. We will cover them each in a separate tutorial.
  3. Third-party middlewares are used to add some special features or functionalities in an express application. It must first be installed on your host or local machine from npm (node package manager), imported in your file and them configured(if necessary). Third-party middlewares are at times refered to as packages or modules.
    The node package manager (npm) website (link below) contains a vast number of packages from other developers (including Express JS dev group) all around the world.
    We are equally going to cover a good number of modules and projects in subsequent tutorials.
    Some examples of third-party middlewares or modules and their uses are ;
  • Passport JS: For authentication
  • Serve-favicon: To add a favicon to your web app.
  • Morgan (useful during development): Http requests logger
  • Multer : Facilitates file upload

And many more…

Thanks for staying till the end. Hope you learnt something new. You can always drop your comments and share with other devs. Remember we will cover more real code and projects in the next tutorials.

Read about morgan middleware

Thanks again…see you !

Links: Express JS Doc, NPM Official Website, Our Website

Spread the love
Tags:
Express JsNode JS
Prev PostWhat are Mongoose Hooks
Next PostHTML Tags
Related Posts
  • How to Make API Calls in Electron.js: A Step-by-Step Tutorial February 7, 2024
  • How to Open and Read an Excel File in Node.js: A Step-by-Step Tutorial February 7, 2024

Leave a Comment Cancel Comment

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

Recent Posts

  • How to Make API Calls in Electron.js: A Step-by-Step Tutorial
  • How to Open and Read an Excel File in Node.js: A Step-by-Step Tutorial
  • Electron.js and Express.js backend: A Comprehensive Tutorial
  • How to Get Started with Electron.js: A Tutorial for Beginners
  • How to add Favicon in Express.js: A Step-by-Step Tutorial

Recent Comments

No comments to show.

Popular Posts

February 7, 2024 / Electron JS, Node JS
How to Make API Calls in Electron.js: A Step-by-Step Tutorial
February 7, 2024 / Javascript (JS), Node JS
How to Open and Read an Excel File in Node.js: A Step-by-Step Tutorial
February 7, 2024 / Electron JS, Javascript (JS)
Electron.js and Express.js backend: A Comprehensive Tutorial

Tags

Express Js Json Morgan Node JS NPM

Categories

  • Electron JS
  • Html, CSS
  • Javascript (JS)
  • MongoDB
  • Node JS
  • React Native

We are a community of developers aimed at teaching code and solving coding problems. We provide coding articles, opportunities, content, videos and tutorials to help developers around the world...

Our Services

  • Website Design
  • Domain and Web Hosting
  • Tutoring
  • Mobile Apps
  • Website Content Writing

Recent Posts

  • How to Make API Calls in Electron.j

    Feb 7, 2024

  • How to Open and Read an Excel File

    Feb 7, 2024

Useful Links

  • Home
  • Services
  • Blog #2
  • About Us
  • Contact Us
  • Request Tutorials
  • Jobs
  • Volunteer
  • Hire Us
  • Support
info@alljavascript.net Drop Us a Line
+237 673917344 Call Us Now
Africa Get Direction
Copyright 2022 alljavascript.net, All rights reserved.