blade.im
261

API Routes

Reading data in Blade happens through the use hook in layouts and pages, while modifying data happens through the useMutation hook in interactive components.

To run arbitrary code on the server for reads or mutations, Triggers can be used (most commonly Triggers of type "During").

This means that all interactions with the server from the client are happening through mutations. As a result, no REST APIs are required to be written.

The only case in which you should therefore consider exposing a REST API is if you would like other clients (such as an iOS app or a third-party app) to access your application. For those cases, Blade automatically generates a REST API at the URL path /api that exposes your Triggers through an auto-generated request schema, which can be enabled by adding this export to your Trigger file:

export const exposed = true;

In general, you should never interact with those APIs from your Blade application, since reading data from an API on the client-side causes a network waterfall and thereby a loading animation. Additionally, writing data through an API requires custom client-side state management, which Blade is designed to abstract away through its mutation syntax and automatic state management.

Furthermore, Blade performs numerous internal optimizations for the use and useMutation hooks, such as combining all queries of a page render (even across layouts) into a single database transaction for maximum performance efficiency.

Custom API Routes

It is highly recommended to rely on Blade's auto-generated REST APIs if you would like to expose your application's data to third-party clients, in order to keep your codebase as clean as possible.

In the rare case that you need to mount an API with a specific request signature to your Blade application, you can add a router.ts file at the root of your application and place a Hono app inside of it, which will then be mounted by Blade:

import { Hono } from "hono";

const app = new Hono()
  .post('/some-path', (c) => c.text('Testing'));

export default app;

However, note that paths mounted in this Hono app cannot interface with the rest of your Blade app in any way. They are only meant to be used in edge cases where you cannot rely on Blade's trigger feature. In other words, your Hono app and your Blade app are two different apps running on the same domain.