For most server side work, Actions should be preferred over routes to offload your boilerplate code to Gadget.

HTTP routes 

What is an HTTP route in Gadget? 

An HTTP route is a server-side function that runs when a URL is visited to produce a response. Gadget matches incoming requests to routes based on each route's URL pattern, and then runs the handler function and sends the reply. Routes in Gadget are constructed using Fastify routes, which means your handlers can use all of Fastify's capabilities including body parsing, validation, middleware support, and the Fastify plugin ecosystem.

When do you use an HTTP route in Gadget? 

HTTP routes are used as an alternative solution to Actions when you need to specifically control the request input and output formats. Usually, Actions are the preferred way of working with your app, as you get an auto-generated, typesafe, performant API for each Action out of the box. HTTP routes work better when you need low-level control, like:

  • handling webhooks from connections not provided by Gadget (Ex. Stripe or Twilio)
  • dynamically generating files (Ex. PDFs or images)
  • serving static files

For example, if you wanted to send an SMS every time a Shopify Product is created in a store, you would use a model action because Gadget has a connection that handles triggers for Shopify's webhooks. But, if you wanted to send an SMS when Stripe sends you a specific webhook, you'd listen to that webhook with an HTTP route and trigger your logic there.

How an HTTP route works in Gadget 

HTTP routes in Gadget are defined as files in the routes folder. Each route has a specific filename which determines the URL path the route will be called at, like GET-hello.js or /[slug]/POST-[id].js. The route will be called whenever a request is made to a URL matching the pattern in the filename.

Route files export a single function accepting a request context object. The request context includes:

  • a request object for inspecting the incoming request headers, body, etc
  • a reply object for managing the response
  • a variety of other objects for working with your backend

Was this page helpful?