In a web application, dynamic routing plays a vital role in managing URLs. Express.js makes it incredibly easy to capture values from URLs using Route Parameters and Query Strings. It also allows you to validate and match route parameters using regular expressions (RegEx) for better control over incoming requests.
This post covers:
- Route Parameters
- Route Parameters with Regex
- Optional Route Parameters
- Query Strings
1. Route Parameters in Express.js
Route Parameters are named segments in a URL path that are used to capture values passed in a URL. They are defined using the colon (:) syntax. You can capture and work with dynamic data through route parameters, which is helpful when you want to serve resources based on their ID or another identifier.
Example:
Let's consider a scenario where you want to access a specific user's profile using their ID.
Code Example:
const express = require('express');
const app = express();
app.get('/user/:id', (req, res) => {
const userId = req.params.id; // Accessing the dynamic 'id' parameter
res.send(`User ID: ${userId}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});In this example, when you visit http://localhost:3000/user/123, the response will be:
User ID: 123Here, :id is the route parameter, and the value 123 is dynamically captured and accessible via req.params.id.
Multiple Route Parameters
You can define multiple route parameters within a single route:
app.get('/user/:userId/book/:bookId', (req, res) => {
const { userId, bookId } = req.params;
res.send(`User ID: ${userId}, Book ID: ${bookId}`);
});If you visit http://localhost:3000/user/123/book/456, the response will be:
User ID: 123, Book ID: 4562. Route Parameters with RegEx
Sometimes you need more control over what values can be passed into the route. That's where Regular Expressions (RegEx) come in. You can use RegEx to validate route parameters and ensure they match a specific format.
Example:
Let's say you want to ensure the userId is only numeric and consists of 3 digits.
Code Example:
app.get('/user/:id(\\d{3})', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});In this case, :id(\\d{3}) ensures that the id must be a three-digit number. If you visit http://localhost:3000/user/123, it works fine, but visiting http://localhost:3000/user/abcd will result in a 404 Not Found because the id does not meet the regex requirement.
Explanation:
\\d{3}: This is a regex that allows only numeric values (\\d) and exactly 3 digits ({3}).
3. Optional Route Parameters
You can make route parameters optional by appending a question mark (?) to the parameter. Optional parameters are useful when a specific segment of the route may or may not be provided by the user.
Example:
If you want to create an optional parameter for bookId in a route, you can do it like this:
app.get('/user/:userId/book/:bookId?', (req, res) => {
const { userId, bookId } = req.params;
if (bookId) {
res.send(`User ID: ${userId}, Book ID: ${bookId}`);
} else {
res.send(`User ID: ${userId}, No Book ID provided`);
}
});Behavior:
- Visiting
http://localhost:3000/user/123/book/456will returnUser ID: 123, Book ID: 456. - Visiting
http://localhost:3000/user/123/bookwill returnUser ID: 123, No Book ID provided.
Here, bookId is an optional route parameter.
4. Query Strings in Express.js
Query Strings are a way to pass additional data to the server as key-value pairs. They appear after the ? symbol in a URL and are not part of the route path.
Example:
Let's say you want to allow users to search for books by their title using a query string.
Code Example:
app.get('/search', (req, res) => {
const { title } = req.query; // Accessing query parameters
if (title) {
res.send(`Searching for book: ${title}`);
} else {
res.send('No search term provided');
}
});In this case:
- Visiting
http://localhost:3000/search?title=JavaScriptwill returnSearching for book: JavaScript. - Visiting
http://localhost:3000/searchwill returnNo search term provided.
Accessing Query Strings:
req.querycontains the query parameters sent in the request.- You can pass multiple query parameters, e.g.,
http://localhost:3000/search?title=JavaScript&author=John:
const { title, author } = req.query;
res.send(`Searching for ${title} by ${author}`);Combining Route Parameters and Query Strings
You can use route parameters and query strings together to build more dynamic URLs.
Example:
Let's create a route that captures a user's ID from the path and accepts an optional query string for filtering their books by genre:
app.get('/user/:userId/books', (req, res) => {
const { userId } = req.params;
const { genre } = req.query;
if (genre) {
res.send(`User ID: ${userId}, searching for books in genre: ${genre}`);
} else {
res.send(`User ID: ${userId}, displaying all books`);
}
});- Visiting
http://localhost:3000/user/123/books?genre=fictionreturnsUser ID: 123, searching for books in genre: fiction. - Visiting
http://localhost:3000/user/123/booksreturnsUser ID: 123, displaying all books.
If you found value in this post, don't forget to follow me for more insights on web development, programming tips, and the latest in tech! Your support really helps — please clap for this article if you enjoyed it.
Also, stay connected:
Follow me on Twitter for quick coding tips and updates. Check out my YouTube Channel for deep dives into development projects and tutorials. Join my learning journey on Udemy and master full-stack development, TypeScript, and more! Let's level up our skills together! 👨💻