Agentic hosting is here. Connect to our MCP now ->

Blog

What is Express.js? Everything you should know

Express.js's shallow learning curve makes it very simple and easy to get started with.

·by Solomon Eseme

Express.js is the most popular backend framework for Node.js, and it is an extensive part of the JavaScript ecosystem.

It is designed to build single-page, multi-page, and hybrid web applications, it has also become the standard for developing backend applications with Node.js, and it is the backend part of something known as the MEVN stack.

The MEVN is a free and open-source JavaScript software stack for building dynamic websites and web applications that has the following components:

  1. MongoDB: MongoDB is the standard NoSQL database
  2. Express.js: The default web applications framework for building web apps
  3. Vue.js: The JavaScript progressive framework used for building front-end web applications
  4. Node.js: JavaScript runtime used for scalable server-side and networking applications.

This guide will explore the Express.js framework's key features and how to build your first application.

What is Express.js?

Express.js, sometimes also referred to as "Express," is a minimalist, fast, and Sinatra-like Node.js backend framework that provides robust features and tools for developing scalable backend applications. It gives you the routing system and simplified features to extend the framework by developing more powerful components and parts depending on your application use cases.

Express.js official logo
Express.js official logo

The framework provides a set of tools for web applications, HTTP requests and responses, routing, and middleware for building and deploying large-scale, enterprise-ready applications.

You install it, and the packages that extend it, with npm (Node Package Manager), the command-line tool that comes with Node.js. It also encourages developers to follow the Don't Repeat Yourself (DRY) principle.

The DRY principle is aimed at reducing the repetition of software patterns, replacing it with abstractions, or using data normalizations to avoid redundancy.

What is Express.js used for?

Express.js is used for a wide range of things in the JavaScript/Node.js ecosystem — you can develop applications, API endpoints, routing systems, and frameworks with it.

Below is a list of just a few of the types of applications you can build with Express.js.

Single-page applications

Single-Page Applications (SPAs) are the modern approach of application development in which the entire application is routed into a single index page. Express.js is an excellent framework for building an API that connects these SPA applications and consistently serves data. Some examples of Single Page Applications are Gmail, Google Maps, Airbnb, Netflix, Pinterest, Paypal, and many more. Companies are using SPAs to build a fluid, scalable experience.

Real-time collaboration tools

Collaboration tools are here to ease the way businesses work and collaborate daily, and with Express.js, you can develop collaborative and real-time networking applications with ease.

Also, the framework is used to develop real-time applications such as chat and dashboard applications, where it becomes straightforward to integrate WebSocket into the framework.

Express.js handles the routing and middleware part of the process, allowing developers to concentrate on the vital business logic of these real-time features when developing live collaborative tools.

Streaming applications

Real-time streaming applications like Netflix are complex and have many layers of data streams. To develop such an app, you need a solid framework to handle asynchronous data streams efficiently.

It's an ideal framework for building and deploying enterprise-ready and scalable streaming applications.

Fintech applications

Fintech is a computer program and other technology used to support or enable banking and financial services. Fintech apps often need fast, reliable APIs that handle many requests at once, and Express.js is a common choice for building their backends.

If you're thinking of building a fintech application with high users and transaction volume, then you'll be joining companies such as PayPal and Capital One in developing and deploying your application using Express.js.

Why you should use Express.js

There are several reasons why you should consider using Express.js for your next project, from faster I/O for faster requests and responses to its single-thread system and asynchronous processes. It also works well with the MVC pattern to simplify data manipulations and routing systems, although Express doesn't force any particular structure on your app.

Let's take a closer look at some of the main reasons you should consider using Express.js.

Flexible and speedy

Express.js is very easy-to-use, flexible, and fast. A minimalistic framework, it offers rapid application development and eases the stress of mastering the many different parts of a larger framework. It also provides rich features such as an excellent routing system, middlewares, and content negotiation right out of the box.

Part of the MEAN stack

Express.js is the framework of choice in each stack represented with the E in any stacks, such as MERN, MEAN, and so forth. It can also easily be integrated into any stack or technology to show how vital the framework is in the MEAN stack development process.

What's more, it can connect efficiently with a more robust database management system than the conventional MySQL and provides a seamless development process across each stack. This combination of features makes Express.js very popular among MEAN developers.

Scalability

Express.js has proven to be very scalable over the years because of the number of large companies using the framework on their server daily.

It handles user requests and responses efficiently and requires little to no extra configuration when developing a large-scale web application.

It has excellent modules, packages, and additional resources, which helps developers to create reliable and scalable web applications.

Built on Node.js and the Google V8 engine

Express.js runs on Node.js, which is built on Google's V8 engine, making the framework very powerful for building and deploying real-time, collaborative, and network-based applications at an enterprise level.

Google V8 engine is an open-source high-performance JavaScript and WebAssembly engine that supports high speed and scalability for complex and intense applications. When you run your backend on Node.js and V8, it's a massive performance and scalability boost to your backend application.

Community support

Since the framework is the most popular Node.js backend framework, it has the highest number of community support, resources, and packages for any development challenges, which makes the framework a popular choice amongst Node.js developers. Its open-sourced nature gives developers the opportunity to create extensible packages and resources to ease development, not just for themselves, but for all others who code with Express.js.

Powerful routing system

The framework has the most powerful and robust routing system built out of the box that assists your application in response to a client request via a particular endpoint.

With the routing system in Express.js, you can split your bloated routing system into manageable files using the framework's router instance.

The express routing system is helpful in managing your application structure, by grouping different routes into a single folder/directory.

Developers create more maintainable codes by grouping functionalities with the Express router and avoiding repetition.

Middleware

Express.js is a framework comprising a series of middleware to create a seamless development process.

Middlewares are codes that execute before an HTTP request reaches the route handler or before a client receives a response, giving the framework the ability to run a typical script before or after a client's request.

With middleware, developers can plug in scripts to intercept the flow of the application, for example, developers can use middleware to check if a user is successfully logged in or logged out.

How Express.js works

Since Express.js uses the client-server model to accept users' requests and send back responses to the client, how it works is not all that different from how other popular frameworks, such as Laravel, work themselves.

When a user sends a request from their web browser by typing in a website address, the browser sends an HTTP request to the application/server (many applications created using Express.js are hosted somewhere in the cloud).

The server will receive the request through one of its routes and process it using the controller that matches the requested route.

After processing, the server will dispatch a response back to the client using HTTP since it's a back-and-forth communication protocol.

The response returned to the client could be standard text, a dynamic HTML page that the browser will process and display a beautiful web page, or JSON data that the frontend developers will handle to display information on the web page.

Let's create a simple server to listen to incoming requests from a specific URL and port number with Express.js:

const express = require('express')
const app = express()
const port = 4000
 
app.get('/', (request, response) => {
  response.send('Testing Hello World!')
})
 
app.listen(port, () => {
  console.log(`Test app listening at http://localhost:${port}`)
})

That's a simple Express.js server that will listen to incoming requests on http://localhost:4000/ and return a text response of "Testing Hello World!".

How to create an Express.js app

Now, let's create a real-world demo application using Express 5. To get started, create a directory for your new application and install Express:

mkdir first-express-app
cd first-express-app
 
npm init -y
npm install express

Next, create an index.js file in the root directory:

touch index.js

After setting up the server as demonstrated above, we will create a Todos array that contains all our todos to be returned to the user depending on the endpoint called. Each todo has an id, and express.json() lets the app read JSON request bodies. Add the following code to the index.js file:

const express = require("express");
const app = express();
const port = 3000;
 
app.use(express.json());
 
app.listen(port, () => {
  console.log(`Test app listening at http://localhost:${port}`);
});
 
const todos = [
  {
    id: 1,
    title: "Todo 1",
    desc: "This is my first Todo",
    completed: true,
  },
  {
    id: 2,
    title: "Todo 2",
    desc: "This is my second Todo",
    completed: true,
  },
  {
    id: 3,
    title: "Todo 3",
    desc: "This is my third Todo",
    completed: true,
  },
  {
    id: 4,
    title: "Todo 4",
    desc: "This is my fourth Todo",
    completed: true,
  },
  {
    id: 5,
    title: "Todo 5",
    desc: "This is my fifth Todo",
    completed: true,
  },
];
let nextId = todos.length + 1;
// Data source ends here

Next, we will create an endpoint for retrieving all the Todos stored in our server:

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

Next, an endpoint to retrieve a single Todo based on the ID of the todo. Route parameters are strings, so we convert the ID with Number() before comparing it, and return a 404 if no todo matches:

app.get("/todos/:id", (request, response) => {
  const todo = todos.find((todo) => todo.id === Number(request.params.id));
  if (!todo) {
    return response.status(404).json({ msg: "Todo not found" });
  }
  response.status(200).json({ data: todo });
});

Now, an endpoint to store a new todo, which gives it the next ID:

app.post("/todos", (request, response) => {
  const { title, desc, completed = false } = request.body;
  const todo = { id: nextId++, title, desc, completed };
  todos.push(todo);
  response.status(201).json({ msg: "Todo created successfully", data: todo });
});

Next, an endpoint to update an existing todo with the ID:

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

Lastly, we'll create an endpoint to delete a single todo based on the ID:

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

This code snippet shows how to implement a DELETE functionality in Express.js. It collects the Todo ID through parameters, searches the array for the matching ID, and deletes it. findIndex() returns -1 when nothing matches, so that's the case we check for, rather than treating index 0 (the first todo) as missing.

Testing the Express.js app

Now it's time to test our new Express.js application!

Run the following command to start the server:

node index.js

You can test the REST API with Postman, or with curl in a second terminal. For example, create a new todo:

curl -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{"title": "Todo 6", "desc": "This is my sixth Todo"}'

The API returns the new todo with its ID:

{"msg":"Todo created successfully","data":{"id":6,"title":"Todo 6","desc":"This is my sixth Todo","completed":false}}

Then fetch it by its ID with curl http://localhost:3000/todos/6, and delete it with curl -X DELETE http://localhost:3000/todos/6. Requesting an ID that doesn't exist returns {"msg":"Todo not found"} with a 404 status.

There you have it. To learn more, we suggest you create more functionality using the approach we have discussed in the article and expand your knowledge of Express.js.

Summary

Express.js is the most popular framework in the Node.js ecosystem, and it's not hard to see why. It offers a wide range of advantages and features to benefit from.

Express.js's shallow learning curve makes it very simple and easy to get started with. It abstracts away unnecessary or unwanted web application features and provides you with a thin layer of core features that allow for flexibility.

What's more, since popular Node.js frameworks such as NestJS are built on top of Express.js, knowing Express.js gives you a decent grasp of other popular frameworks. This knowledge can help you make vital decisions on business logic-building, which framework to use aside from Express.js, and when to use default or user packages.

Deep dive into the cloud!

Deploy your application, database, or static site in minutes.