Intro to Express.js

Himanshu MauryaHimanshu Maurya
5 min read

Express.js is a lightweight and flexible web framework for Node.js. It helps you build websites and APIs easily.

It's a key part of the MEAN (MongoDB, Express, Angular, Node.js) and MERN (MongoDB, Express, React, Node.js) stacks.

Real life analogy

Express.js is like a Restaurant Waiter

Imagine a restaurant:

  • The customer is the client/browser.

  • The kitchen is the server/database.

  • The waiter is Express.js.

How it works:

  1. Customer places an order (HTTP request)
    → I'd like a pizza.

  2. Waiter (Express.js) receives the order
    → Understands what the customer wants.

  3. Waiter passes the order to the kitchen (backend logic or database)
    → Kitchen prepares the pizza (processes data, fetches info).

  4. Waiter brings the food back to the customer (HTTP response)
    → Pizza is served to the customer (data or HTML returned).

Why important
Express.js is important because it acts like a smart and efficient waiter in a restaurant. Just like a good waiter, it helps organize incoming orders by managing routes, so each request goes to the right place. It also works as a translator between the customer (the client) and the kitchen (the server or database) using middleware, making sure the data is handled correctly along the way. By managing these tasks smoothly, Express.js makes the entire process of handling requests and sending responses fast, simple, and well-organized—allowing developers to build web applications more easily and efficiently.

Why Use Express.js?

Simple to Use : You can build powerful apps with less code and effort.

Supports Middleware : You can easily add extra features like data handling, login checks, logging, and error messages.

Handles Routes : It helps you manage different URLs and actions (like GET, POST) in your app.

Works Well with Databases : It connects easily with popular databases like MongoDB, MySQL, and PostgreSQL.

Fast and Lightweight : It’s quick and doesn’t have too many rules, and it runs on fast Node.js.

Step-by-Step: Installing Express.js

Step-1 . Install Node.js

Step-2 . Create a Project Folder

mkdir my-express-app
cd my-express-app

Step-3 . Initialize Node Project

npm init -y

Step-4 . Install Express

npm install express

Note : If you want to check version of express

npm install express

Architecture of Express.js

+-----------+         +----------------+         +-------------------+         +--------------------+
|           |         |                |         |                   |         |                    |
|  Client   +-------->+   Middleware   +-------->+   Middleware (n)  +-------->+    Controller      |
| (Request) |         | (e.g., logger) |         | (e.g., auth check)|         | (Business logic)   |
|           |         |                |         |                   |         |                    |
+-----------+         +----------------+         +-------------------+         +--------------------+
                                                                                         |
                                                                                         v
                                                                              +----------------------+
                                                                              |                      |
                                                                              |    Response Sent     |
                                                                              |      to Client       |
                                                                              |                      |
                                                                              +----------------------+

Request :

A user sends a request (like opening a webpage or submitting a form).

Middleware:

Middleware is like “meet me when you go”

Middleware are like checkpoints the request goes through.

  • Check if the user is logged in

  • Parse the body of a form

  • Log the request details

  • Handle errors

Controller :

This is where the main logic lives. The controller handles the request and sends a response.

Creating a Basic Express App

Create a App.js file and write basic express app

// app.js
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware to parse JSON
app.use(express.json());

// Home route
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// Example POST route
app.post('/data', (req, res) => {
  const data = req.body;
  res.json({ message: 'Data received', data });
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Run the server:

node app.js

Standard way of writing express

Project Structure

project/
│
├── app.js
├── routes/
│   └── index.js
├── controllers/
│   └── mainController.js

App.js File :

const express = require('express');
const app = express();
const PORT = 3000;

// Middleware
app.use(express.json());

// Routes
const indexRoutes = require('./routes/index');
app.use('/', indexRoutes);

// Start Server
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

Routes file :

routes/index.js

const express = require('express');
const router = express.Router();
const { home } = require('../controllers/mainController');

// Define routes
router.get('/', home);

module.exports = router;

Controller file :

controllers/mainController.js

exports.home = (req, res) => {
  res.send('Welcome to the modular Express server!');
};

Run the server:

node app.js

Visit:

http://localhost:3000

Compare raw Node.js to Express.js

Comparing raw Node.js to Express.js is a great way to understand how Express simplifies backend development.

1. Raw Node.js Version

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  const parsedUrl = url.parse(req.url, true);
  const path = parsedUrl.pathname;

  res.setHeader('Content-Type', 'text/plain');

  if (req.method === 'GET') {
    if (path === '/') {
      res.writeHead(200);
      res.end('Welcome to the homepage!');
    } else if (path === '/about') {
      res.writeHead(200);
      res.end('This is the about page.');
    } else {
      res.writeHead(404);
      res.end('404 Not Found');
    }
  } else {
    res.writeHead(405);
    res.end('Method Not Allowed');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

2. Express.js Version

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to the homepage!');
});

app.get('/about', (req, res) => {
  res.send('This is the about page.');
});

app.use((req, res) => {
  res.status(404).send('404 Not Found');
});

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
| Feature                | Raw Node.js                             | Express.js                                      |
|------------------------|-----------------------------------------|-------------------------------------------------|
|   Routing              | Manual path and method checks           | Built-in routing (`app.get`, etc.)              |
|   Parsing URL          | Needs `url.parse()` manually            | Done automatically                              |
|   Request Methods      | Must manually check `req.method`        | Handled by `app.get`, `app.post`, etc.          |
| Headers & Status Codes | Manual with `res.writeHead()`           | Simplified with `res.send()`, `res.status()`    |
|   404 Handling         | Custom logic needed                     | Use `app.use()` for fallback                    |

Conclusion

Express.js makes it much easier to build web apps using Node.js. Instead of writing a lot of repetitive code, Express gives you simple tools to handle things like routing, requests, and responses. This helps you focus on building the actual features of your app. Whether you want to make a small API or a full web app, Express is flexible and powerful enough to handle both. If you're learning backend development with Node.js, Express is a great place to start.


I’m truly thankful for your time and effort in reading this.

20
Subscribe to my newsletter

Read articles from Himanshu Maurya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshu Maurya
Himanshu Maurya

Hi, Thank-you for stopping by and having a look at my profile. Hi! I’m a web developer who loves working with the MERN stack . I enjoy making interactive and user-friendly websites and webapps. I’m great at taking ideas and bringing them to life through coding!