What Is Express.js?
Express.js, commonly called Express, is a web application framework for Node.js. It provides tools for building web applications, HTTP servers, routes, and APIs using JavaScript.
Express is built around routing and middleware. An application receives a request, processes it through middleware and route handlers, and sends an appropriate response to the client.
Express is intentionally minimal. Developers can add the middleware, database libraries, and other tools their projects require.
Official documentation: Express.js website.
Why Do Developers Use Express.js?
A server can be built using Node.js alone, but Express simplifies many common web development tasks.
- Create web servers.
- Build REST-style HTTP APIs.
- Define application routes.
- Process HTTP requests and responses.
- Use middleware to organize request processing.
- Serve static files such as HTML, CSS, JavaScript, and images.
- Handle errors and missing routes.
- Connect applications to databases through appropriate libraries.
- Build backend services for websites and mobile applications.
Express.js and Node.js
| Node.js | Express.js |
|---|---|
| JavaScript runtime | Web application framework |
| Provides server-side JavaScript capabilities | Simplifies web application development |
| Includes the built-in HTTP module | Provides convenient routing and middleware |
| Can create servers without Express | Runs on Node.js |
Express does not replace Node.js. It uses Node.js and adds a convenient framework for handling web requests.
Installing Express.js
You need Node.js and npm installed on your development environment. npm is the package manager commonly used to install JavaScript libraries.
Create a project folder and initialize it:
mkdir myapp
cd myapp
npm init -y
Install Express:
npm install express
Check your installed Node.js and npm versions:
node --version
npm --version
Your First Express Application
This example creates an Express application with a home route and starts a server on port 3000.
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Save this code as app.js.
Start the server:
node app.js
On the same computer where the server is running, open
http://localhost:3000 in a browser.
How Express Requests Work
A browser, website, or mobile application sends an HTTP request to the server. Express passes the request through applicable middleware and route handlers. The application then sends a response.
Client → Express Server → Middleware → Route Handler → Response
The exact middleware and route handlers that run depend on the application's configuration and the incoming request.
What Is Routing?
Routing determines how an application responds to a particular URL path and HTTP method.
app.METHOD(PATH, HANDLER);
For example, a GET route for the home page looks like this:
app.get("/", (req, res) => {
res.send("Home Page");
});
Common route methods include get(), post(),
put(), and delete().
GET Routes
GET requests are commonly used to retrieve information from a server.
app.get("/users", (req, res) => {
res.send("User List");
});
A request to /users using GET can be handled by this
route.
POST Routes
POST requests commonly send data to a server, for example when submitting a form or creating a resource.
app.post("/users", (req, res) => {
res.status(201).send("User Created");
});
In a real application, validate the submitted data and save it to an appropriate data store before reporting that a resource was created.
PUT Routes
PUT is commonly used to create or replace the state of a resource at a known URL. Applications sometimes use it for updates.
app.put("/users/:id", (req, res) => {
res.send(`Update requested for user ${req.params.id}`);
});
This example only demonstrates routing. It does not actually update a database record.
DELETE Routes
DELETE requests are used to request removal of a resource.
app.delete("/users/:id", (req, res) => {
res.send(`Delete requested for user ${req.params.id}`);
});
A production application should verify permissions and perform the actual deletion before returning an appropriate response.
Request and Response Objects
Express route handlers commonly receive two important objects:
reqrepresents the incoming request.resprovides methods for sending a response.
app.get("/", (req, res) => {
console.log(req.method);
console.log(req.path);
res.send("Welcome!");
});
The request object also provides information such as route parameters, query parameters, headers, and parsed request data when appropriate middleware has been configured.
Sending JSON
JSON is a common format for transferring structured data between servers, websites, and mobile applications.
app.get("/api/user", (req, res) => {
res.json({
name: "John",
age: 25,
country: "Nigeria"
});
});
Express sets an appropriate content type when sending a JSON response
through res.json().
What Is Middleware?
Middleware functions run during the request-response process. They can execute code, access the request and response objects, end the request, or pass control to the next middleware.
app.use((req, res, next) => {
console.log("Request received");
next();
});
Calling next() passes control onward. Middleware that
neither sends a response nor passes control onward can leave a
request waiting.
Why Middleware Is Important
Middleware can support tasks such as:
- Logging requests.
- Authentication and authorization.
- Parsing request data.
- Validating incoming data.
- Applying security checks.
- Serving static files.
- Handling errors.
- Applying rate limits where appropriate.
Built-in JSON Middleware
Express includes express.json() to parse incoming JSON
request bodies when the request has a supported JSON content type.
app.use(express.json());
app.post("/users", (req, res) => {
console.log(req.body);
res.json({
message: "User data received"
});
});
req.body is valid or trustworthy.
Validate required fields, data types, lengths, and permissions before
using submitted values.
URL Route Parameters
Route parameters allow a URL to contain a value that can be read by the route handler.
app.get("/users/:id", (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
For example, requesting /users/25 gives the parameter
id the value 25.
Validate parameter values before using them in database queries or other operations.
Query Parameters
Query parameters are values included after a question mark in a URL. They are commonly used for searching, filtering, and pagination.
app.get("/search", (req, res) => {
const keyword = req.query.keyword;
res.json({
searchTerm: keyword
});
});
Example URL:
/search?keyword=javascript
Query values come from client input. Check their types and validate them before using them.
Serving Static Files
The express.static() middleware can serve files such as
HTML, CSS, client-side JavaScript, and images.
app.use(express.static("public"));
A project could contain these files:
public/
index.html
style.css
app.js
images/
With this configuration, files inside the public
directory can be served as static resources.
Express Router
As an application grows, placing every route in one file can become
difficult to maintain. express.Router() lets you group
related routes into separate modules.
Example: create a file named users.js.
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Users List");
});
router.get("/:id", (req, res) => {
res.send(`User ${req.params.id}`);
});
module.exports = router;
Mounting a Router
Import the router into the main application and mount it at a path.
const express = require("express");
const app = express();
const usersRouter = require("./users");
app.use("/users", usersRouter);
app.listen(3000, () => {
console.log("Server running on port 3000");
});
The router can now handle requests to /users and
/users/:id.
Express and REST APIs
Express is commonly used to create HTTP APIs. A REST-style API often represents resources through URLs and uses HTTP methods to perform operations.
GET /api/products
GET /api/products/:id
POST /api/products
PUT /api/products/:id
DELETE /api/products/:id
These endpoints illustrate a common pattern for working with product resources. The exact behavior depends on the application design.
Simple Product API Example
This example demonstrates listing products and adding a product in memory. The data disappears when the server restarts, so a real application would normally use persistent storage.
const express = require("express");
const app = express();
app.use(express.json());
let nextId = 3;
let products = [
{ id: 1, name: "Phone" },
{ id: 2, name: "Laptop" }
];
app.get("/api/products", (req, res) => {
res.json(products);
});
app.post("/api/products", (req, res) => {
const name = req.body?.name;
if (typeof name !== "string" || !name.trim()) {
return res.status(400).json({
error: "A valid product name is required"
});
}
const product = {
id: nextId++,
name: name.trim()
};
products.push(product);
res.status(201).json(product);
});
app.listen(3000, () => {
console.log("API running on port 3000");
});
Start the application and send requests to
http://localhost:3000/api/products from a browser or an
API testing tool.
HTTP Status Codes
HTTP status codes communicate the result of a request to the client.
| Status | Meaning |
|---|---|
| 200 | Request succeeded |
| 201 | Resource created |
| 204 | Request succeeded with no response body |
| 400 | Bad request |
| 401 | Authentication is required or invalid |
| 403 | Access is forbidden |
| 404 | Resource or route not found |
| 500 | Internal server error |
res.status(404).json({
error: "Product not found"
});
Error Handling
Express supports error-handling middleware. It has four parameters:
err, req, res, and
next.
app.use((err, req, res, next) => {
console.error(err);
if (res.headersSent) {
return next(err);
}
res.status(500).json({
error: "Something went wrong"
});
});
Place general error-handling middleware after the routes and middleware that may pass errors to it.
404 Route Handling
A 404 response is appropriate when no route has handled the requested path. Place a fallback after your normal routes.
app.use((req, res) => {
res.status(404).json({
error: "Route not found"
});
});
A route that exists but cannot find a requested database record may also return 404 from its own handler.
Express and Databases
Express does not include its own database system. Applications use suitable database drivers or libraries to store and retrieve data.
Common Database Choices
- PostgreSQL
- MySQL
- SQLite
- MongoDB
- MariaDB
Choose a database based on the data model, application requirements, hosting environment, performance needs, and maintenance requirements.
Express and Authentication
Authentication checks who a user is. Authorization determines what that user is allowed to do.
Express does not force one authentication system. Developers can use sessions, secure cookies, token-based approaches, OAuth integrations, or suitable authentication libraries.
Express Security Best Practices
Security needs to be considered from the beginning of a backend project. Useful practices include:
- Validate incoming data and reject invalid input.
- Use authentication and authorization where needed.
- Keep private credentials out of public source code.
- Use HTTPS in production.
- Keep Node.js and dependencies updated.
- Use appropriate security middleware.
- Apply rate limiting to sensitive or abuse-prone endpoints.
- Configure CORS deliberately when browser clients need it.
- Limit sensitive details in error responses.
- Use parameterized database queries or safe query builders.
- Review file uploads and access permissions carefully.
Security middleware can help, but it does not replace correct application logic, validation, access control, or secure deployment.
Environment Variables
Database credentials, private API keys, and environment-specific settings should not normally be hard-coded into application source code.
Environment variables are a common way to configure a server.
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Configure variables through your hosting provider or development environment. Do not publish private values in your website or public repository.
Express Project Structure
Express does not require a single folder structure. A larger project might separate routes, controllers, middleware, models, and static files.
my-app/
├── app.js
├── package.json
├── routes/
│ ├── users.js
│ └── products.js
├── controllers/
│ ├── userController.js
│ └── productController.js
├── middleware/
│ └── auth.js
├── models/
│ └── user.js
└── public/
├── index.html
├── style.css
└── app.js
This is one possible organization. For a small project, a simpler structure may be enough.
Express Application Generator
The Express application generator can create a basic project structure to help you get started.
npx express-generator myapp
cd myapp
npm install
Review the generated files before using them. You can change the structure and add dependencies according to your application's needs.
Learn more: Express application generator documentation.
Express with Frontend Frameworks
Express can provide backend APIs for applications built with different frontend technologies.
React Vue Angular SvelteA frontend can make HTTP requests to an Express API, receive JSON responses, and display the returned data.
Some frameworks also provide their own server-side features. Choose an architecture that fits your project's requirements.
Express and JSON APIs for Mobile Apps
An Android or other mobile application can communicate with an Express backend over HTTP or HTTPS.
For example, a backend might expose endpoints such as:
https://example.com/api/users
https://example.com/api/products
https://example.com/api/news
The server can authenticate requests when necessary, retrieve data from a database, and return a JSON response.
Express vs the Node.js HTTP Module
Node.js includes an HTTP module that can create servers without Express. Express provides higher-level tools for routing and middleware.
Node.js HTTP Example
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Hello World");
});
server.listen(3000);
Express Example
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World");
});
app.listen(3000);
Both approaches can create a server. Express is useful when you want its routing, middleware, and other web application features.
Advantages of Express.js
- Relatively easy to get started with.
- Works with JavaScript and Node.js.
- Provides flexible application structure.
- Supports routing and middleware.
- Useful for HTTP APIs and backend services.
- Can serve static files.
- Works with many database libraries.
- Has a large ecosystem of supporting packages.
- Can be used for small applications and larger services.
Limitations and Things to Understand
- Express does not provide a database by itself.
- You must choose and configure an authentication approach.
- Larger applications need clear organization.
- Security depends on sound implementation and configuration.
- Developers need to understand JavaScript, HTTP, and asynchronous code.
- Additional features may require third-party packages.
Express is intentionally flexible. That flexibility gives developers freedom, but it also means they must make thoughtful choices about project structure and supporting libraries.
Common Express.js Mistakes
1. Forgetting to call next()
Middleware that does not send a response or pass control onward can leave the request waiting.
2. Placing the 404 handler too early
Place a general 404 handler after the routes it is intended to follow.
3. Exposing secret keys
Do not publish API keys, database passwords, or other private credentials.
4. Failing to validate user input
Treat client-supplied values as untrusted. Validate their types, lengths, formats, and permissions before using them.
5. Inconsistent error handling
Use appropriate status codes and avoid revealing unnecessary internal details in production responses.
6. Assuming in-memory data is permanent
Arrays and objects stored only in application memory are normally lost when the process restarts. Use a suitable persistent database when data must be retained.
Beginner Express.js Project Ideas
- Hello World server.
- Simple website backend.
- Contact form API.
- Todo API.
- Notes API.
- Product catalog API.
- Blog backend.
- User authentication demo.
- Weather information dashboard backend.
- Mobile application backend.
- Football scores API client backend.
- Learning platform backend.
Start with a small project, test it, and add features gradually. A project that uses a database, validation, and error handling is a useful next step after learning basic routes.
Simple Todo API
This example demonstrates retrieving and adding todo items. Like the product example, the data is held in memory and is not permanent.
const express = require("express");
const app = express();
app.use(express.json());
let nextId = 3;
let todos = [
{ id: 1, title: "Learn Express" },
{ id: 2, title: "Build an API" }
];
app.get("/todos", (req, res) => {
res.json(todos);
});
app.post("/todos", (req, res) => {
const title = req.body?.title;
if (typeof title !== "string" || !title.trim()) {
return res.status(400).json({
error: "A valid title is required"
});
}
const todo = {
id: nextId++,
title: title.trim()
};
todos.push(todo);
res.status(201).json(todo);
});
app.listen(3000, () => {
console.log("Todo API running on port 3000");
});
Save the code as app.js, install Express, and run
node app.js. You can test GET requests in a browser and
use an API testing tool to send POST requests.
Express.js Learning Roadmap
- Learn JavaScript fundamentals.
- Understand Node.js and npm.
- Learn HTTP requests and responses.
- Install Express.
- Create your first Express server.
- Learn routes and HTTP methods.
- Understand request and response objects.
- Learn middleware and request parsing.
- Work with JSON.
- Learn route and query parameters.
- Organize routes with Express Router.
- Build a small REST API.
- Connect a database.
- Learn validation and error handling.
- Understand authentication and authorization.
- Study web security basics.
- Learn environment configuration.
- Test and deploy an application.
Express.js Cheat Sheet
| Code | Purpose |
|---|---|
express() | Create an Express application |
app.listen() | Start the server |
app.get() | Define a GET route |
app.post() | Define a POST route |
app.put() | Define a PUT route |
app.delete() | Define a DELETE route |
app.use() | Register middleware or mount a router |
express.json() | Parse supported JSON request bodies |
express.static() | Serve static files |
req.params | Read route parameters |
req.query | Read query parameters |
req.body | Access parsed request data |
res.send() | Send a response |
res.json() | Send a JSON response |
res.status() | Set the HTTP status code |
express.Router() | Create modular route handlers |
Frequently Asked Questions
Is Express.js a programming language?
No. Express.js is a web framework for Node.js. It is commonly used with JavaScript.
Is Express.js the same as Node.js?
No. Node.js is a JavaScript runtime, while Express is a framework that runs on Node.js.
Can Express build APIs?
Yes. Express is widely used to create HTTP APIs and backend services.
Can Express connect to a database?
Yes. Express applications can use appropriate database drivers and libraries to communicate with databases.
Can Express be used for Android apps?
Yes. An Android app can communicate with a deployed Express backend through HTTP or HTTPS APIs.
Does Express include authentication automatically?
Express does not require one particular authentication system. Developers choose an appropriate approach and configure it securely.
Does Express require Node.js?
Yes. Express is a web framework that runs on Node.js.
What Node.js version does Express 5 require?
Express 5 requires Node.js 18 or higher. Check the official documentation for current requirements.
Can I host Express on Cloudflare Pages?
Cloudflare Pages is designed primarily for static sites and supported serverless functions. A conventional, continuously running Express server generally needs a suitable Node.js hosting environment, or you may need to adapt the application to a supported serverless platform.
Conclusion
Express.js is a useful framework for building backend applications and APIs with JavaScript and Node.js. It provides routing and middleware tools that help developers process HTTP requests and organize server-side code.
Important topics include routes, middleware, request and response objects, JSON, parameters, REST APIs, error handling, databases, authentication, and security.
Start with a small server, build a simple API, test your endpoints, and then add persistent storage and the security features your application requires.