ExpressJS Tutorial: The Ultimate Guide (2023)

This is the most comprehensive tutorial to the ExpressJS framework online.

In this expressjs tutorial, you will learn how to use the most popular Node.js framework, Expressjs. You will learn ExpressJS from scratch to an advanced level.

Also, how to install Node.js and set up the Expressjs server in your local machine.

ExpressJS Tutorial: The Ultimate Guide (2023)

Chapter 1: ExpressJS Complete Overview

In this Expressjs tutorial, you will learn how to use the most popular Node.js framework, ExpressJS.

This ExpressJS tutorial will teach you Expressjs from scratch to an advanced level. You will also learn how to install Node.js and set up the Expressjs server in your local machine.

Also, you will learn how to connect a MongoDB database with Expressjs and build and deploy a full-blown application to the server in this Expressjs tutorial.

Let’s dive right in:

Before we dive in, if you’re a backend developer or looking at delving into this career path, join other developers to receive daily articles on backend development that will boost your productivity.

Prerequisites

Before continuing with this guide, you will need to understand what server-side web programming, frameworks, general Knowledge of JavaScript and NodeJS are, which will aid your understanding of the ExpressJS framework.

To learn ExpressJS in detail, there is no better course to recommend personally than Just Express (with a bunch of node and http). In detail. Check it out now for a discount.

What is Expressjs Framework?

ExpressJS framework is a fast, un-opinionated, and minimalist web framework that provides a robust set of features for web application development in the NodeJS/JavaScript ecosystem. 

ExpressJS is a Sinatra-like framework that starts by creating simple features while adding and developing more robust components and features depending on your application use cases.

The ExpressJS API deals with the web application, HTTP requests and responses, routing, and middlewares.

ExpressJS comes inbuilt with great features and plugins that make it different from other Node.js frameworks as a web framework.

Let’s dive into them:

Features of ExpressJS

ExpressJS has many great features that span across order frameworks depending on ExpressJS.

We will discuss a few of the features in a minute:

Powerful Routing System

ExpressJS offers a powerful, robust, and highly advanced routing system that assists your application responds to a client request via a particular endpoint.

ExpressJS allows your long and bloated routes to be split into different route files and managed independently through ExpressJS Router, a complete middleware, and routing system.

Middleware

Middlewares do not have a specific definition. It can be anything depending on the use case and functionalities.

Middlewares execute before an HTTP request reaches the route handler or before a client received a response.

ExpressJS is made up of middleware series; in fact, an expressjs application is essentially a series of middleware function calls. It also made it very easy to create and use middleware.

Templating

The templating engine ExpressJS provides allows developers to build dynamic content on the web pages by building HTML pages on the server-side.

Debugging 

ExpressJS provides an easy debugging mechanism that makes debugging ExpressJS applications easier by pinpointing the exact part of the web page with a bug.

Why you should learn ExpressJS

This question always pops in when considering learning a new technology from a sea of frameworks available, and it’s the right question to ask.

Here are my personal opinions on why you should consider learning ExpressJS 5:

Most importantly, there are many reasons to learn a particular technology different from what is listed below, and you should do even more research before concluding.

Popular Framework

Firstly, ExpressJS is the backbone of many great and popular frameworks in the Node.JS ecosystem. A knowledge of it is like having at least a good grasp of other popular frameworks.

You can get a list of other frameworks using ExpressJS under the hood. 

With a good knowledge of ExpressJS, you can easily take on a project in any Node.js framework and deliver on it successfully with little to no help.

Easy learning curve

Next, ExpressJS does not overwhelm you with many unnecessary or unwanted web application features.

Instead, it provides a thin layer of web application features while allowing you to be flexible with the Node.js features you know and love.

With ExpressJS, spinning up a web server is in a matter of minutes and also very lightweight since it comes with only the subset of features needed to run a basic server.

Easy to manage middlewares

ExpressJS provides an easy-to-manage way of creating and using middlewares which can be used to make decisions at different stages ( authentication, authorization, logging, etc.) before giving the correctness of response to the HTTP request made by the client.

ExpressJS is Fast

Lastly, ExpressJS is lightweight, fast, and scalable, and it’s highly recommended for high-performance-oriented applications.

ExpressJS Framework vs. Other Frameworks

Comparing the ExpressJS framework with other Node.js frameworks in the ecosystem is like comparing a father to a son.

ExpressJS is unopinionated and highly performant.

You can have a good grasp and comparisons with other frameworks from Express, Koa, Meteor, Sails.js: Four Frameworks Of The Apocalypse by Chouxian Yang.

Now, you have completed the overview of ExpressJS, let’s delve into the framework properly.

Chapter 2: ExpressJS The Framework

In this chapter, we will discuss a little in-depth about the ExpressJS 5 framework.

We will discuss the structure of the framework, how it interacts with other components of the framework and how to understand the framework from a beginner’s perspective.

Unlike other frameworks like Laravel, ExpressJS 5 doesn’t apply any prevalent design patterns such as MVC, MVP, MVVM, or whatever is trending out of the box.

Still, it is built with simplicity, easy to use in mind.

With ExpressJS 5, you can customize and roll out your own application structure without having to follow a particular pattern or folder structure.

Though there are Express Generators, ExpressJS allows you to take control and build out your structure exactly how your application is designed.

We have written a couple of contents on how to structure your ExpressJS applications based on different application features and preferences.

  1. Node Hero – Node.js Project Structure Tutorial

  2. Bulletproof node.js project architecture

One thing to note is that ExpressJS is a web framework that is build to handle web HTTP requests and send out responses to the client who made the request easily.

Let’s talk about Request and Response and how it’s done in ExpressJS:

Request and Response analogy

When a website user sends a request either by typing a website URL in the browser’s address bar and pressing Go, the user sends an HTTP(s) request to a web server hosted somewhere, maybe written with ExpressJS.

Read more on it here.

When this request gets to our expressjs server, we want to handle the user’s request and return a response to the user (the response could be sending back a dynamic HTML page, or returning JSON data, etc.)

We will create our server and listen to incoming requests from a specific URL and port number with ExpressJS.


const express = require('express')
const app = express()
const port = 3000

app.get('/', (request, response) => {
  response.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

As with the code above,

We require expressJS package using require('express') after installed using:

npm install express --save

We executed the expressJS package and save the returned value as app with:

const app = express()

Next, we defined our port number.

Next, we use the get function from the app instance, which takes in a URL and a Callback function.

The callback function expects returns the request and response params which is very useful and can be used to retrieve the properties of the user’s request, and also sends back data to the user as response using send in this case.

Lastly, we listen to requests coming into our expressjs server from the port number we defined.

If we have noticed from our discussions so far, ExpressJS as a framework is made up of two most important concepts, viz:

Routing System

Routing is the single most important concept in the ExpressJS framework because this is how requests come into your application in the first place.

ExpressJS has created and managed different express js routers compared to when working with Node.js.

app.get('/about', (request, response) => {
  response.send('This is about us page')
})

In the code snippet above, we have just created a simple express js route for the /about page, when a user visits https://yourdomain.com/about, it will display the information above to the user.

The above code snippet shows a typical example of a GET request. Expressjs allows every other type of available such as POST, PUT, DELETE, etc., making up the REST architectural style.

Middlewares

Middlewares are like a middleman between a request and the response in a REQUEST → RESPONSE cycle.

When a web server receives a request, ExpressJS gives you a Request object used to retrieve numerous information about the request and the client, and also, this request expects a response to come back.

ExpressJS also gives you a Response object that can be modified to contain information you want to send back to the client.

Middlewares in ExpressJS are just functions that can modify these Request and Response objects either to retrieve or store relevant information.

An example of a simple express js middleware could be to log the current date and time on every URL the user visits on our website.

app.use(function(req, res, next) => {
  console.log('The time is: '+ Date.now())
  next();
})

Did you notice how we used app.use() to register the express js middleware? It can be written differently, and different middlewares can be created in Expressjs to perform various tasks.

You can read a simpler explanation of middleware.

Now that we understand the inner workings of the Express framework, let’s start building our first project following the structure:

Chapter 3: Building a Simple Todo API with ExpressJS

So far, we have explored the internal workings of ExpressJS, and we have foster more understanding of the framework.

In this ExpressJS tutorial, we are going to build on our knowledge to develop a real-world application using ExpressJS 5:

We can use ExpressJS to develop the Restful API ( Microservice ) of your backend application, and the frontend can be developed with either Vue, React, or Angular.

We can also use ExpressJS to develop a monolithic application where the frontend and the backend (logic) are all in the same codebase.

If you’re starting, you need to have Node.js and NPM installed on your local machine.

To get started, download and install the latest version of Node.js, which will come with NPM.

This Expressjs tutorial will be building both the API-only backend and the monolithic application that includes both the frontend and the backend of a Todo application.

Let’s dive right in:

Building a Simple Todo API with ExpressJS 5

Setting up Express 5

As of the time of writing, Express 5 is still in the alpha release stage and comes with lots of bug fixes, breaking changes, and improvements.

Our application will be based on Express 5, so you can review the changes in my Express 5: What’s new.

You can review and install the previous version from here, which was a major release of Expressjs as a framework.

To install Expressjs 5:

Create a folder in your machine by running the following command.

mkdir todo-express-api
cd todo-express-api

Next, install Express 5 with this command:

npm install [email protected] --save

Note that Express 5 is still in the alpha stage when writing, and the command can change when released.

Next, create a server.js file in the root directory to contain all your server codes.

touch server.js

…and paste in the following codes.


const express = require('express')
const app = express()
const port = 3000

app.get('/', (request, response) => {
  response.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

You should already be familiar with the script above, but we will extend the script to contain more endpoints (URL) below.

const express = require("express");
const app = express();
const port = 3000;

// Data Source, could be replaced with a real database
const todos = [
  {
    title: "Todo 1",
    desc: "This is my first Todo",
    completed: true,
  },

  {
    title: "Todo 2",
    desc: "This is my second Todo",
    completed: true,
  },

  {
    title: "Todo 3",
    desc: "This is my third Todo",
    completed: true,
  },

  {
    title: "Todo 4",
    desc: "This is my fourth Todo",
    completed: true,
  },

  {
    title: "Todo 5",
    desc: "This is my fifth Todo",
    completed: true,
  },
];
// Data source ends here

// Endpoint starts here
app.get("/", (request, response) => {
  response.status(200).json(todos);
});

app.get("/todos", (request, response) => {
  response.status(200).json(todos);
});

app.get("/todos/:id", (request, response) => {
  response
    .status(200)
    .json({ data: todos.find((todo) => todo.id === request.params.id) });
});

app.post("/todos", (request, response) => {
  todos.push(request.body);
  response.status(201).json({ msg: "Todo created successfully" });
});

app.put("/todos/:id", (request, response) => {
  const todo = todos.find((todo) => todo.id === request.params.id);
  if (todo) {
    const { title, desc, completed } = request.body;
    todo.title = title;
    todo.desc = desc;
    todo.completed = completed;
    response.status(200).json({ msg: "Todo updated sucessfully" });
    return;
  }
  response.status(404).json({ msg: "Todo not found" });
});

app.delete("/todos/:id", (request, response) => {
  const todoIndex = todos.findIndex((todo) => (todo.id = request.params.id));
  if (todoIndex) {
    todos.splice(todoIndex, 1);
    response.status(200).json({ msg: "Todo deleted successfully" });
  }
  response.status(404).json({ msg: "Todo not found" });
});
// Endppoint ends here

// App listens to incoming requests here
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Above, we have created different endpoints to retrieve all, retrieve single, create, update, and delete todos, which are basically called CRUD (Create, Read, Update, Delete).

Testing with Postman

We will test our newly developed REST API with Postman and be sure we have the right data.

Run the following command:

node server.js

You can read more about Postman and install it on your local machine if you don’t already have it.

todos_express.png

Suppose you have a response as above congrats. You can test out the remaining endpoints.

Next, we will build a real-world application with Express JS:

Build a real-world ticketing system

To show the capabilities of the Expressjs Node.js framework and how we can combine it with the frontend, this ExpressJS tutorial will lead you through building a Ticketing System App. 

This app will create events, generate tickets for the event, allow users to view the event and the tickets, and make purchases and redeem the event tickets.

Once you finish the ExpressJS tutorial, you will have a functioning Ticketing application like the following deployed to Heroku:

Go from a total beginner in backend development with ExpressJS to a PRO by learning advanced topics and building real-world projects above this PDF… Join the waiting list.

Chapter 4: Advanced ExpressJS Guide

Now, deploying your ExpressJS project can be tedious, especially if it is your first time. Still, in this Expressjs tutorial, we will deploy your first ExpressJS project efficiently and successfully.

Deploying to Heroku

To deploy ExpressJS to Heroku is a rather fun and straightforward process. It comes with great benefits and supports auto-deployment and auto testing.

That’s why I have prepared a work-through of an article on deploying to Heroku.

The article is written with Laravel in mind but can be tweak to deploy ExpressJS too.

Deploying ExpressJS to Shared Hosting

Deploying ExpressJS to shared hosting might be the cheapest option available right now for testing purposes. That’s why I have prepared a work-through article on deploying Node.js to Shared Hosting.

Conclusion: ExpressJS

In this expressjs tutorial, we have looked at the nitty-gritty of ExpressJS and have created a real-world application to demonstrate the knowledge we have gained so far practically.

We have even looked at how to deploy the application to different hosting platforms using the knowledge from this expressjs tutorial.

To learn ExpressJS in detail, there is no better course to recommend personally than Just Express (with a bunch of node and http). In detail. Check it out now for a discount.

Now, it’s your turn to practice everything you have learned from this ExpressJS tutorial until you master them by building real-world projects.

Let me know what you will be making. If none, comment “ExpressJS is Great,” we may connect from there.

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board

Backend Tips, Every week