Introduction to Express.js
Getting started with Express.js - the fast, unopinionated web framework for Node.js
What is Express.js?
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It's the de facto standard server framework for Node.js, powering millions of applications worldwide.
β‘ Why Express.js?
Minimal & Fast
Thin layer of features without hiding Node.js
Robust Routing
Powerful routing API with full control
Middleware
Pluggable middleware for any functionality
Battle-tested
Used by Netflix, Uber, IBM, PayPal
Installation
# Create a new project
mkdir my-express-app
cd my-express-app
# Initialize package.json
npm init -y
# Install Express
npm install express
# For TypeScript projects
npm install express
npm install -D typescript @types/express @types/node ts-node nodemon
# Initialize TypeScript
npx tsc --init
Your First Express Server
// app.js (JavaScript)
const express = require('express');
const app = express();
const PORT = 3000;
// Basic route
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// JSON response
app.get('/api/status', (req, res) => {
res.json({ status: 'running', timestamp: new Date() });
});
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
// Run with: node app.js
Express with TypeScript
// src/app.ts
import express, { Request, Response } from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON
app.use(express.json());
// Type-safe route
app.get('/', (req: Request, res: Response) => {
res.json({ message: 'Hello from TypeScript Express!' });
});
// Route with typed parameters
interface UserParams {
id: string;
}
app.get('/users/:id', (req: Request<UserParams>, res: Response) => {
const { id } = req.params;
res.json({ userId: id });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
// package.json scripts
{
"scripts": {
"dev": "nodemon --exec ts-node src/app.ts",
"build": "tsc",
"start": "node dist/app.js"
}
}
Project Structure
# Recommended Express.js project structure
my-express-app/
βββ src/
β βββ app.ts # Express app setup
β βββ server.ts # Server entry point
β βββ routes/
β β βββ index.ts # Route aggregator
β β βββ users.ts # User routes
β β βββ products.ts # Product routes
β βββ controllers/
β β βββ userController.ts
β β βββ productController.ts
β βββ middleware/
β β βββ auth.ts # Authentication
β β βββ errorHandler.ts # Error handling
β β βββ validation.ts # Request validation
β βββ models/
β β βββ User.ts # Data models
β βββ services/
β β βββ userService.ts # Business logic
β βββ utils/
β βββ logger.ts # Utility functions
βββ tests/
βββ package.json
βββ tsconfig.json
βββ .env
Basic App Setup Pattern
// src/app.ts - Separate app from server
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import { userRoutes } from './routes/users';
import { errorHandler } from './middleware/errorHandler';
const app = express();
// Security middleware
app.use(helmet());
app.use(cors());
// Logging
app.use(morgan('dev'));
// Body parsing
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Routes
app.use('/api/users', userRoutes);
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'healthy' });
});
// Error handling (must be last)
app.use(errorHandler);
export default app;
// src/server.ts - Entry point
import app from './app';
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`π Server running on port ${PORT}`);
});
Essential Dependencies
# Core dependencies
npm install express cors helmet morgan dotenv
# TypeScript dependencies
npm install -D typescript @types/express @types/cors @types/morgan @types/node
# Development tools
npm install -D nodemon ts-node
# Common additions
npm install express-validator # Request validation
npm install express-rate-limit # Rate limiting
npm install compression # Gzip compression
# package.json
{
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.18.2",
"helmet": "^7.0.0",
"morgan": "^1.10.0"
}
}
π‘ Quick Tips
- β’ Always separate app setup from server startup for testing
- β’ Use
helmet()for security headers out of the box - β’ Use
cors()to enable Cross-Origin requests - β’ Set up environment variables with
dotenvearly - β’ Use
nodemonfor auto-restart during development