Node and Express - Dynamic Routes
Learn everything about Express in this Node and Express tutorial series. This article goes in depth on Express dynamic routes including query and route parameters.
Table of Contents 📖
- What is a Dynamic Route?
- What are Route Parameters?
- Implementing a Dynamic Route with Express
- Accessing Route Parameters
- Multiple Route Parameters
- What is request.params?
- What about Query Parameters?
- Query Parameters Structure
- Accessing Query Parameters
- Summary
What is a Dynamic Route?
So far in this series, each route we have defined has been static. In other words, the route is just a hardcoded string. However, routes can be dynamic as well. For example, if we had a page that listed all the registered users on our application at /users, clicking on a profile of one of the users, say WittCode, would take us to /users/WittCode. Or if we clicked on the profile of Bill123, it would take us to /users/Bill123.
Now, we don't want to create a route for each user as that would take forever and just isn't feasible. Instead, what we would want to do is have a dynamic route that accepts route parameters.
What are Route Parameters?
Route parameters are variables made from sections of the URL. For example, instead of having /users/WittCode hardcoded, we could just supply a paramter of /users/:username with the route parameter being username. The route parameter is identified by the colon (:) in the URL. Then, the username of the profile we click on in /users replaces :username. So if we clicked on Tom, :username would be replaced with Tom and the path would become /users/Tom. On the other hand, if we clicked on WittCode, :username would be replaced with WittCode and the path would become /users/WittCode.
Implementing a Dynamic Route with Express
Lets change one of our routes in users/index.js to be dynamic.
const express = require('express');
const router = express.Router();
router.get('/', (request, response) => {
response.send('<h1>This is all the users!</h1>')
});
router.get('/:username', (request, response) => {
response.send(`<h1>This is ${request.params.username}'s profile!</h1>`);
});
module.exports = router;
Now, go into the browser and type in "localhost:1234/users/Tom", then type in "localhost:1234/users/WittCode", and we should see the following output.
We made our route dynamic by using the route parameter :username. This means that our route is listening for whatever will be typed in to /users/:username. This was made possible with the code below.
router.get('/:username', (request, response) => {
response.send(`<h1>This is ${request.params.username}'s profile!</h1>`);
});
Remember, we are exporting this router to our main index.js file. There, we are making this router object responsible for all requests to /users. That is why we just have to put /:username and not /users/:username.
Accessing Route Parameters
In the code we wrote above, the contents of the URL are being sent back in a response to the client accessing the webpage. For example, if we type in /users/WittCode it says "This is WittCode's profile!". This is done through using request.params.username. Specifically, request.params allows us to access all the parameters passed to the URL. So, we could even make this route more dynamic.
Multiple Route Parameters
const express = require('express');
const router = express.Router();
router.get('/', (request, response) => {
response.send('This is all the users!')
});
router.get('/:username/:favChannel', (request, response) => {
response.send(`${request.params.username}'s favorite YouTube channel is ${request.params.favChannel}!`);
});
module.exports = router;
Typing out "localhost:1234/users/Tom/WittCode" or "localhost:1234/users/Bruce/MrBeast" would produce the following.
What is request.params?
Request.params is an object that contains the keys passed to the route. For example, here we pass :username and :favChannel. Therefore, these are accessed by request.params.username and request.params.favChannel.
What about Query Parameters?
Route parameters aren't the only thing we can access using Express. We can also access query parameters. Query parameters are extensions of a website's URL that contain information such as search queries, user preferences, etc.
Query Parameters Structure
Query Parameters are in key value pairs, always come after a ?, and are separated by a &. For example, localhost:1234/users/WittCode?theme=dark&product=laptop&sort=ascending. So we have 3 query parameters here: theme, product, and sort. These query parameters have the values dark, laptop, and ascending respectively.
Accessing Query Parameters
Query Parameters are accessed by request.query and then the key of the query parameter. So using our URL from above, the query parameters would be accessed by request.query.theme, request.query.product, and request.query.sort.
But as query parameters can change, lets just loop through all of them and print them out.
router.get('/:username', (request, response) => {
if (request.query) {
Object.entries(request.query).forEach((object) => {
let [key, value] = object;
console.log(`${key} : ${value}`);
})
}
response.send(`<h1>This is ${request.params.username}'s profile!</h1>`);
});
The method Object.entries() returns an array of an object's properties. We then loop through this array and print out the key and value. No matter how many query parameters are supplied we will print them out.
Summary
There we have it! In the next video we are going to be going over Express middleware. If you enjoy these articles please consider donating by clicking support me at the top of this website or subscribe to my YouTube channel WittCode!