Skip to Content

Use with Effect UI

Read Effetch's calls in Effect UI's queries and Commands, render them on the server, and keep what the page ships safe to show.

Effect UI, the effect/ui modules in Effect 4.2 and later, loads a component's data with queries and changes it with Commands. Both run an Effect, so an Effetch call fits either one as it is, with no adapter. What they need from you is two schemas, one for what the call returns and one for how it fails, because a page rendered on the server sends both to the browser. This page shows where each schema comes from, and what to change when the page is public.

Effect marks Effect UI as unstable, so its API can change in a minor Effect release. Effetch itself works with Effect 4.0 and later, and only Effect UI needs 4.2.

Read a call in a query

A query takes its success schema from the endpoint's output, and its error schema from Fetch.errorCodec. Its body is the call. The following module defines a client and an endpoint, a query that reads a todo, and a page that shows the todo or why it failed:

import * as  from "effect/Effect";
import * as  from "effect/reactivity/AsyncResult";
import * as  from "effect/Schema";
import { ,  } from "effect/ui";
import {  } from "effect/ui/html";

import {  } from "@monarcode/effetch";
import { , ,  } from "@monarcode/effetch/plugins";

class  extends .<>("ApiProblem")({
  : .,
}) {}

class  extends .<>()("TodoNotFound", {
  : .,
}) {}

const  = .({ : ., : . });

class  extends .<>()("Api", {
  : "/api",
  : ,
  : [(), ({ : "5 seconds" })],
}) {}

const  = .("GET /todos/:id", {
  : ,
  : { 404:  },
});

class  extends .<>()("Todos", , { :  }) {}

/** The codec for a call's errors on `Api`, for every query and Command. */
const  = < extends .ErrorCodecSource>(: ) =>
  .(, {
    : ,
    : [],
    : true,
  });

export class  extends .<>()("todos/GetTodo", {
  : { : . },
  : .,
  : (),
  : "1 minute",
}) {
  static readonly  = this.(
    .(function* () {
      const  = yield* ;
      return ({  }) => .({ : {  } });
    }),
  );
}

const  = .({
  : "TodoPage",
  : .({ : . }),
  : .({}),
  : .,
  : {
    : { : , : ({  }) => ({ : . }) },
  },
}).({
  : () => ({}),
  : () => .,
  : () =>
    .(.., {
      : () => .("Loading…"),
      : () => {
        switch (.) {
          case "TodoNotFound":
            return .(`There's no todo ${.}.`);
          case "HttpError":
            return .(.?. ?? `HTTP ${.}`);
          case "DecodeError":
            return .("The todos came back in a shape this page can't read.");
          case "NetworkError":
          case "TimeoutError":
            return .("The todos can't be reached.");
        }
      },
      : () => .("Something went wrong."),
      : ({ :  }) => .(.),
    }),
});

export const  = .(.(.));

The parts that come from Effetch:

  • success: getTodo.output is the schema the call decodes its response with. A bound endpoint, such as Todos's get, has the same output.
  • apiErrors builds the error schema. It names the client, whose defaultError types HttpError's body, and the errors the client's plugins add, here TimeoutError, which no endpoint or client lists. Leave one out and the query's toLayer doesn't compile, and the message names the missing error. With one helper per client, the list lives next to the plugins, and adding a plugin means changing one line.
  • The query's args stay in the page's terms, { id }, and the body turns them into the call's, { params: { id } }.

In the view, each error has its type, in the browser as on the server. TodoNotFound arrives as an instance of its class, so instanceof works too. HttpError's body is an ApiProblem, or undefined when the response didn't match it, so read it with ?.. The view reads status and body, not message, for a reason Render what both sides have explains.

TodoPage still needs Todos and an HttpClient. Provide the platform's HttpClient where the app starts, and Todos.layer with Api.layer to the page or to the app, as you would for any other service.

Effect UI's query cache doesn't retry a failed query. The client's retry plugin does, inside the call.

Run a call from a Command

A Command changes data, and the same two schemas describe its result. Give make its args, and map both outcomes with Command.match where you issue it:

import * as  from "effect/Effect";
import * as  from "effect/Schema";
import {  } from "effect/ui";

import {  } from "@monarcode/effetch";

class  extends .<>()("Api", { : "/api" }) {}

const  = .({ : ., : . });

const  = .("POST /todos", {
  : .({ : . }),
  : ,
});

class  extends .<>()("Todos", , {
  : ,
}) {}

export class  extends .<>()(
  "todos/CreateTodo",
  {
    : { : . },
    : .,
    : .(, { :  }),
  },
) {
  static readonly  = this.(
    .(function* () {
      const  = yield* ;
      return ({  }) => .({ : {  } });
    }),
  );
}

// In a component's `update`, with its own messages:
export const  = (: string) =>
  .({  }).(
    .({
      : () => `Added ${.}`,
      : () => `Couldn't add it (${.})`,
    }),
  );

In a component, onSuccess and onFailure return that component's messages, and $.run(create(title)) issues it. Commands only run in the browser, so their errors don't go in the page.

Render on the server

A server render runs the page's queries, then writes each settled query into the page's HTML, so the browser adopts it without fetching it again. That includes the queries that failed: each error goes in the page as its query's error schema encodes it, where anyone who opens the page source can read it.

By default, Fetch.errorCodec sends what an error carries, for an RPC client you trust. On a public page, that can show more than you mean to:

{
  "_tag": "HttpError",
  "method": "GET",
  "url": "http://todos.internal:8080/api/todos/7",
  "status": 500,
  "text": "{\"code\":\"db_down\",\"stack\":\"at db.ts:12\"}"
}

The URL names the host your server called, which can be an internal one, and text is the response as the backend sent it, with fields your error schema doesn't declare, such as stack. With redact: true, as apiErrors passes, the same error goes as:

{
  "_tag": "HttpError",
  "method": "GET",
  "url": "/api/todos/7",
  "status": 500,
  "body": { "code": "db_down" }
}

What redact changes:

FieldWithout redactWith redact: true
Every error's urlThe full URLThe path, without the scheme and host
HttpError's bodytext, the raw responsebody, as your error schema encodes it
A DecodeError's messageCan quote the responseA fixed message

A struct or a class, such as ApiProblem, sends only the fields it declares. A schema that takes any JSON, such as Schema.Unknown, sends all of it, and without an error schema no body is sent. HttpError's body comes back typed in the browser either way, and with redact its text is that body as JSON.

The URLs that change are those of HttpError, NetworkError, DecodeError and a TimeoutError given in errors. Your statusErrors errors send their own fields either way. redact needs Effetch 0.1.1 or later on the side that decodes, the browser here. For the full list of what's sent, see Send errors across the wire.

When the browser shouldn't see an error at all, catch it in the query's body and fail with an error of your own, or answer the status with one of your statusErrors, which sends only its own fields.

Render what both sides have

redact changes what's written into the page's state, not the error the server has. The server renders the page's HTML from its own error, with the full URL and the response, and the browser hydrates it with the error it decoded. So a view that renders error.message puts GET http://todos.internal:8080/api/todos/7: HTTP 500 in the HTML, and the browser, whose error has only the path, renders something else and builds those nodes again.

Render the fields that are the same on both sides: _tag, method, status, and body when the call has an error schema, as ApiProblem is here. Leave out each error's url and message, and an HttpError's text. Without an error schema, leave out body too: the server's is the whole parsed response, and redact sends none. A test with ssr, as in Test the pages, fails when a view renders one of them, with a message that the client rebuilt the server's nodes.

Call your own API from the server

A client with a relative baseUrl, such as "/api", calls the page's own origin in the browser. On the server there's no page to resolve it against, so give the server's HttpClient the origin:

import * as  from "effect/Effect";
import * as  from "effect/http/FetchHttpClient";
import * as  from "effect/http/HttpClient";
import * as  from "effect/http/HttpClientRequest";
import * as  from "effect/Layer";

export const  = .(
  .,
  .(
    .,
    .(
      .("http://localhost:3000"),
    ),
  ),
).(.(.));

Provide it where the server renders, in place of the browser's FetchHttpClient.layer. The URLs your calls fail with are then absolute on the server, which is one more reason to redact what the page ships.

HtmlServerHttp.layerHttp builds the services you give it once, and every request shares them. For a service that belongs to one request, such as the signed-in user's cookie on each call, render with HtmlServer.renderToHtml in your own route handler, and build the client's layers there.

Fit retries into the render's budget

A server render waits for its queries up to its budget. A query that's still loading then, a retried call included, renders its loading state, and the browser loads it after hydration. Give the budget room for the retry plugin's waits, or the page renders a loading state that a second attempt would have filled.

Test the pages

FetchTest.layer is an HttpClient, so it can stand in for the platform's under Effect UI's test tools, and your queries, endpoints and client run as they are. The following test renders TodoPage on the server, hydrates it in a fresh document, and checks the error the page shipped:

// @vitest-environment happy-dom
import { ,  } from "@effect/vitest";
import * as  from "effect/Effect";
import * as  from "effect/Layer";
import * as  from "effect/reactivity/AsyncResult";
import * as  from "effect/Schema";
import { ,  } from "effect/ui";
import {  } from "effect/ui/html";
import {  } from "effect/ui/html/testing";
import {  } from "effect/ui/testing";

import {  } from "@monarcode/effetch";
import {  } from "@monarcode/effetch/test";

class  extends .<>()("Api", {
  : "https://todos.internal:8080",
}) {}

const  = .("GET /todos/:id", {
  : .({ : ., : . }),
});

class  extends .<>()("Todos", , { :  }) {}

class  extends .<>()("todos/GetTodo", {
  : { : . },
  : .,
  : .(, { : , : true }),
  : "1 minute",
}) {
  static readonly  = this.(
    .(function* () {
      const  = yield* ;
      return ({  }) => .({ : {  } });
    }),
  );
}

const  = .({
  : "TodoPage",
  : .({ : . }),
  : .({}),
  : .,
  : {
    : { : , : ({  }) => ({ : . }) },
  },
})
  .({
    : () => ({}),
    : () => .,
    : () =>
      .(.., {
        : () => .("Loading…"),
        : () => .("Couldn't load the todo."),
        : ({ :  }) => .(.),
      }),
  })
  .(.(.));

const  = .([
  .(, () =>
    .(.(500, { : "db_down" })),
  ),
]);

.("ships a failed todo without the raw response", () =>
  .(function* () {
    // Renders on the server, then hydrates in a fresh document. It fails
    // when the browser fetches what the server shipped.
    const  = yield* (, { : "7" });
    .(., "Couldn't load the todo.");
    const  = .(.["~query"]);
    .(, '"url":"/todos/7"');
    .(, "todos.internal");
    .(, '"text"');
  }).(
    .,
    .(
      .(
        ..(.(.), .()),
        .(),
      ),
    ),
  ),
);

Two things about time in these tests:

  • it.effect runs on Effect's test clock, which only moves when the test moves it. ssr moves it, up to its budget, 500 milliseconds unless you give one. A client with the retry plugin waits between attempts, so pass ssr the budget your server renders with.
  • A Play (HtmlPlay.make) doesn't move the clock. After an action whose call is retried, move it yourself with TestClock.adjust, from effect/testing/TestClock.

See it in an app

The repository's examples/store-ui is the store example's modules behind an Effect UI app, rendered on the server with Vite and hydrated in the browser. Its queries use one storeErrors helper with redact: true, a 404 reaches the product page as ProductNotFound, and buying the cheapest product is a Command that fails with the workflow's errors and the calls'. Its tests render each page with ssr and drive the purchase with a Play, against FetchTest. Run it with pnpm example store-ui.

What's next

On this page