HVRDHVRD
ExpressJS

Introduction

Comprehensive documentation covering Express.js fundamentals, architecture, middleware, routing, and practical examples.

What is Express.js?

Express.js is a minimal, fast, and flexible web framework for Node.js. It simplifies building web applications and APIs by providing an easy-to-use abstraction over Node's built-in HTTP module.

Express helps developers by:

  • Managing routing
  • Handling middleware
  • Simplifying request and response handling
  • Providing tools to build RESTful APIs

It’s the most popular framework in the Node.js ecosystem due to its simplicity, performance, and robust community.


Why Use Express.js Instead of Native HTTP Module?

Using the built-in Node.js http module for every project results in a lot of boilerplate code:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/api' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello World' }));
    return;
  }

  res.writeHead(404);
  res.end('Not Found');
});

server.listen(3000);

Express abstracts this into a cleaner, more maintainable form:

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

app.get('/api', (req, res) => {
  res.json({ message: 'Hello World' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Express handles routing, status codes, headers, and body serialization automatically.


Setting Up an Express Project

Step 1: Initialize the Project

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

Step 2: Create the Server

Create index.js:

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

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

// Sample route
app.get('/', (req, res) => {
  res.send('Welcome to Express.js!');
});

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

Run the server:

node index.js

Visit http://localhost:3000/ and see "Welcome to Express.js!" in the browser.


Middleware in Express.js

What Is Middleware?

Middleware functions are functions that have access to the request (req), response (res), and next middleware function (next) in the request-response cycle.

They can:

  • Modify req and res objects
  • Perform operations (e.g., logging)
  • End the request-response cycle or pass control to the next middleware

Example: Logging Middleware

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Proceed to next middleware/route handler
});

Built-in Middleware

Express provides built-in middleware like:

  • express.json() – Parses incoming JSON payloads
  • express.urlencoded() – Parses URL-encoded bodies

Example:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

Routing in Express.js

Routes define how the application responds to client requests.

Basic Routing Example

app.get('/api/todos', (req, res) => {
  res.json([{ id: 1, task: 'Learn Express.js' }]);
});

app.post('/api/todos', (req, res) => {
  const { task } = req.body;
  res.status(201).json({ id: Date.now(), task });
});

Route Parameters

app.get('/api/todos/:id', (req, res) => {
  const { id } = req.params;
  res.json({ id, task: 'Example Todo' });
});

Query Parameters

app.get('/search', (req, res) => {
  const { keyword } = req.query;
  res.send(`Searching for: ${keyword}`);
});

Handling Errors

Express allows centralized error handling using error-handling middleware:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

Trigger an error example:

app.get('/error', (req, res) => {
  throw new Error('This is a forced error');
});

Serving Static Files

Express provides express.static() to serve files from a directory.

app.use(express.static('public'));

Example folder structure:

express-app/
├── public/
│   └── index.html
├── index.js

Requesting http://localhost:3000/index.html serves the file automatically.


Example: In-Memory Todo API

const express = require('express');
const app = express();
app.use(express.json());

let todos = [];

app.get('/todos', (req, res) => {
  res.json(todos);
});

app.post('/todos', (req, res) => {
  const { task } = req.body;
  const newTodo = { id: todos.length + 1, task };
  todos.push(newTodo);
  res.status(201).json(newTodo);
});

app.get('/todos/:id', (req, res) => {
  const { id } = req.params;
  const todo = todos.find(t => t.id === parseInt(id));
  if (todo) {
    res.json(todo);
  } else {
    res.status(404).json({ error: 'Todo not found' });
  }
});

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

Advantages of Express.js

  • Minimalist and flexible
  • Easy middleware integration
  • Extensive documentation and ecosystem
  • Large community support
  • Supports REST API development efficiently