ExpressJS is the most popular web framework for NodeJS. It provides an easy way to build large scale web and mobile applications using the power of NodeJS. In this post, we will learn how to get started with ExpressJS.

If you are new to the NodeJS ecosystem, I will recommend you to start with the post on creating a Node server.

1 – What is ExpressJS?

ExpressJS is a layer built on top of NodeJS. The job of ExpressJS is to make it easy for developers to build complex applications using NodeJS.

Basically, we can use ExpressJS to build single-page, multi-page and hybrid web and mobile applications.

The difference between NodeJS and Express is that NodeJS is a platform for building applications for server-side using JavaScript V8 engine. Express is basically an abstraction over NodeJS that hides the complexity of NodeJS.

Writing server side logic is complex with vanilla JS. For example, handling NodeJS routes without Express is cumbersome. Typically, developers want to focus on business logic. They don’t want to deal with a bunch of boilerplate code to handle basic features such as reading incoming requests.

This is where Express framework comes handy. As a framework, it provides a bunch of helper functions, tools and rules that help us build the application more efficiently. In other words, Express makes the developer life easier. Also, it shortens the development time of new applications.

2 – Installation of ExpressJS

Needless to say, we need to have NodeJS to work with ExpressJS. We can install NodeJS from the official site.

Next, we create a brand new project for our Express demo application.

See below commands:

$ mkdir node-express-demo
$ cd node-express-demo
$ npm init -y
$ npm install --save express

Basically, we create a project directory, initialize a new Node project and install Express. After installation, the package.json file for the project will get updated.

{
  "name": "express-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  }
}

As the time of writing this, we are using Express version 4.

3 – Getting Started with ExpressJS – First Application

Now that our project is ready, we can proceed with our first application.

To do so, create a file app.js within the project directory.

const http = require('http');

const express = require('express');

const app = express();

const server = http.createServer(app);

server.listen(3000);

We first import the core NodeJS module http using the require statement. Then, we import the express function. Basically, the express library exports a function and we store it in the constant express.

On calling the express() function, we get the application context. We store it in constant app.

We can start the application server by calling http.createServer(). This function also takes the application instance as input and returns a server instance. We can simply invoke the listen() method with the appropriate port number to start the application server.

This is basically our first application. We can start the application using the command node app.js. Technically, this application does not do much as there are no request handlers. However, it is still an ExpressJS application.

Incidentally, we can shorten the application code even further by directly using app.listen() instead of server.listen().

See below:

const express = require('express');

const app = express();

app.listen(3000)

4 – Using ExpressJS Middleware

To do something useful with our application, we can start by using middleware. Technically, ExpressJS is all about using middleware.

A middleware is nothing but a function that executes during the request response flow. Think of middleware as a funnel head. The request passes through this funnel before reaching the destination.

We can add middleware functions to our ExpressJS application by using the special function app.use().

See below:

const express = require('express');

const app = express();
app.use((req, res, next) => {
    console.log('In the middleware!')
    next();
})

app.use((req, res, next) => {
    console.log('In another middleware!')
    res.send('<h1>Hello from Express</h1>')
})

app.listen(3000)

Basically, the app.use() takes a function that has 3 parameters – request object, response object and a special function next().

Here, next() is a function we have to call in order to allow the request to proceed further to the next middleware. This is why we call next() after the console.log() statement in the first middleware function.

However, in the second middleware, we don’t call next() again. This is because we are sending a response back to the client.

Conclusion

In this post, we have seen how to get started with ExpressJS. We understood the process of creating a new Express application. Also, we looked at ExpressJS middleware to handle incoming request and response object.

Want to create multiple routes in ExpressJS? Check out this post on ExpressJS Route Handlers.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

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