Seeding data
Populate @anonymous() Rayfin entities from a Node.js script with a publishable-key-only RayfinClient, and what a script needs before it can write @authenticated() rows.
Use RayfinClient from a plain Node.js script to populate development data — the same
client.data.<Entity> calls you use from your frontend, run with tsx instead of in a
browser. A script has no browser session, so on its own it can only send the
publishableKey your project already generates — enough to satisfy an @anonymous() grant,
and nothing else. See Seeding @authenticated() entities
below if the entity you want to seed requires a signed-in user.
What a seed script can authenticate as
Create the client with the suppliedToken adapter from @microsoft/rayfin-client instead
of a browser session. Called without a token, it sends only the publishable key:
RayfinClient.create({
baseUrl: env['RAYFIN_PUBLIC_API_URL'],
publishableKey: env['RAYFIN_PUBLIC_PUBLISHABLE_KEY'],
auth: suppliedToken(),
services: { data: dataService<AppSchema>() },
});suppliedToken replaces the 1.x RayfinServerClient, which was removed in 2.0. It starts no
browser session and gives the client no client.auth. See
@microsoft/rayfin-client for its options.
Without an access token, every request carries only the publishable key. That satisfies an
@anonymous() grant and nothing else — it cannot satisfy @authenticated(), which
requires a valid signed-in user's access token on every request (see
Built-in roles).
A Node.js script cannot sign itself in. Fabric SSO signs a user in through a browser popup or
the Fabric portal iframe (see Fabric SSO) — flows a headless script
cannot drive — and, per Sessions, Rayfin doesn't expose a way to read a
token back out for reuse elsewhere. suppliedToken({ accessToken }) exists for code that
already holds a Rayfin access token issued by another trusted flow, not as a way to sign a
script in.
Service principal credentials (rayfin login --service-principal) don't help here either
— they authenticate the CLI itself for deployment (rayfin up, rayfin up db apply), a
separate concern from a signed-in user's access token that client.data.* calls check.
Seeding an anonymous entity
Reference or lookup data with no owner — content anyone can read, that only you create — is the case a seed script handles cleanly, because it needs no caller identity at all:
import { entity, anonymous, uuid, text } from '@microsoft/rayfin-core';
@entity()
@anonymous('*')
export class FaqCategory {
@uuid() id!: string;
@text({ max: 100 }) name!: string;
}import { entity, anonymous, uuid, text, one } from '@microsoft/rayfin-core';
import { FaqCategory } from './FaqCategory.js';
@entity()
@anonymous('*')
export class FaqEntry {
@uuid() id!: string;
@text({ max: 200 }) question!: string;
@text({ max: 2000 }) answer!: string;
@one(() => FaqCategory) category!: FaqCategory;
}@one() generates the category_id foreign key column, so FaqEntry does not declare it.
Note
A Fabric tenant administrator has to turn on Enable anonymous data access for Fabric
Apps (Preview) before Fabric accepts these @anonymous() permissions. Without it,
applying the schema fails with HTTP 403 ANONYMOUS_DATA_ACCESS_BLOCKED_BY_TENANT_ADMIN —
see Fabric tenant setting for anonymous access.
Read the backend URL and publishable key from rayfin/.env (generated by rayfin up)
rather than hardcoding them — both vary per project and per deployment. Call
client.dispose() when the script finishes so it releases the client's resources:
import { readFileSync } from 'fs';
import { RayfinClient, suppliedToken } from '@microsoft/rayfin-client';
import { dataService } from '@microsoft/rayfin-data';
import type { AppSchema } from '../rayfin/data/schema';
function loadEnv(): Record<string, string> {
const vars: Record<string, string> = {};
for (const line of readFileSync('rayfin/.env', 'utf-8').split('\n')) {
const match = line.match(/^([^#=]+)=(.+)$/);
if (match) vars[match[1].trim()] = match[2].trim();
}
return vars;
}
const env = loadEnv();
const client = RayfinClient.create({
baseUrl: env['RAYFIN_PUBLIC_API_URL'],
publishableKey: env['RAYFIN_PUBLIC_PUBLISHABLE_KEY'],
auth: suppliedToken(),
services: { data: dataService<AppSchema>() },
});
async function seed() {
// Create parent records first, then children that reference their IDs.
const category = await client.data.FaqCategory.create({ name: 'Billing' });
await client.data.FaqEntry.create({
question: 'How do I change my plan?',
answer: 'Open Settings → Billing and choose a new plan.',
category: { id: category.id },
});
}
seed()
.catch(console.error)
.finally(() => client.dispose());Install the packages the script imports, then run it with tsx:
npm install @microsoft/rayfin-client @microsoft/rayfin-data
npx tsx scripts/seed.tsOr wire it into package.json for a shorter command:
{
"scripts": {
"seed": "tsx scripts/seed.ts"
}
}npm run seedCreate parents before children. A @one() relationship needs the parent's id to
exist first — create the FaqCategory before the FaqEntry that references it, as shown
above. create returns the new row's id, which is all the child needs. See
Relationships for how @one() / @many() work.
Seeding a single entity
For an entity with no relationships, the script is shorter — it only creates rows:
import { readFileSync } from 'fs';
import { RayfinClient, suppliedToken } from '@microsoft/rayfin-client';
import { dataService } from '@microsoft/rayfin-data';
import type { AppSchema } from '../rayfin/data/schema';
function loadEnv(): Record<string, string> {
const vars: Record<string, string> = {};
for (const line of readFileSync('rayfin/.env', 'utf-8').split('\n')) {
const match = line.match(/^([^#=]+)=(.+)$/);
if (match) vars[match[1].trim()] = match[2].trim();
}
return vars;
}
const env = loadEnv();
const client = RayfinClient.create({
baseUrl: env['RAYFIN_PUBLIC_API_URL'],
publishableKey: env['RAYFIN_PUBLIC_PUBLISHABLE_KEY'],
auth: suppliedToken(),
services: { data: dataService<AppSchema>() },
});
async function seed() {
const names = ['Billing', 'Account', 'Troubleshooting'];
for (const name of names) {
await client.data.FaqCategory.create({ name });
}
}
seed()
.catch(console.error)
.finally(() => client.dispose());Seeding @authenticated() entities
Most application data is not anonymous — anything with a user_id/owner_id and a
row-level policy, like the Todo entity in Build a todo app, is
scoped with @authenticated(). A seed script cannot sign itself in as a user, so a
publishable-key-only client like the ones above cannot write into an entity that requires
authentication.
A scripted path exists only when your code already holds a delegated Microsoft Entra access token for a user: Sign in with an Entra token exchanges it for a Rayfin session as that user, and the rows you create are written as that user and checked against your policies. Rayfin does not acquire the Entra token for you.
Otherwise, create rows like that the way a real signed-in user would — through the running
app itself, signed in with Fabric SSO — rather than through a script. Do not hand-roll an
Authorization header or fabricate a token shaped like a Fabric-issued JWT: there is no
supported way to mint a valid one outside Fabric's sign-in flows, and Rayfin rejects anything
that doesn't verify against its own signing keys.
In my Rayfin 2.0 project, I have an FaqCategory entity (id, name) and an FaqEntry entity (id,
question, answer, with a @one(() => FaqCategory) relationship named category), both decorated
@anonymous('*') as public reference data with no owner. Write a Node.js seed script at
scripts/seed.ts that reads RAYFIN_PUBLIC_API_URL and RAYFIN_PUBLIC_PUBLISHABLE_KEY from
rayfin/.env and creates the client with RayfinClient.create({ baseUrl, publishableKey, auth:
suppliedToken(), services: { data: dataService<AppSchema>() } }), importing RayfinClient and
suppliedToken from @microsoft/rayfin-client and dataService from @microsoft/rayfin-data. Call
suppliedToken() with no token, since this client only needs to satisfy the anonymous role.
Create one FaqCategory named "Billing", then one FaqEntry in that category with
category: { id: category.id }, and call client.dispose() when the script finishes. Add a
"seed" script to package.json that runs it with tsx.