Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Routes and Handlers

Routing Basics in Fastify

Learn Fastify routing: shorthand methods, the full route() declaration, route options, multiple methods, route priority, 404 handling and duplicate-route errors.

A route connects an HTTP method and a URL to a handler function. Routing is the heart of any web framework, and Fastify keeps it simple: you declare routes with a handful of methods, and a fast router (a radix tree called find-my-way) picks the right one for each request.

This lesson covers the two ways to declare routes, the options a route accepts, how Fastify decides between overlapping routes, and what happens when nothing matches.

Shorthand methods

For every common HTTP method there is a shorthand on the instance:

JavaScript
app.get('/books', async () => [...]);
app.post('/books', async (request, reply) => {...});
app.put('/books/:id', handler);
app.patch('/books/:id', handler);
app.delete('/books/:id', handler);
app.head('/books', handler);
app.options('/books', handler);

Each takes a URL, an optional options object, and a handler. The options sit between the URL and the handler:

JavaScript
app.get('/books', { schema: { querystring: {...} } }, async (request) => {...});

app.all('/ping', handler) registers the handler for all standard methods at once. Use it sparingly: explicit methods are easier to reason about.

Node.js Shorthand routes and methods

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.

A request whose method has no route for that URL gets a 404. (Fastify's 404 for an unknown method is deliberate and simple: the route does not exist.)

The full declaration: app.route()

Shorthands are sugar over app.route(), which takes everything in one object. Use it when you want several methods on one handler, or when route options are long and you prefer one flat object:

JavaScript
app.route({
  method: ['GET', 'HEAD'],
  url: '/status',
  schema: { response: { 200: { type: 'object', properties: { ok: { type: 'boolean' } } } } },
  handler: async () => ({ ok: true }),
});
Option Purpose
method A method name or an array of names
url (or path) The path, with optional parameters and wildcards
handler The function that produces the response
schema Validation and serialization rules (chapter 3)
preHandler, onRequest, ... Hooks that apply to this route only
config Your own per-route data, readable as request.routeOptions.config
bodyLimit Override the body size limit for this route
errorHandler An error handler for this route only
logLevel A different log level for this route
constraints Route by host or version header (advanced)
Node.js route() with several methods and custom config

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.

config is the right place for per-route facts that hooks need, such as "this route requires the admin role" or "do not log this route". A hook can read request.routeOptions.config and act on it, which keeps rules next to the route they describe.

Which route wins?

URLs can overlap. Fastify's rule is simple: the most specific route wins. A static segment beats a parameter, and a parameter beats a wildcard.

JavaScript
app.get('/users/me', ...);      // chosen for /users/me
app.get('/users/:id', ...);     // chosen for /users/42
app.get('/users/*', ...);       // chosen for /users/42/photos

Declaration order does not matter, so you can never break a route by moving it. You will explore parameters and wildcards in the next lesson.

Node.js Static beats parametric

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.

The parametric route was declared first here, and /users/me still goes to the static one.

Trailing slashes and case

By default /books and /books/ are different routes, and /Books differs from /books. Two server options change that: ignoreTrailingSlash: true and caseSensitive: false. A common recommendation is to keep the defaults and redirect or document one canonical form, because accepting many spellings of one URL creates duplicate pages for search engines and for caches.

Duplicate routes fail loudly

Declaring the same method and URL twice is a programming error, and Fastify throws at startup instead of silently picking one:

Node.js A duplicate route is an error

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.

Failing at startup is useful: you find the mistake the moment you run the app, not when a customer hits the second handler that never runs.

The 404 handler

For URLs with no matching route Fastify sends its default JSON 404 ({"message":"Route GET:/x not found","error":"Not Found","statusCode":404}). Replace it with setNotFoundHandler:

JavaScript
app.setNotFoundHandler(async (request, reply) => {
  return reply.code(404).send({ error: 'Not found', path: request.url });
});

You can set different not-found handlers inside different plugin scopes, for example a JSON one for /api and an HTML one for the rest of the site.

Common mistakes

  • Putting the options after the handler. The order is url, options, handler.
  • Expecting order to matter. It does not: specificity decides.
  • Declaring a route in a conditional that runs twice (for example inside an event handler). Routes are registered at startup, not per request.
  • Registering routes after listen(). Fastify locks the route table once the server is ready; add routes before ready.
  • Using app.all for convenience and accidentally exposing methods like DELETE.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do route options go in app.get(url, options, handler)?

    The signature is url, options, handler, with options optional.
  2. 2. Given /users/me and /users/:id, which handles /users/me?

    The router prefers the most specific match, regardless of declaration order.
  3. 3. What happens if you declare GET /ping twice?

    Duplicates raise FST_ERR_DUPLICATED_ROUTE so mistakes surface immediately.
  4. 4. What is route config useful for?

    request.routeOptions.config lets hooks apply rules declared next to the route.

Summary

  • Declare routes with shorthand methods (get, post, ...) or with app.route({...}).
  • The signature is url, options, handler; route() accepts arrays of methods.
  • The most specific route wins; declaration order never matters.
  • Trailing slashes and case matter by default; duplicate routes fail at startup.
  • Customize unknown URLs with setNotFoundHandler.

Next: Route Parameters and Query Strings