Dynamic Routes

Okay in our previous exercise we learned that we can define routes, but we hardcoded the endpoints like /users and what if we wanted something dynamic on these route endpoints, something like /user/321 321 being the user id. This is exactly what we will do in this chapter.

Route Parameters

So express api routes have this concept of Route Parameters, where we can send dynamic data inside the url and capture in our code and use it

Dynamic Route

321 is our dynamic data, it could be anything and our code needs to use this.

So let's see a real example of how we will use this.

app.get('/users/:user', (req, res) => {
    if (req.params.user) {
            user: `The user is ${req.params.user}`,
            id: req.params.user
    } else {
            errorMessage: `Could not find user ${req.params.user}`,

So our req.params will be holding the value of user parameter and we can access it like any javascript object req.params.user