ExpressJS Tutorial

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It is an open source framework developed and maintained by the Node.js foundation.

What is Express.js?

Express provides a minimal interface to build our applications. It provides us the tools that are required to build our app. It is flexible as there are numerous modules available on npm, which can be directly plugged into Express.

Why Learn Express.js?

Express Framework unlike its competitors like Rails and Django, which have an opinionated way of building applications, has no “best way” to do something. It is very flexible and pluggable. It uses Pug, a template language for writing HTML templates.

How to Install Express.js?

Express requires Node.JS and NPM to be installed first. Different operating systems required different steps to install Node.js, please follow the provided methods according to your installed operating system.

Once node is installed, you can run the following npm command inside the Node project where package.json is residing.

npm install save express

To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command −

npm install g nodemon

Example of Express.js Application

Once express set up is complete, we can start developing our first app using Express. Create a new file called index.js and type the following in it.

var express = require(‘express’); var app = express(); app.get(‘/’, function(req, res){ res.send(“Hello world!”); }); app.listen(3000);

Save the file, go to your terminal and type the following.

nodemon index.js

This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot.

Hello world

Prerequisites to Learn Express.js

Before proceeding with this tutorial, you should have a basic understanding of JavaScript. As we are going to develop web-based applications using Express.js and Node.js, it will be good if you have some understanding of other web technologies such as HTMLCSSAJAX, etc.

Getting Started with Express.js

This tutorial is designed for software programmers who want to learn the Express.js and its architectural concepts from basics to advanced. This tutorial will give you enough understanding on all the necessary components of Express.js with suitable examples.

Considering NodeJS as base environement, before going deep into expressjs you should familiar with fundamentals of nodejs like environment setup, REPL terminal, NPM, Callbacks, Events, Objects, etc.

ExpressJS – Overview

ExpressJS is a web application framework that provides you with a simple API to build websites, web apps and back ends. With ExpressJS, you need not worry about low level protocols, processes, etc.

What is Express?

Express provides a minimal interface to build our applications. It provides us the tools that are required to build our app. It is flexible as there are numerous modules available on npm, which can be directly plugged into Express.

Express was developed by TJ Holowaychuk and is maintained by the Node,js foundation and numerous open source contributors.

Why Express?

Unlike its competitors like Rails and Django, which have an opinionated way of building applications, Express has no “best way” to do something. It is very flexible and pluggable.

Features of ExpressJS

Following are the salient features of ExpressJS making it a default choice among web application developers.

  • Minimalistic Design− ExpressJS is an unopinionated. ExpressJS framework is highly flexible with a simple, minimalistic design principles. We can quickly setup server, define routes and start handling http requests with very few lines of code.

  • Middleware/Routing− ExpressJS provides clear options for Routes with support for all kind of HTTP methods like POST, GET, PUT etc.

  • Flexibility− There is no prerequisites or any format to follow in order to use ExpressJS. If we know NodeJS, we can write code as per our preference.

  • Templating− ExpressJS supports various templating engines like PUG, Jade or EJS to generate HTML content on the fly.

  • Static File Serve− ExpressJS supports static files like images/css/javascript from a folder seemlessly.

  • NodeJS Based− Core functionalities of asynchronous programming and event driven programming features of NodeJS can be integrated with ExpressJS easily.

Applications of ExpressJS

Following are the salient features of ExpressJS making it a default choice among web application developers.

  • Support RESTful APIs− REST Architecture is very powerful style to enable communication of front-end with backend. ExpressJS supports RESTful APIs by design.

  • Support for Real Time Applications− Event Driven Programming helps to create chat, parallel collaborative editing tools etc. ExpressJS integrates with Node and supports Event Driven Programming seemlessly.

  • Support for Single Page Applications(SPA)− SPA and RESTFul APIs allows Express Based application to update content dynamically enriching user experience.

ExpressJS vs Django vs Ruby on Rails

Sr.No.FeatureExpressJSDjangoRuby on Rails
1LanguageJavaScriptPythonRuby
2FlexibilityHighly flexible. Unopinionated by design.Moderate. Opinionated by design.Low. Highly opinionated.
3PerformanceHighly performantModerateModerate
4Support for MiddlewareVery HighLimitedLimited5ApplicationsREST APIs, Web AppsFull Stack DevelopmentFull Stack Development

Pug

Pug (earlier known as Jade) is a terse language for writing HTML templates. It −

    • Produces HTML
    • Supports dynamic code
  • Supports reusability (DRY)

It is one of the most popular template language used with Express.

MongoDB and Mongoose

MongoDB is an open-source, document database designed for ease of development and scaling. This database is also used to store data.

Mongoose is a client API for node.js which makes it easy to access our database from our Express application.

ExpressJS – Environment Setup

ExpressJS is a NodeJS based application framework. In case to start with Express, we need to set up environment for Node.js, this section will guide you. Node.js can be installed on different OS platforms such as Windows, Linux, Mac OS X, etc. You need the following tools on your computer −

  • The Node.js binary installer

  • Node Package Manager (NPM)

  • IDE or Text Editor

Node Installation Steps

Binaries for various OS platforms are available on the downloads page of the official website of Node.js. Visit https://nodejs.org/en/downloadto get the list.

Official Website

This page shows command line as well as installers as well as ZIP archives for Windows, macOS installer as well as tar archives and binaries for Linux OS on x64 and ARM architecture are available.

Installation on Windows

Assuming that you are working with Windows 10/Windows 11 powered computer, download the 64-bit installer for Windows: https://nodejs.org/dist/v22.13.0/node-v22.13.0-x64.msi, and start the installation by double-clicking the downloaded file.

Nodejs Setup Wizard

The installation takes you through a few steps of the installation wizard. It also adds the installation directory of Node.js executable to the system path.

To verify if Node.js has been successfully installed, open the command prompt and type node -v. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine, as shown below.

Microsoft Windows [Version 10.0.26100.2894] (c) Microsoft Corporation. All rights reserved. C:\Users\Tutorialspoint>node v v22.13.0 C:\Users\Tutorialspoint>

Installation on Ubuntu Linux

First, download the tar file corresponding to Linux binary (https://nodejs.org/dist/v22.13.0/node-v22.13.0-linux-x64.tar.xz) and then, extract the binary using the tar command −

tar xf nodev22.13.0linuxx64.tar.gz

Move the extracted files to the installation directory /usr/local/node-v22.13.0.

sudo mv node<version> /usr/local/nodev22.13.0

Create a symlink to the executable in /usr/bin directory.

sudo ln s /usr/local/nodev22.13.0/bin/node /usr/bin/node

You can now verify the correct installation with the following command −

node v

Using Ubuntu package manager

Refresh your local package index first by the following command −

sudo apt update

Then install Node.js −

sudo apt install nodejs

As in above case, verify the installation

node v

NPM (Node Package Manager) is included in Node.js binaries from its official website since Node version 0.6.0., so you are not required to install it separately.

You can use any text editor available in your OS (notepad in Windows, vi or nano in Ubuntu) to key-in and save the Node.js script. However, it is recommended that you use a suitable IDE for the purpose as it has several features such as syntax highlighting etc. VS Code is a popular source-code editor, which has out of the box support for JavaScript (and hence Node.js), which is highly recommended.

You can verify the version of NPM using following command

npm v
10.9.2

Postman Installation Steps

Postman is a API, Application Programming Interface, Testing tool. We’ll use it to test our REST APIs developed during Express JS tutorial. Please follow the Postman Environment Setup.

ExpressJS – Installation

In this chapter, we will learn how to start developing and using the Express Framework. To start with, you should have the Node and the npm (node package manager) installed. If you dont already have these, go to the ExpressJS Environment Setup chapter to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal.

node v v22.13.0 npm v 10.9.2

Now that we have Node and npm set up, let us understand what npm is and how to use it.

Node Package Manager(npm)

npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS.

How to use npm?

There are two ways to install a package using npm: globally and locally.

  • Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code.

npm install g <packagename>
  • Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag.

npm install <packagename>

Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project.

Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it −

E:\Dev>mkdir helloworld E:\Dev>cd helloworld E:\Dev\helloworld>

Step 2 − Now to create the package.json file using npm, use the following code.

E:\Dev\helloworld>npm init

It will ask you for the following information.

E:\Dev\helloworld>npm init

Just keep pressing enter, and enter your name at the author name field.

E:\Dev\helloworld>npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help init` for definitive documentation on these fields and exactly what they do. Use `npm install ` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (helloworld) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: ‘MAHESH PARASHAR’ license: (ISC) About to write to E:\Dev\helloworld\package.json: { “name”: “hello-world”, “version”: “1.0.0”, “main”: “index.js”, “scripts”: { “test”: “echo \”Error: no test specified\” && exit 1″ }, “author”: “‘MAHESH PARASHAR'”, “license”: “ISC”, “description”: “” } Is this OK? (yes) npm notice npm notice New major version of npm available! 10.9.2 > 11.0.0 npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.0.0 npm notice To update run: npm install g npm@11.0.0 npm notice E:\Dev\helloworld>

Step 3 − Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command −

E:\Dev\helloworld>npm install save express added 69 packages, and audited 70 packages in 4s 14 packages are looking for funding run `npm fund` for details found 0 vulnerabilities

Tip − The —save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us.

This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command −

E:\Dev\helloworld>npm install g nodemon added 29 packages in 2s 4 packages are looking for funding run `npm fund` for details

You can now start working on Express.