Rayfin

Build a todo app

Build a Fabric-authenticated todo app end to end, from a per-user data model through a React UI to a deploy on Microsoft Fabric.

This walkthrough builds a todo list where every signed-in user sees only their own items — a Todo entity secured with row-level security, a typed data client, and a React UI, ending with a live deploy to a Fabric app. It follows the bundled todoapp template that Rayfin 2.0.0 ships, so you can read each step against the files in your own project.

What you'll build

  • A Todo entity with a policy that scopes every row to the signed-in user.
  • A client module that composes Fabric sign-in and typed data access into one Rayfin client.
  • A small data-access module wrapping client.data.Todo for list, create, update, and delete.
  • A React page wired to that module.
  • A development loop with npm run dev, which runs rayfin dev, applies declared backend state, and starts the frontend locally.
  • A deployed Fabric app serving the built frontend against the live backend.
PromptBuild a per-user todo app with Rayfin
Create a Rayfin 2.0 todo app with `npm create @microsoft/rayfin@latest todo-app -- --template todoapp`, then run `cd todo-app` and `npm install`. In rayfin/data/Todo.ts, keep the @role('authenticated', '*', { policy: (claims, item) => claims.sub.eq(item.user_id) }) decorator so each signed-in user can only read and write their own rows, and change user_id to @text({ max: 128 }) before the first deploy. Confirm that src/services/rayfinClient.ts creates the client with RayfinClient.create, auth: browserSession({ storage: true }) from @microsoft/rayfin-auth, and services: { data: dataService<TodoAppSchema>(), functions: functionsService() }, and that src/services/todos.ts sets user_id from client.auth.getSession() when it creates a todo. Run `npx rayfin login`, then `npm run dev`, and report the local frontend URL. Finally deploy with `npx rayfin up` and report the hosting URL from `npx rayfin up status`.

1. Scaffold a project

npm create @microsoft/rayfin@latest todo-app -- --template todoapp
cd todo-app
npm install

The todoapp template uses the flat layout: Rayfin configuration and entities under rayfin/, React code under src/. Rayfin selects the MSSQL dialect for you; Fabric apps support MSSQL only. On Windows PowerShell, if --template does not reach Rayfin, run the same command with npm.cmd instead of npm.

The template generates these files, among others. Steps 2 through 7 walk through the first six:

FileWhat it does
rayfin/data/Todo.tsDeclares the Todo entity and its row-level security policy.
rayfin/data/schema.tsRegisters the entity for the CLI and types the client.
rayfin/rayfin.ymlDeclares the auth, data, and static-hosting services.
src/services/rayfinClient.tsCreates the Rayfin client once.
src/services/todos.tsWraps client.data.Todo for the UI.
src/pages/HomePage.tsxRenders, adds, toggles, and deletes todos.
src/services/bootstrap.ts, src/services/RayfinAuthService.ts, src/hooks/AuthContext.tsx, src/components/AuthPage.tsxFabric SSO sign-in. See Testing a Rayfin app for how these fit together.
src/__tests__/Vitest tests for the data and auth seams.

2. Define the Todo entity

Entities live under rayfin/data/. Every field gets exactly one type decorator, and the class gets a permission decorator that controls who can read and write rows.

rayfin/data/Todo.ts
import {
  entity,
  role,
  text,
  boolean,
  date,
  uuid,
} from '@microsoft/rayfin-core';

@entity()
@role('authenticated', '*', {
  policy: (claims, item) => claims.sub.eq(item.user_id),
})
export class Todo {
  @uuid() id!: string;
  @text({ min: 1, max: 100 }) title!: string;
  @boolean() isCompleted!: boolean;
  @date() createdAt!: Date;
  @text({ max: 128 }) user_id!: string;
}
  • @role('authenticated', '*', { policy: ... }) grants every CRUD action to signed-in users, but the policy callback narrows every read and write to rows where user_id matches the caller's sub claim — this is the row-level security rule.
  • user_id is @text(), not @uuid(). It isn't a foreign key to another entity; it holds the caller's JWT sub claim, an opaque string identifier. Reserve @uuid() for fields that reference another entity's id through @one()/@many(). See Multi-tenant patterns for more on this distinction and for organization-scoped variations of this pattern.
  • @text({ min: 1, max: 100 }) caps the column width on MSSQL. Every @text() field needs an explicit max — omitting it produces an NVARCHAR(MAX) column that can break GraphQL schema generation. See Deployment troubleshooting.

The template declares user_id as a bare @text(). Add { max: 128 } as shown before your first deploy, so the column is created with a bounded width.

3. Register it in the schema

rayfin/data/schema.ts lists the entity classes the CLI compiles and maps entity names to their classes, so the data service can provide a typed client.data.Todo:

rayfin/data/schema.ts
import { Todo } from './Todo.js';

export type TodoAppSchema = {
  Todo: Todo;
};

export const schema = [Todo];

Add every new entity to this map — both the schema array the CLI reads, and the TodoAppSchema type your frontend imports. Keep the .js extension on relative imports between files under rayfin/; see Project structure.

4. Configure rayfin.yml

The app needs data (MSSQL), auth (Fabric SSO), and static hosting for the built frontend.

rayfin/rayfin.yml
id: todo-app
name: todo-app
version: 1.0.0
services:
  auth:
    enabled: true
    fabric:
      enabled: true
    allowedRedirectUris:
      - http://localhost:5173
  data:
    enabled: true
    dialect: mssql
  staticHosting:
    enabled: true
    folder: dist
    buildCommand: npm run build:fabric
    indexDocument: index.html
    assetAccess: protected

The scaffold sets id and name from your project name. See the rayfin.yml reference for every field. You don't need to add a publishable_key — the CLI retrieves and writes that on your first deploy, and it can't be hand-edited.

5. Wire the client

Changed in 2.0

src/services/rayfinClient.ts creates the client once and exposes it to the rest of the app. In Rayfin 2.0, RayfinClient.create composes the client from an explicit auth adapter and the services the app registers:

  • browserSession({ storage: true }) from @microsoft/rayfin-auth provides client.auth and keeps the session in browser storage.
  • dataService<TodoAppSchema>() from @microsoft/rayfin-data provides the typed client.data.Todo.
  • functionsService() from @microsoft/rayfin-functions provides client.functions.

AppClient is inferred from createClient, so its type always matches what is registered. This file matches the 2.0.0 todo template.

src/services/rayfinClient.ts
import { browserSession } from '@microsoft/rayfin-auth';
import {
  RayfinClient,
  resolveRayfinConfig,
  type RayfinRuntimeConfig,
} from '@microsoft/rayfin-client';
import { dataService } from '@microsoft/rayfin-data';
import { functionsService } from '@microsoft/rayfin-functions';

import type { TodoAppSchema } from '../../rayfin/data/schema';

export interface RayfinClientConfig {
  baseUrl: string;
  publishableKey: string;
  /** True when the API URL points at localhost. Exposed via {@link isLocalBackend}. */
  localDev: boolean;
  /** Absolute same-origin URL for local Functions calls when the Vite adapter is active. */
  functionsBaseUrl?: string;
  /** Fabric coordinates fallback for local dev, where no runtime config is emitted. */
  runtimeConfig?: RayfinRuntimeConfig;
}

function createClient(config: {
  baseUrl: string;
  publishableKey: string;
  functionsBaseUrl?: string;
  runtimeConfig?: RayfinRuntimeConfig;
}) {
  return RayfinClient.create({
    ...config,
    auth: browserSession({ storage: true }),
    services: {
      data: dataService<TodoAppSchema>(),
      functions: functionsService(),
    },
  });
}

export type AppClient = ReturnType<typeof createClient>;
let client: AppClient | null = null;
let localDev = false;

export async function initRayfinClient(
  config: RayfinClientConfig
): Promise<AppClient> {
  if (client) {
    throw new Error('Rayfin client is already initialized.');
  }
  const resolved = await resolveRayfinConfig({
    apiUrl: config.baseUrl,
    publishableKey: config.publishableKey,
    ...config.runtimeConfig,
  });
  client = createClient({
    // resolved.baseUrl/publishableKey are always set: config.baseUrl/publishableKey
    // are non-optional defaults, so the resolve step can only overlay on top of them.
    baseUrl: resolved.baseUrl!,
    publishableKey: resolved.publishableKey!,
    functionsBaseUrl: config.functionsBaseUrl,
    runtimeConfig: resolved.runtimeConfig,
  });
  localDev = config.localDev;
  return client;
}

export function getRayfinClient(): AppClient {
  if (!client) {
    throw new Error(
      'Rayfin client not initialized. Call bootstrapAuth() first.'
    );
  }
  return client;
}

/** True when the app was bootstrapped against a localhost backend. */
export function isLocalBackend(): boolean {
  return localDev;
}

bootstrapAuth() in src/services/bootstrap.ts calls initRayfinClient once at startup with the VITE_RAYFIN_API_URL and VITE_RAYFIN_PUBLISHABLE_KEY values that Rayfin tooling writes, and resolveRayfinConfig() overlays the rayfin.config.json that a deployed app or the Vite development adapter serves. The managed backend is always the Fabric backend that rayfin dev provisions or reuses, so isLocalBackend() stays false in development and production; the localhost branch serves the template's tests.

Because the 2.0 client no longer installs its capabilities, the template's package.json declares @microsoft/rayfin-auth, @microsoft/rayfin-data, and @microsoft/rayfin-functions next to @microsoft/rayfin-client. See Installation.

6. Build the data access layer

Changed in 2.0

Wrap every client.data.Todo call in a small service module. This is also where the app decides whose todos it is writing: user_id is set from the signed-in session on create and is never accepted from the caller. This file matches the 2.0.0 todo template.

src/services/todos.ts
import { getRayfinClient, isLocalBackend } from './rayfinClient';

export interface TodoItem {
  id: string;
  title: string;
  isCompleted: boolean;
  createdAt: Date;
}

// Local-dev fallback: when no Fabric backend is configured, keep todos in
// memory so the sample is fully functional without a database.
let inMemoryTodos: TodoItem[] = [];

export async function getTodos(): Promise<TodoItem[]> {
  if (isLocalBackend()) {
    return [...inMemoryTodos].sort(
      (a, b) => b.createdAt.getTime() - a.createdAt.getTime()
    );
  }

  const client = getRayfinClient();
  const results = await client.data.Todo.select([
    'id',
    'title',
    'isCompleted',
    'createdAt',
  ])
    .orderBy({ createdAt: 'desc' })
    .execute();
  return results as TodoItem[];
}

export async function createTodo(title: string): Promise<TodoItem> {
  if (isLocalBackend()) {
    const todo: TodoItem = {
      id: crypto.randomUUID(),
      title,
      isCompleted: false,
      createdAt: new Date(),
    };
    inMemoryTodos.push(todo);
    return todo;
  }

  const client = getRayfinClient();
  const session = client.auth.getSession();
  if (!session.isAuthenticated || !session.user) {
    throw new Error('Cannot create todo: user is not authenticated.');
  }
  const todo = await client.data.Todo.create({
    title,
    isCompleted: false,
    createdAt: new Date(),
    user_id: session.user.id,
  });
  return todo as TodoItem;
}

export async function updateTodo(
  id: string,
  updates: Partial<Pick<TodoItem, 'title' | 'isCompleted'>>
): Promise<void> {
  if (isLocalBackend()) {
    const todo = inMemoryTodos.find((t) => t.id === id);
    if (!todo) throw new Error('Todo not found');
    Object.assign(todo, updates);
    return;
  }

  const client = getRayfinClient();
  await client.data.Todo.update({ id }, updates);
}

export async function deleteTodo(id: string): Promise<void> {
  if (isLocalBackend()) {
    inMemoryTodos = inMemoryTodos.filter((t) => t.id !== id);
    return;
  }

  const client = getRayfinClient();
  await client.data.Todo.delete({ id });
}
  • getTodos uses the query chain .select([...]).orderBy(...).execute() — select only the fields the UI needs, and always specify an order. In 2.0 the result type contains only the selected fields, with Date fields typed Date | string and booleans typed boolean | 'true' | 'false'. The template casts the rows to TodoItem and the page never reads createdAt; convert values explicitly, for example with new Date(row.createdAt), before you rely on their runtime type. See Querying data.
  • createTodo reads the caller's ID from client.auth.getSession() and sets it as user_id — the server-side policy from step 2 then enforces that this user can only act on rows with a matching user_id.
  • updateTodo and deleteTodo filter by { id }; the Todo entity's policy still applies underneath, so a request for someone else's row matches nothing.
  • In 2.0, update returns only the primary key and the fields you sent, so updateTodo resolves with no value and the page reloads its list instead of reading the row back.

The isLocalBackend() branches keep todos in memory for the template's localhost mode, which its Vitest tests force by mocking src/services/rayfinClient.ts. See Testing a Rayfin app for that test-only seam.

7. Build the React UI

The page loads the list on mount and reloads it after every add, toggle, and delete. Its TodoRow component renders one todo with a completion toggle and a delete button. This file matches the 2.0.0 todo template.

src/pages/HomePage.tsx
import { useCallback, useEffect, useState } from 'react';

import { useAuth } from '@/hooks/AuthContext';
import {
  createTodo,
  deleteTodo,
  getTodos,
  updateTodo,
  type TodoItem,
} from '@/services/todos';

export function HomePage() {
  const { signOut, user } = useAuth();
  const [todos, setTodos] = useState<TodoItem[]>([]);
  const [newTodoTitle, setNewTodoTitle] = useState('');
  const [loading, setLoading] = useState(true);

  const fetchTodos = useCallback(async () => {
    const data = await getTodos();
    setTodos(data);
    setLoading(false);
  }, []);

  useEffect(() => {
    void fetchTodos();
  }, [fetchTodos]);

  const handleAddTodo = async (e: React.FormEvent) => {
    e.preventDefault();
    const title = newTodoTitle.trim();
    if (!title) return;
    setNewTodoTitle('');
    await createTodo(title);
    await fetchTodos();
  };

  const handleToggle = async (id: string, isCompleted: boolean) => {
    await updateTodo(id, { isCompleted: !isCompleted });
    await fetchTodos();
  };

  const handleDelete = async (id: string) => {
    await deleteTodo(id);
    await fetchTodos();
  };

  const pending = todos.filter((t) => !t.isCompleted);
  const completed = todos.filter((t) => t.isCompleted);

  return (
    <div className="bg-gray-50 min-h-screen">
      <header className="flex items-center justify-between px-8 py-5 bg-white border-b border-gray-200">
        <h1 className="text-xl font-bold text-gray-900">Todo App</h1>
        <div className="flex items-center gap-4">
          {user?.email && (
            <span className="text-sm text-gray-600" title={user.email}>
              {user.email}
            </span>
          )}
          <button
            onClick={() => void signOut()}
            className="text-gray-400 hover:text-gray-600 transition-colors text-sm"
            aria-label="Sign out"
          >
            Sign out
          </button>
        </div>
      </header>

      <main className="max-w-xl mx-auto px-4 py-10">
        <form
          onSubmit={(e) => void handleAddTodo(e)}
          className="flex gap-3 mb-8"
        >
          <input
            type="text"
            value={newTodoTitle}
            onChange={(e) => setNewTodoTitle(e.target.value)}
            placeholder="What needs to be done?"
            className="flex-1 rounded-xl border border-gray-300 bg-white px-4 py-3 text-sm text-gray-900 placeholder-gray-400 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
          <button
            type="submit"
            disabled={!newTodoTitle.trim()}
            className="rounded-xl bg-blue-600 px-5 py-3 text-sm font-medium text-white shadow-sm transition-all hover:bg-blue-700 disabled:opacity-40"
          >
            Add
          </button>
        </form>

        {loading ? (
          <p className="text-center text-gray-400 text-sm">Loading...</p>
        ) : todos.length === 0 ? (
          <div className="text-center py-16">
            <p className="text-gray-400 text-sm">
              No todos yet. Add one above!
            </p>
          </div>
        ) : (
          <div className="space-y-6">
            {pending.length > 0 && (
              <section>
                <h2 className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-3">
                  To Do ({pending.length})
                </h2>
                <ul className="space-y-2">
                  {pending.map((todo) => (
                    <TodoRow
                      key={todo.id}
                      todo={todo}
                      onToggle={handleToggle}
                      onDelete={handleDelete}
                    />
                  ))}
                </ul>
              </section>
            )}

            {completed.length > 0 && (
              <section>
                <h2 className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-3">
                  Completed ({completed.length})
                </h2>
                <ul className="space-y-2">
                  {completed.map((todo) => (
                    <TodoRow
                      key={todo.id}
                      todo={todo}
                      onToggle={handleToggle}
                      onDelete={handleDelete}
                    />
                  ))}
                </ul>
              </section>
            )}
          </div>
        )}
      </main>
    </div>
  );
}

function TodoRow({
  todo,
  onToggle,
  onDelete,
}: {
  todo: TodoItem;
  onToggle: (id: string, isCompleted: boolean) => void;
  onDelete: (id: string) => void;
}) {
  return (
    <li className="group flex items-center gap-3 rounded-xl bg-white px-4 py-3 shadow-sm border border-gray-100">
      <button
        onClick={() => onToggle(todo.id, todo.isCompleted)}
        className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${
          todo.isCompleted
            ? 'border-blue-500 bg-blue-500 text-white'
            : 'border-gray-300 hover:border-blue-400'
        }`}
        aria-label={todo.isCompleted ? 'Mark incomplete' : 'Mark complete'}
      >
        {todo.isCompleted && (
          <svg
            className="h-3 w-3"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={3}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M5 13l4 4L19 7"
            />
          </svg>
        )}
      </button>
      <span
        className={`flex-1 text-sm ${
          todo.isCompleted ? 'text-gray-400 line-through' : 'text-gray-900'
        }`}
      >
        {todo.title}
      </span>
      <button
        onClick={() => onDelete(todo.id)}
        className="text-gray-300 hover:text-red-500 transition-colors opacity-0 group-hover:opacity-100"
        aria-label="Delete todo"
      >
        <svg
          className="h-4 w-4"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M6 18L18 6M6 6l12 12"
          />
        </svg>
      </button>
    </li>
  );
}

8. Run the development loop

npx rayfin login
npm run dev

The scaffolded npm run dev script runs rayfin dev, not plain Vite. It provisions or reuses the Fabric backend, applies runtime settings and the Todo schema, writes RAYFIN_PUBLIC_* and framework environment values, then starts the frontend through npm run dev:frontend. Open the local URL it prints and sign in: the Fabric SSO popup flow works from http://localhost:5173 because that origin is listed in allowedRedirectUris.

Restart npm run dev after changing rayfin/data/Todo.ts or rayfin/data/schema.ts so the startup schema apply sees the new model. See Develop locally for ports, flags, and troubleshooting.

9. Deploy

npx rayfin up
npx rayfin up status

rayfin up creates the Fabric app on the first run, applies the Todo schema, builds and uploads the React frontend, and prints the live hosting URL. On later runs it skips the upload when the built files and the deployment target are unchanged since the last successful deploy. New in 2.0 See Deploying with rayfin up for the full workflow, flags, and what gets written to rayfin/.deployments.json.

10. Apply later schema changes

After the first deploy, npm run dev applies schema changes to your backend when it starts, and npx rayfin up applies them as part of a deploy. For a schema-only retry or script, apply the schema on its own:

npx rayfin up db apply

Next steps

Something wrong on this page?Report an issueEdit this page

On this page