What is Express.js?

What is Express.js?

Understanding Express

When I first started with Node.js and Express, I had difficulty understanding the technical terms used in the documentation. In this article, I aim to simplify the basics.

We'll go through the following points:

  1. What is Express?
  2. How to install Express?
  3. What is routing?
  4. What is a middleware function?

First things first.

1. What is Express.js?

Express is a free and open-source web application framework for Node.js that provides a robust set of features for web and mobile applications.

It's documentation states -

Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.

In simple words, it helps us tidy up complex code.

It was developed by TJ Holowaychuk in 2010. Rights to manage Express were bought by StrongLoop in 2014, after which StrongLoop was acquired by IBM in 2015. It was finally added as an Incubator Project by the Node.js Foundation in 2016.

2. How to install Express?

Prerequisites: You need to have Node.js installed and a project directory where you want to install Express.

In the terminal, go into the root of your project directory and run the command npm init to create a package.json file.

Anatomy of a package.json

{
  "name": "example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Once a package.json is generated, all you need to do to install Express is run the command npm install express --save. To check whether you have successfully installed Express, you can go into the package.json file in your code editor (like VS Code) and it should show express and its version under dependencies.

{
  "name": "example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

3. What is routing?

Routing refers to how a server-side application responds to a client request on a particular URL/path and a specific HTTP method.

Let's break that down.

Syntax of a route:

app.METHOD(PATH, HANDLER)

METHOD refers to HTTP methods such as get, put, post, delete. PATH refers to the URL such as /api/user. HANDLER refers to the middleware function/s that will get executed when both the method and the path match, i.e when the route is matched.

For instance, say you want to get student details from the database. So you'll have to define a route for GET method and the URL which needs to be hit when making the request. It might look something like this app.get("/api/students", getStudents(req, res)). Here, getStudents() is the middleware that will get executed when the server receives a get request at the URL /api/students. This middleware will actually go and get student details for us.

4. What is a middleware function?

Middleware functions are functions that have access to the request object(req), the response object(res), and the next middleware function in the application’s request-response cycle. An application may have more than one middleware that stacks one on top of the other.

When a request is received from the client, it is passed on to the first middleware in the stack, along with a response object and a next() callback. The middleware will execute any code inside the function. It can then either terminate the HTTP request or pass control on to the next middleware in the stack by calling next() within the body of the middleware function.

The next middleware function is commonly denoted by a variable named next and passed as an argument to the current middleware function.

Syntax of a middleware function:

function middlewareExample(req, res, next) { next(); }

An Express application can use 5 different types of middleware:

  • Application-level middleware

  • Router-level middleware

  • Error-handling middleware

  • Built-in middleware

  • Third-party middleware

App.use() is used to bind application-level middleware to an instance of the app object which is instantiated on the creation of the Express server. It is basically saying - "every request received from the client will have to go through me".

You would use router.use() for router-level middleware. The .use() method in Express is a middleware handler.

Syntax:

app.use(path, middleware function/s)

In the above example, the path (URL) is optional. When no path is specified, the function gets executed every time the app receives a request, irrespective of which URL has been hit.

Example of an application-level middleware:

Auth middleware:

In a To-Do app, once an already created user logs in, s/he is provided with a JSON Web Token (JWT), which must be verified every time the user makes an HTTP request (GET, PATCH, POST, or DELETE).

app.use("/api/*", verifyToken(req, res, next): void {
   const jwt: string = req.headers['x-token-header'];
   if (!jwt) {
      res.status(403).send({ message: 'No token provided!' });
   } else {
jsonwebtoken.verify(jwt, config.get('secretString'), (err) => {
   if (err) {
      res.status(403).send(err);
   } else {
      next();
   }
   });
});

Can you figure out which is the middleware in the above example? Correct! verifyToken(req, res, next) is the middleware function. Here, the path /api/* has been added to differentiate from requests that do not need a JWT authentication such as sign up and log in (since we don't want the middleware to be executed when there's no need for authentication).

To get a better understanding of what Express is, you need to understand Node.js and its relation to Express. Going through HTTP methods and routing will also prove to be helpful.

That's it for today. If you liked this article or have any insight on how to make it better, let me know by commenting below. Alternatively, you can hit me up on Twitter @knamrata23. where I'm always active. Thanks for reading. Until next time.

WhatsApp Image 2021-05-08 at 4.10.43 PM.jpeg