TechLearn Hub

Simple Technology Learning for Everyone

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.

Simple idea: Node.js lets JavaScript run on a server. Express provides convenient tools for building web servers and APIs with Node.js.

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.

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
Version note: Express 5 requires Node.js 18 or higher. Check the official documentation for current compatibility and installation instructions.

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.

Important: This is a local development server. Other people cannot automatically access it through a public website. To make an application available online, you need suitable hosting and production configuration.

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.

Basic request flow:

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:

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:

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"
    });
});
Do not assume that 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.

Do not place private credentials, database files, or confidential documents in a directory that is publicly served.

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.

This is a learning example, not a production database. In a real application, use persistent storage, authentication where required, authorization, validation, and appropriate error handling.

HTTP Status Codes

HTTP status codes communicate the result of a request to the client.

Status Meaning
200Request succeeded
201Resource created
204Request succeeded with no response body
400Bad request
401Authentication is required or invalid
403Access is forbidden
404Resource or route not found
500Internal 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.

In production, avoid sending stack traces, secrets, or internal system details to users. Log appropriate diagnostic information securely.

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

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.

Never store passwords in plain text. Use established password-hashing libraries and follow secure authentication practices. Protect session cookies, secrets, and private API credentials.

Express Security Best Practices

Security needs to be considered from the beginning of a backend project. Useful practices include:

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 Svelte

A frontend can make HTTP requests to an Express API, receive JSON responses, and display the returned data.

Frontend → HTTP Request → Express API → Database → JSON Response

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.

These are example URLs, not live APIs. A real mobile application needs a deployed backend, appropriate network permissions, and secure handling of authentication tokens and user data.

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

Limitations and Things to Understand

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

  1. Hello World server.
  2. Simple website backend.
  3. Contact form API.
  4. Todo API.
  5. Notes API.
  6. Product catalog API.
  7. Blog backend.
  8. User authentication demo.
  9. Weather information dashboard backend.
  10. Mobile application backend.
  11. Football scores API client backend.
  12. 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.

This small example is for learning. A public API needs additional protection, suitable persistence, and validation appropriate to its requirements.

Express.js Learning Roadmap

  1. Learn JavaScript fundamentals.
  2. Understand Node.js and npm.
  3. Learn HTTP requests and responses.
  4. Install Express.
  5. Create your first Express server.
  6. Learn routes and HTTP methods.
  7. Understand request and response objects.
  8. Learn middleware and request parsing.
  9. Work with JSON.
  10. Learn route and query parameters.
  11. Organize routes with Express Router.
  12. Build a small REST API.
  13. Connect a database.
  14. Learn validation and error handling.
  15. Understand authentication and authorization.
  16. Study web security basics.
  17. Learn environment configuration.
  18. 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.paramsRead route parameters
req.queryRead query parameters
req.bodyAccess 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.

Next step: Build a small REST API with Express. Practising with a real project will help you understand routing, middleware, and request handling.