Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Routes and Handlers

Route Parameters and Query Strings

Read dynamic URL segments and query strings in Fastify: request.params, request.query, wildcards, repeated keys, decoding, and how types are coerced.

URLs carry data in two places: the path (/users/42) and the query string (/users?role=admin&page=2). Fastify exposes them as request.params and request.query. Both hold strings unless a schema converts them, which is the single most common source of confusing bugs for newcomers, so this lesson spends time on it.

Path parameters

Mark a dynamic segment with a colon:

JavaScript
app.get('/users/:id', async (request) => {
  return { id: request.params.id };
});

A request to /users/42 gives request.params of { id: '42' }. Notice the string '42'. A route can have several parameters, and a parameter can sit next to static text:

JavaScript
app.get('/users/:userId/posts/:postId', handler);   // /users/7/posts/12
app.get('/flights/:from-:to', handler);             // /flights/LHR-JFK
app.get('/files/:name.:ext', handler);              // /files/report.pdf

Parameters match one segment (they never contain /), and values are URL-decoded for you: /users/a%20b yields 'a b'. Fastify also limits parameter length (maxParamLength, default 100 characters); longer values produce a 404 as if the route did not exist, which protects you from huge inputs.

Node.js Params: several segments and static text between them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Regular expressions and optional parameters

Real Fastify's router can restrict a parameter with a regular expression in parentheses, and can make a trailing parameter optional with ?. These are read-only here because the stand-in router is simpler:

JavaScript
app.get('/orders/:id(^\\d+$)', handler);    // digits only, otherwise 404
app.get('/posts/:slug?', handler);          // matches /posts and /posts/hello

Regular expressions in routes make matching slower (the router can no longer use a plain tree lookup for that segment). Prefer a schema to validate the format and return a helpful 400 instead; see Validating Requests.

Wildcards

An asterisk matches the rest of the path, available as request.params['*']:

JavaScript
app.get('/static/*', async (request) => ({ file: request.params['*'] }));

/static/css/site.css gives { file: 'css/site.css' }. Wildcards are useful for file servers and catch-all proxies. The wildcard must be at the end of the pattern, and a static or parametric route beats it for overlapping URLs.

Node.js A wildcard captures the rest of the path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Query strings

Everything after ? is parsed into request.query:

JavaScript
app.get('/search', async (request) => {
  const { q, page } = request.query;
  return { q, page };
});

GET /search?q=fastify&page=2 produces { q: 'fastify', page: '2' }. Rules to remember:

  • Values are strings ('2', not 2).
  • A key that appears once is a string; repeated keys (?tag=a&tag=b) become an array. So the same parameter can be a string or an array depending on the caller, which is another reason to use a schema.
  • The default parser does not build nested objects: ?filter[status]=open gives the single key 'filter[status]'. If you want nesting, use the querystringParser option with a library such as qs or encode filters as JSON/repeated keys.
  • Percent-encoding is decoded for you (?q=a%20b gives 'a b').
Node.js Everything in a query string is text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Converting types with a schema

Writing Number(request.query.page) everywhere is tedious and easy to forget. A route schema can declare types, and Fastify then validates and coerces the values before your handler runs:

Node.js Schema coercion: strings become numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You get defaults when keys are missing, numbers instead of strings, and a 400 response with a readable message when a value does not fit. Chapter 3 explains schemas fully; for now, remember that un-schema'd params and queries are always strings.

Building URLs safely

When your code creates links, encode user data with encodeURIComponent, and build query strings with URLSearchParams:

JavaScript
const url = `/search?${new URLSearchParams({ q: 'rock & roll', page: 2 })}`;
// /search?q=rock+%26+roll&page=2

String-concatenating raw user input into a URL breaks on characters like &, # and spaces and can allow parameter injection.

Common mistakes

  • Comparing a numeric id with === against the string from request.params (user.id === request.params.id is false when user.id is 42).
  • Trusting that a query key is a string; an attacker can send it twice and your code receives an array.
  • Using parseInt without checking for NaN. Prefer a schema.
  • Putting secrets (tokens, passwords) in the URL. URLs end up in logs, history and referrers; use headers or the body.
  • Using a wildcard route that also matches things you did not intend to serve, such as /static/../secret. File serving needs a vetted plugin (@fastify/static).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of request.params.id for GET /users/42 without a schema?

    URL segments are text. A schema with type integer can coerce it to a number.
  2. 2. What does ?tag=a&tag=b produce in request.query.tag?

    Repeated keys become an array, which is why schemas are useful for fixing the expected shape.
  3. 3. How do you read the part of the URL matched by '' in /static/?

    The wildcard capture is stored under the key '*' in request.params.
  4. 4. Which is the best way to get numeric pagination values from the query string?

    A schema validates, coerces and applies defaults before the handler runs.

Summary

  • :name marks a path parameter; values are decoded strings stored in request.params.
  • * captures the rest of the path as request.params['*'].
  • request.query holds query values as strings; repeated keys become arrays; no nesting by default.
  • A route schema can validate, coerce and default params and query values.
  • Encode URLs you build, and keep secrets out of URLs.

Next: The Request Object