Express.js is one of the most widely used web frameworks for Node.js. It provides a minimal, fast, and flexible way to build web servers, APIs, and backend services on top of Node’s non-blocking architecture.
What Express.js Is
Express sits on top of Node’s core HTTP module and simplifies routing, middleware handling, and server creation. Instead of using external servers like Apache or NGINX, Express lets you build a custom server directly in JavaScript with full control.
Table of Contents
Core Concepts (The Important Parts)
- Routing: Defines how your app responds to client requests (e.g., GET, POST) to specific URLs (like
/or/users). - Middleware: Functions that have access to the request and response objects. They can execute code, modify the request, and call the next function in the stack. This is used for tasks like logging, authentication, and parsing data.
Basic “Project 2025
Install Node.js, create a folder, and initialize the project:
mkdir myapp
cd myapp
npm init -y
npm install express
Step 1: Createing server
Create a file named server.js and add the following code:
// server.js
import express from "express";
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
// Built-in middleware to parse JSON
app.use(express.json());
// Built-in middleware to handle urlencoded form data
app.use(express.urlencoded({ extended: true }));
//Basci Routes (Controllers)
app.get("/", (req, res) => {
res.send("Express server is working! Try visiting /api/hotels");
});
app.get("/api/hotels", (req, res) => {
res.json({
message: "Hotels fetched successfully",
data: [
{ id: 1, name: "Taj Delhi", location: "Delhi" },
{ id: 2, name: "Hilton", location: "New York" },
],
});
});
// Health check route
app.get("/health", (req, res) => {
res.json({ status: "OK", timestamp: new Date().toISOString() });
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 Server running on http://localhost:${PORT}`);
console.log(`📊 Try these endpoints:`);
console.log(` http://localhost:${PORT}/`);
console.log(` http://localhost:${PORT}/api/hotels`);
console.log(` http://localhost:${PORT}/health`);
});
Modern Express supports ES modules using
"type": "module"in package.json.
Step 2 : Run the Server
To run it simple : node server.js
To run the server, use the node command. For development, it’s best to use nodemon to auto-restart on changes.
- Install
nodemonas a development dependency: npm install –save-dev nodemon - Add a
startscript to yourpackage.json:json”scripts”: { “start”: “node server.js”, “dev”: “nodemon server.js” } - Run your server in development mode: npm run dev
- Visit
http://localhost:3000in your browser.
Key Updates for 2025
- ES6 Modules: The tutorial now uses
importinstead ofrequire(). To enable this, add"type": "module"to yourpackage.jsonor use the.mjsfile extension. - Simplified CORS: For enabling Cross-Origin Resource Sharing, simply install and use the dedicated
corspackage. The manual header-setting approach is no longer recommended for most cases.
npm install cors
import cors from 'cors'; app.use(cors()); // Enable All CORS Requests
Core Concepts
1. Middleware
Middleware functions run sequentially for every request, each doing a small piece of work.
app.use((req, res, next) => {
console.log("Request received");
next();
});
2. Routing
Routing matches URL + HTTP methods to handler functions.
app.get("/users", (req, res) => {
res.json({ message: "User list" });
});
3. JSON & Form Parsing
Express now includes body-parsing features by default:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Using Express with MongoDB (Mongoose)
Install Mongoose:
npm install mongoose
database.js, Ensure you are using the latest Mongoose version which has better async/await support and simplified options.
import mongoose from 'mongoose';
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.DB_URL);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.error(error);
process.exit(1);
}
};
connectDB();
Add .env:
DB_URL=mongodb://your_url_here
Include DB in server setup:
import { connectDB } from "./database.js";
connectDB();
Enabling CORS (2025 Best Practice)
Option 1: Using cors package (still reliable)
npm install cors
import cors from "cors";
app.use(cors());
Option 2: Custom CORS headers
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
next();
});
Nodemon for Development
npm install --save-dev nodemon
Add script:
"dev": "nodemon server.js",
"start": "node server.js"
Run:
npm run dev