Introduction to Express.js
Build web apps faster with Node's most popular framework
- install Express into a Node project with npm,
- create a server and define routes (URL + method),
- read the request and send a response,
- use middleware to run code on every request.
1. What is Express, and why use it?
Express is a web framework for Node.js. A framework is a set of ready-made tools that take care of the repetitive, boring parts so you can write less code.
Analogy. Building a server with plain Node is like cooking from raw ingredients: you chop, measure, and clean everything yourself. Express is like a well-stocked kitchen with prepped ingredients and sharp knives already laid out. You still cook the meal (your app), but the setup is done for you.
Here is the same tiny server written both ways so you can feel the difference. First, plain Node:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello!');
} else {
res.writeHead(404);
res.end('Not found');
}
});
server.listen(3000);
Now the same idea with Express - shorter and easier to read:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello!');
});
app.listen(3000);
Express set the status code, the content type, and matched the URL and method for us. That is the plumbing it handles.