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