Fragno

Services

Running functions defined by Fragments on the server.

Services are functions exposed by Fragment authors to users. They are designed to be called on the server, such as in loader functions or background processing.

Basic Usage

The services object is available on the Fragment's server-side instance.

jobs/my-background-process.ts
import { createExampleFragmentInstance } from "../lib/example-fragment-server";

export async function myBackgroundProcess() {
  const { getHashFromHostsFileData } = createExampleFragmentInstance().services;

  setInterval(
    () => {
      const hash = getHashFromHostsFileData();
      console.log("Hash of hosts file:", hash);
    },
    /* every hour */ 1000 * 60 * 60,
  );
}

Calling Route Handlers Directly

In some cases, you may need to call a Fragment's route handler directly from your server-side code and receive a full Response object with headers (such as Set-Cookie). This is particularly useful in frameworks like React Router and Remix where you handle requests in server actions.

Use callRoute() instead of services when you need:

  • Access to response headers (cookies, custom headers, etc.)
  • Full control over the HTTP response
  • To call routes from server actions/loaders

Example

import { authFragment } from "../lib/auth-fragment-server";

export async function action({ request }: Route.ActionArgs) {
  const formData = await request.formData();

  // Call the route handler directly by method and path
  const response = await authFragment.callRoute("POST", "/sign-in", {
    body: {
      email: formData.get("email") as string,
      password: formData.get("password") as string,
    },
  });

  // The response includes any headers set by the fragment (e.g., Set-Cookie)
  return response;
}

API Reference

fragment.callRoute(method, path, options?): Promise<Response>

Parameters:

  • method: HTTP method ("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS")
  • path: Route path (e.g., "/sign-in", "/users/:id")
  • options: Optional parameters
    • body: Request body (for POST, PUT, PATCH, DELETE requests)
    • pathParams: Path parameters (e.g., { id: "123" } for /users/:id)
    • query: Query parameters as object or URLSearchParams
    • headers: Request headers as object or Headers

Returns: A Promise<Response> with the full HTTP response including headers

Type Safety: The method and path parameters are strongly typed based on the fragment's available routes. TypeScript will provide autocomplete and type checking for the path and options.

Unlike services, callRoute() validates input using the route's schema and provides full HTTP semantics including status codes, headers, and response body.