- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js Express Framework
Express is a fast, unopinionated, and minimal web framework for Node.js. While Node.js provides a built-in http module, using it to build complex applications often leads to repetitive "boilerplate" code. Express acts as a thin layer on top of Node.js, providing a more intuitive syntax to handle routes, requests, and responses. Whether you are building a simple landing page or a massive RESTful API, Express is the industry standard for server-side JavaScript development.
Key Features of Express Framework
- Simplified Routing: Easily map URLs to specific functions using HTTP methods like GET, POST, PUT, and DELETE.
- Middleware Support: Plug in third-party or custom functions to handle tasks like authentication, logging, and data parsing before the request reaches your logic.
- High Performance: Because it is a "thin" layer, it maintains the raw speed of Node.js while providing much-needed utility.
- Templating Engine Integration: Seamlessly connect with engines like EJS, Pug, or Handlebars to render dynamic HTML on the server.
dotenv to manage these safely.
Installing Express
Before installing Express, you need to initialize your project folder to create a package.json file, which tracks your dependencies.
Initialize a Node.js project:
npm init -y
Install Express:
npm install express
node -v in your terminal.
Creating a Basic Express Server
To get started, we need to import the library, instantiate an app, and tell it to listen for incoming traffic on a specific port.
Code Example
Create server.js:
const express = require('express');
const app = express();
// Define a simple route
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Run the server:
node server.js
Visit http://localhost:3000 in your browser to see the message.
nodemon during development. It automatically restarts your server every time you save a file. Install it via npm install -g nodemon and run your app with nodemon server.js.
Adding Middleware
Middleware functions are the backbone of Express. Think of them as a "pipeline" that the request travels through. Each function has access to the Request (req) and Response (res) objects, and can either end the cycle or pass control to the next function using next().
// Middleware to log the time of each request
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} request to ${req.url}`);
next(); // Don't forget this, or the request will hang!
});
// Built-in middleware to parse JSON bodies (essential for APIs)
app.use(express.json());
app.get('/', (req, res) => {
res.send('Middleware is active and logging requests.');
});
next() inside a custom middleware. If you don't call it, the browser will just spin forever because Express doesn't know to move on to the next route handler.
Routing in Express
Routing determines how an application responds to a client request to a particular endpoint. In real-world scenarios, you'll use different HTTP methods to perform CRUD (Create, Read, Update, Delete) operations.
// GET request - Fetching data
app.get('/about', (req, res) => {
res.send('About Page: This is where we describe our company.');
});
// POST request - Sending data (e.g., submitting a form)
app.post('/api/users', (req, res) => {
// In a real app, you would save req.body to a database
res.status(201).json({ message: 'User created successfully!' });
});
// Dynamic Routing - Using parameters
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User Profile for ID: ${userId}`);
});
/:id before a specific route like /about, Express might capture the wrong request.
Summary
Express is a powerful framework that simplifies web application development in Node.js by removing the complexity of the native HTTP module. By mastering routing, middleware, and request handling, you can build everything from small utility scripts to enterprise-grade backends. Its massive ecosystem and active community make it one of the safest and most efficient choices for modern web developers.