Explain Codes LogoExplain Codes Logo

How to get a URL parameter in Express?

javascript
express
middleware
routing
Alex KataevbyAlex Kataev·Sep 10, 2024
TLDR

Retrieve URL parameters in Express with the req.params and fetch query strings with req.query. Here's an illustration:

app.get('/user/:id', function (req, res) { res.send(`UserID: **${req.params.id}**, Filter: **${req.query.filter}**`); });

This constructs a route with a URL parameter (:id) and possibly a query string parameter (filter). Visiting the route with URL like /user/123?filter=admin will echo back the id and filter values.

Route parameters: Dynamic values in your URLs

Express captures dynamic segments in the URL through parameters in routes. Given /product/:id, you could access the ID as req.params.id.

app.get('/product/:id', function (req, res) { // Mr. ID, I presume const productId = req.params.id; });

Pay attention to the parameter name in the route (:id) — it should exactly match the property you try to access on req.params.

Query parameters: Sifting through URLs

Query parameters, falling after the "?" in a URL, aid in filtering, sorting or pagination. You can access these parameters through req.query:

app.get('/search', function (req, res) { const queryTerm = req.query.term; // Ah, the elusive term const sortBy = req.query.sort; // Sort it like it's hot! });

Query strings can feature multiple parameters like /search?term=nodejs&sort=latest, separating each key-value pair by an "&".

Minding URL parameters: Lessons on Express routes

Debugging junction: Routes and parameters

Finding no values where you'd expect them? Your route definitions could have typos. Ensure that parameter names in the URLs and the route handlers are spelt the same way.

Configure paths correctly

Check your route paths in Express. Misconfigured routes could be the roadblock in retrieving parameters.

Express versions: Pick the right guide

Before getting the parameter handling right, ensure you've got your Express version right. The once mighty req.param now stands deprecated in the latest Express versions.

One ring to rule them all: Middleware

For consistent handling of parameters, consider using middleware through app.param(). It can transform or validate parameter values before they reach your routes.

Processing a user ID in middleware would look like this:

// Pre-processing ID in middleware: because someone's got to do it app.param('userId', function (req, res, next, id) { req.userId = id; next(); }); app.get('/user/:userId', function (req, res) { res.send(`Processed UserID: **${req.userId}**`); });

This smart strategy ensures consistent handling of user ID across routes with :userId as a parameter.

Firing up tests and experiments

Test in action: Simulating requests

For debugging, create test cases with various URL structures to ensure req.params and req.query are working as expected.

Word from the wise: Watch the syntax

Remember properties on req.query and req.params are case-sensitive. You need to access them exactly as they appear in the URL or route definition.

Middleware archery: Aiming for accuracy

Leverage middlewares like body-parser or logging functions to parse or log query parameters. It makes debugging a cakewalk.