Express.js Introduction

Beginner
⏱️ 16 min read
📚 Updated: Jul 2026
🎯 5 Examples
Node.js · API · middleware

What You’ll Learn

This page is a self-contained introduction to Express.js—the most popular web framework for Node.js. You will understand what Express does, install it, and build your first HTTP server with routes and middleware.

01

Introduction

What Express adds.

02

Key features

Middleware & routes.

03

Advantages

Why teams pick it.

04

Setup

npm & listen.

05

Examples

Hello API.

06

Trade-offs

Pros & cons.

👋 Introduction

Express.js, commonly known as Express, is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile backends.

It simplifies building scalable, maintainable server applications by offering clean routing, middleware hooks, and helpers for HTTP requests and responses. Instead of wiring low-level http modules by hand, Express gives you a small API that scales from a one-file demo to production APIs.

💡
Beginner tip

Install Node.js first, then run npm install express in a project folder. Start with a single app.get('/') route before adding databases or authentication.

🔑 Key Features of Express.js

Middleware Support

Express is known for its middleware support, which lets you extend the application with functions that receive req, res, and next. Use middleware for logging, authentication, parsing JSON bodies, and centralized error handling.

JavaScript
const express = require('express');
const app = express();

const customMiddleware = (req, res, next) => {
  console.log('This middleware runs before the route handler.');
  next();
};

app.use(customMiddleware);

app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Routing

Express provides a simple routing system based on HTTP methods and URL patterns. Define app.get, app.post, app.put, and app.delete handlers to keep code organized as your API grows.

JavaScript
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

app.get('/about', (req, res) => {
  res.send('This is the About page.');
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Template Engines

Express supports template engines such as EJS, Pug, and Handlebars for server-side HTML rendering. Set view engine, place templates in a views folder, and call res.render() to separate presentation from route logic.

JavaScript
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.render('index', {
    title: 'Express.js Example',
    message: 'Hello, Express!'
  });
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

HTTP Utility Methods

Express makes request and response handling straightforward. Built-in middleware parses JSON and URL-encoded bodies; response helpers send JSON, set headers, redirect, and stream files.

JavaScript
const express = require('express');
const app = express();

app.use(express.json());

app.post('/api/user', (req, res) => {
  const { username, email } = req.body;
  res.json({ username, email });
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

👍 Advantages of Express.js

  1. Fast and minimalistic — Express focuses on core HTTP features without heavy opinionated structure, keeping apps lightweight and quick to start.
  2. Active community and ecosystem — thousands of middleware packages cover sessions, CORS, security headers, rate limiting, and database integration.
  3. Flexibility and customization — choose your own folder layout, ORM, and front-end stack; Express does not lock you into one architecture.

👎 Disadvantages of Express.js

  1. Lack of built-in features — Express intentionally stays small. You often add third-party packages for validation, ORMs, and real-time features, which requires choosing and wiring libraries yourself.
  2. Learning curve for beginners — concepts like middleware chains, async error handling, and routing order take time if you are new to Node.js or server-side JavaScript.

💻 How to Install and Run

Express runs on Node.js. Create a project, install the package, write a server file, and start it with node.

terminal
mkdir my-express-app
cd my-express-app
npm init -y
npm install express
node app.js
  • npm init -y — creates package.json with default settings.
  • npm install express — adds Express to node_modules and records it in dependencies.
  • node app.js — runs your server; visit the URL printed in the console.
  • Use nodemon app.js during development to auto-restart on file changes.

🧰 Core Building Blocks

ConceptWhat it does
Application (app)Main Express instance; registers routes and middleware
RouterModular mini-app for grouping related routes
MiddlewareFunctions that run in order for each request
Route handlersCallbacks that send responses for specific URLs and methods
req objectIncoming HTTP request (params, query, body, headers)
res objectOutgoing response (send, json, status, render)
app.listen()Starts the HTTP server on a port

⚡ Quick Reference

TaskCode snippet
Create appconst app = express();
GET routeapp.get('/path', (req, res) => { ... });
Parse JSON bodyapp.use(express.json());
Send textres.send('Hello');
Send JSONres.json({ ok: true });
Start serverapp.listen(3000, () => console.log('Ready'));

📝 Example & Examples Gallery

Five starter servers you can copy into app.js after running npm install express. Save the file, run node app.js, and test routes in a browser or with curl.

Example 1 — Hello, Express!

The smallest useful server: one GET route and app.listen.

JavaScript
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Example 2 — Custom middleware

JavaScript
const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.get('/', (req, res) => {
  res.send('Logged request!');
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Example 3 — Multiple routes

JavaScript
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Home page');
});

app.get('/about', (req, res) => {
  res.send('This is the About page.');
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Example 4 — JSON POST API

JavaScript
const express = require('express');
const app = express();

app.use(express.json());

app.post('/api/user', (req, res) => {
  const { username, email } = req.body;
  res.json({ username, email });
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Example 5 — Route parameters

JavaScript
const express = require('express');
const app = express();

app.get('/users/:id', (req, res) => {
  res.json({ userId: req.params.id });
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Dynamic segments like :id appear in req.params—essential for REST APIs.

📋 Express vs Other Node Frameworks

FrameworkStyleBest for beginners when…
ExpressMinimal, middleware-centricYou want the largest ecosystem and most tutorials
FastifyPerformance-focused, schema validationYou need high throughput APIs with built-in logging
KoaAsync middleware (from Express creators)You prefer modern async/await middleware patterns
Node httpBuilt-in, no frameworkYou want to understand HTTP at the lowest level first

🧠 How an Express Request Flows

1

Client sends HTTP request

Browser or API client hits a URL like GET /api/user.

Request
2

Middleware runs

Logging, JSON parsing, and auth middleware execute in registration order.

Middleware
3

Route handler matches

Express finds the handler for the method and path, then runs your callback.

Route
=

Response sent

res.send, res.json, or res.render returns data to the client.

🎉 Conclusion

  • Express.js is a powerful, widely used framework in the Node.js ecosystem.
  • Its simplicity, flexibility, and rich middleware ecosystem make it ideal for APIs and web apps.
  • Key features include middleware, routing, template engines, and HTTP utility methods.
  • Trade-offs include minimal built-ins and a learning curve for server-side newcomers.
  • Whether you are a beginner or experienced developer, Express streamlines backend development.
  • Start with one route, then grow into routers, JSON APIs, and production middleware.

💡 Best Practices

✅ Do

  • Use express.json() before routes that read JSON bodies
  • Organize routes into separate router modules as the app grows
  • Centralize error handling with a four-argument middleware
  • Store secrets in environment variables, not source code
  • Return appropriate HTTP status codes (res.status(404), etc.)
  • Use helmet and cors middleware in production APIs

❌ Don’t

  • Call res.send twice in the same request handler
  • Forget to call next() in middleware that should pass control forward
  • Block the event loop with long synchronous work on every request
  • Hard-code ports without reading process.env.PORT
  • Skip input validation on user-supplied req.body data
  • Expose stack traces to clients in production error responses

❓ Frequently Asked Questions

Express.js is a minimal, flexible web framework for Node.js. It simplifies HTTP servers, routing, middleware, and template rendering so you can build APIs and web apps faster than using Node's built-in http module alone.
Yes, at least the basics: npm, modules with require or import, and asynchronous JavaScript. Express runs on Node.js, so understanding how Node executes JavaScript on the server is essential.
Yes. Express is open source under the MIT license. You can use it in personal and commercial projects without licensing fees.
REST APIs, JSON backends for React or mobile apps, server-rendered websites with EJS or Pug, webhooks, microservices, and full-stack applications when paired with a database and front-end framework.
Middleware functions run between receiving a request and sending a response. They can log requests, parse JSON bodies, authenticate users, or handle errors. Call next() to pass control to the next function in the chain.
Create a project folder, run npm init and npm install express, save your server code as app.js, then run node app.js. Visit http://localhost:3000 (or your chosen port) in a browser or API client.
Did you know?

Express has been the de facto Node.js web framework since 2010. Major platforms—including many tutorial sites and production APIs—use Express with EJS templates, static file serving, and middleware like Helmet for security. The CodeToFun website itself is built with Express and EJS.

Try It Yourself

Create a folder, run npm install express, paste Example 1 into app.js, and start building.

Get Node.js →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful