What is Express.js and why is it used?
What is Express.js?
Express.js is a minimal, fast, and unopinionated web framework for Node.js. It provides a thin layer of fundamental web application features on top of Node.js's built-in http module, without obscuring any of Node.js's core capabilities.
Why Use Express.js?
Without Express, a basic Node.js HTTP server looks like:
js
// Pure Node.js — verbose and manual
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ users: [] }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);With Express:
js
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.json({ users: [] });
});
app.listen(3000);Core Features
| Feature | Description |
|---|---|
| Routing | Define URL handlers with HTTP methods |
| Middleware | Composable request/response pipeline |
| Static files | Serve HTML, CSS, images with one line |
| Template engines | Render HTML with EJS, Pug, Handlebars |
| Error handling | Centralized error management |
| REST API support | JSON parsing, status codes, headers |
Hello World
js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});Express.js vs Alternatives
| Framework | Style | Best For |
|---|---|---|
| Express.js | Minimal, flexible | REST APIs, full-stack apps |
| Fastify | Fast, schema-based | High-performance APIs |
| Koa | Modern, async-first | Lightweight middleware chains |
| NestJS | Opinionated, TypeScript | Enterprise-scale apps |
| Hapi | Configuration-heavy | Secure enterprise APIs |
Express Application Object
js
const express = require('express');
const app = express();
// app is an instance of Express Application
// Key properties and methods:
app.use() // mount middleware
app.get() // handle GET route
app.post() // handle POST route
app.listen() // start HTTP server
app.set() // configure settings
app.locals // app-level variablesSummary
Express.js simplifies Node.js web development by providing routing, middleware, and utilities for building HTTP servers. It's the most popular Node.js framework with a massive ecosystem and is the foundation for frameworks like NestJS and LoopBack.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.