Skip to main content

Express Route Paths

Route paths are an essential part of Express.js routing. They determine how your application responds to client requests at specific endpoints or URLs. Understanding how to effectively use route paths will help you build clean, organized, and functional web applications.

Introduction to Route Paths

In Express, a route path combined with a request method defines where and how your application handles requests. The path can be:

  • A simple string
  • A string pattern with wildcards
  • A regular expression
  • A combination of multiple paths

Route paths support various patterns that help us create flexible and dynamic routing structures in our applications.

Basic String Paths

The simplest form of route paths are string literals. These match the exact URL path that follows your domain name.

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

// Basic route with a string path
app.get('/', (req, res) => {
res.send('This is the homepage');
});

// Another basic route
app.get('/about', (req, res) => {
res.send('About page');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

When a user visits http://localhost:3000/, they'll see "This is the homepage", and when they visit http://localhost:3000/about, they'll see "About page".

Route Parameters

Often, we need to capture values from the URL. Route parameters allow us to do this by specifying named segments in the route path.

javascript
// Route with a parameter
app.get('/users/:userId', (req, res) => {
res.send(`User profile for user ID: ${req.params.userId}`);
});

// Multiple parameters
app.get('/users/:userId/books/:bookId', (req, res) => {
res.send(`User ${req.params.userId} is viewing book ${req.params.bookId}`);
});

If a user visits http://localhost:3000/users/123, they'll see "User profile for user ID: 123". Similarly, http://localhost:3000/users/123/books/456 will display "User 123 is viewing book 456".

Route parameters are identified by a colon (:) followed by the parameter name. The values are stored in the req.params object using the parameter names as keys.

String Patterns and Special Characters

Express route paths support pattern matching through special characters:

The ? Character

The question mark makes the previous character optional:

javascript
// Will match both "search" and "searc"
app.get('/searc?h', (req, res) => {
res.send('Search page');
});

The + Character

The plus sign matches one or more occurrences of the previous character:

javascript
// Will match "search", "searcch", "searcccch", etc.
app.get('/searc+h', (req, res) => {
res.send('Search page with many c\'s');
});

The * Character

The asterisk acts as a wildcard, matching any character or sequence:

javascript
// Will match "search", "searchify", "searching", etc.
app.get('/search*', (req, res) => {
res.send('Search with suffix');
});

The () Characters

Parentheses group characters together:

javascript
// Will match "search" or "seek"
app.get('/se(ar|e)ch', (req, res) => {
res.send('Search or seek page');
});

Regular Expressions

For more complex pattern matching, Express supports regular expressions:

javascript
// Will match any path that ends with "fly"
app.get(/.*fly$/, (req, res) => {
res.send('Something that ends with fly');
});

This route will match paths like /butterfly, /dragonfly, or even /fly.

Practical Example: Building a Blog API

Let's see how we might use route paths in a real-world application like a blog API:

javascript
const express = require('express');
const app = express();
app.use(express.json());

// Sample blog data
const blogPosts = [
{ id: 1, title: 'Getting Started with Express', content: 'Express is a minimal web framework...' },
{ id: 2, title: 'Route Parameters', content: 'Route parameters are named URL segments...' }
];

// Get all blog posts
app.get('/api/posts', (req, res) => {
res.json(blogPosts);
});

// Get a specific post by ID
app.get('/api/posts/:postId', (req, res) => {
const postId = parseInt(req.params.postId);
const post = blogPosts.find(p => p.id === postId);

if (post) {
res.json(post);
} else {
res.status(404).json({ error: 'Post not found' });
}
});

// Get posts with optional category filter
app.get('/api/posts/category/:categoryName?', (req, res) => {
if (req.params.categoryName) {
res.json({ message: `Posts filtered by category: ${req.params.categoryName}` });
} else {
res.json({ message: 'All posts (no category filter)' });
}
});

app.listen(3000, () => {
console.log('Blog API running on port 3000');
});

In this example:

  • /api/posts returns all blog posts
  • /api/posts/1 returns the blog post with ID 1
  • /api/posts/category/javascript would filter posts by the "javascript" category
  • /api/posts/category would return all posts without filtering

Route Path Order Matters

The order in which you define routes in Express is significant. Express matches routes in the order they are defined. Consider this example:

javascript
// This route will never be reached
app.get('/users/:userId', (req, res) => {
res.send(`User profile: ${req.params.userId}`);
});

// This specific route will always match first
app.get('/users/admin', (req, res) => {
res.send('Admin dashboard');
});

In this case, if you visit /users/admin, Express will match the first route and treat "admin" as the userId. To fix this, define more specific routes before more general ones:

javascript
// Specific route first
app.get('/users/admin', (req, res) => {
res.send('Admin dashboard');
});

// General route after
app.get('/users/:userId', (req, res) => {
res.send(`User profile: ${req.params.userId}`);
});

Summary

Express route paths are powerful tools for building dynamic web applications. They allow you to:

  • Define simple routes with string paths
  • Capture data from URLs with route parameters
  • Create flexible routes with string patterns and special characters
  • Use regular expressions for complex matching
  • Build organized APIs with clean URL structures

Understanding how to effectively use route paths is fundamental to Express.js development and will help you create more maintainable and user-friendly web applications.

Additional Resources

Exercises

  1. Create a route that responds to /products and /products/all with the same handler function.
  2. Build a route that captures both a user ID and a status parameter (e.g., /users/123/status/active).
  3. Create a route that matches any path that starts with /download/ and ends with either .pdf or .doc.
  4. Implement a simple REST API for a todo list with routes for listing, creating, updating, and deleting todos.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)