Creating Routes in Express.js

🚀 Introduction

Routes are one of the core features of Express.js. A route determines how an application responds to a client's request for a specific URL and HTTP method. Each route consists of a path, an HTTP method, and a callback function (also called a route handler) that processes the request and sends a response.

Information

Express provides methods such as app.get(), app.post(), app.put(), and app.delete() to define routes for different HTTP methods.

📋 Prerequisites

  • Node.js installed.
  • Express.js installed using npm install express.
  • A basic Express server already created.

đŸ›Ŗ What is a Route?

A route tells Express what to do when a client sends a request to a particular URL. It matches the request based on its HTTP method and path, then executes the corresponding route handler.

Client Request
HTTP Method
URL Path
Route Handler
HTTP Response
GET
POST
PUT
DELETE
/
/users
/products

📝 Basic Route Syntax

General Route Syntax

app.METHOD(PATH, (req, res) => {
  // Handle the request
  res.send('Response');
});

Replace METHOD with an HTTP method such as get, post, put, or delete.

📌 Creating a GET Route

GET Route Example

const express = require('express');

const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to the Home Page');
});

app.listen(3000);

When a client sends a GET request to /, Express executes the callback function and returns the specified response.

📌 Creating Multiple Routes

Multiple Routes

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

app.get('/about', (req, res) => {
  res.send('About Page');
});

app.get('/contact', (req, res) => {
  res.send('Contact Page');
});

Tip

Each route should represent a meaningful resource or page within your application.

📌 Routes for Different HTTP Methods

Retrieves data from the server.

GET Route

app.get('/users', (req, res) => {
  res.send('List of Users');
});

Creates new data on the server.

POST Route

app.post('/users', (req, res) => {
  res.send('User Created');
});

Updates existing data.

PUT Route

app.put('/users/:id', (req, res) => {
  res.send('User Updated');
});

Deletes existing data.

DELETE Route

app.delete('/users/:id', (req, res) => {
  res.send('User Deleted');
});

🔗 Route Parameters

Route parameters allow you to capture dynamic values from the URL using a colon (:).

Route Parameters

app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

If the client requests /users/101, the value of req.params.id will be 101.

❓ Query Parameters

Query parameters are appended to the URL after a question mark and are commonly used for filtering, searching, or sorting data.

Query Parameters

app.get('/search', (req, res) => {
  res.send(`Searching for: ${req.query.keyword}`);
});

Example request:
/search?keyword=laptop

🔄 Route Matching Process

📊 Common Route Methods

MethodPurposeExample
app.get()Retrieve data/users
app.post()Create new data/users
app.put()Update existing data/users/1
app.delete()Delete data/users/1
app.all()Handle all HTTP methods/status

🌟 Using app.all()

The app.all() method handles requests for all HTTP methods on a specific path.

app.all() Example

app.all('/status', (req, res) => {
  res.send('Server is running');
});

💡 Best Practices

  • Use meaningful and descriptive route names.
  • Follow RESTful conventions when designing APIs.
  • Keep route handlers short and readable.
  • Move complex business logic into controller files.
  • Group related routes using the Express Router.
  • Use route parameters for dynamic resources and query parameters for filtering.

Best Practice

As your application grows, organize routes into separate files using the Express Router to improve maintainability and code organization.

📚 Learn More

Explore the official Express.js documentation for advanced routing techniques:
â€ĸ Express Routing Guide
â€ĸ Express.js Official Documentation

📝 Summary

Summary

Routes define how an Express.js application responds to incoming HTTP requests. By combining HTTP methods, URL paths, route parameters, and query parameters, you can build powerful and organized web applications and RESTful APIs. As applications grow, organizing routes with the Express Router helps keep the codebase clean, modular, and maintainable.