Fragno

User Quick Start

Learn how to integrate Fragno Fragments into your application

Edit on GitHub

These are usage instructions for integrating a Fragment, example-fragment, into a project as a user.

Installation

Install the fragment you want to use:

npm i @fragno-dev/example-fragment

Create a server-side instance of the Fragment

Create a server-side instance of the Fragment, somewhere central in your codebase:

This is the place where the Fragment is configured by passing Fragment-specific config fields such as API keys, but also callback methods.

lib/example-fragment-server.ts
import { createExampleFragment } from "@fragno-dev/example-fragment";

export function createExampleFragmentInstance() {
  return createExampleFragment({
    // Pass any Fragment-specific config fields
    someApiKey: process.env.EXAMPLE_API_KEY!,
  });
}

Mount the API routes

The API routes defined in the Fragment should be accessible from your frontend. We do this by creating a "catch-all" API route that will (in this case) forward all requests starting with /api/example-fragment to the Fragment.

Since most frameworks use file-based routing, the location of this file is important.

app/api/example-fragment/[...all]/route.ts
import { toNextJsHandler } from "@fragno-dev/core/next-js";
import { createExampleFragmentInstance } from "@/lib/example-fragment-server";

export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(createExampleFragmentInstance());

Web Standards

Fragno uses the web standard Request and Response objects, so frameworks not listed here will integrate in a very similar manner. The handler function on a Fragment instance takes a request and returns a response.

Create a client-side integration

Again in a central place, but now for the client-side integration:

lib/example-fragment-client.ts
import { createExampleFragmentClient } from "@fragno-dev/example-fragment";
import { useFragno } from "@fragno-dev/core/react";

const exampleFragmentClient = createExampleFragmentClient();
export const exampleFragment = useFragno(exampleFragmentClient);

Mount Route

You're free to mount the backend routes on a different route. In that case it's important to pass the mountRoute option to the client-side integration.

Client-side usage

You can now use the Fragment in any of your components:

components/ExampleComponent.tsx
import { exampleFragment } from "@/lib/example-fragment-client";

export default function ExampleComponent() {
  const { data, loading } = exampleFragment.useData();

  return (
    <div>
      <h1>Example Component</h1>
      {loading ? <div>Loading...</div> : <div>{data}</div>}
    </div>
  );
}