Writing a function
Register Rayfin functions with udf.func, use RayfinContext for typed data access and the caller's identity, and keep generated frontend types in sync.
Write functions in the package configured by services.functions.path in rayfin/rayfin.yml. The default is rayfin/functions/.
Note
Functions are generally available in Rayfin 1.36 and are not available in every Fabric region or tenant.
Project layout
After npx rayfin functions init, the functions package lives at services.functions.path. The default path is rayfin/functions/:
rayfin/
data/ ← entity classes shared through TypeScript project references
functions/
src/
function_app.ts ← register functions here
types.ts ← generated AppFunctionsSchema; never hand-edit
secrets.generated.ts ← generated secret registry; never hand-edit
tsconfig.json ← references: [{ "path": ".." }]
package.json
host.json
local.settings.json ← local-only settings and local secret valuesThe scaffolded tsconfig.json uses composite: true with a project reference to rayfin/, so functions can import entity types from rayfin/data/ without duplicating definitions. Install packages used only by functions in the functions package, not the app root.
Register handlers with udf.func
Create one UserDataFunctions instance and register every handler with udf.func(name, handler, []):
import { UserDataFunctions } from '@microsoft/fabric-user-data-functions';
const udf = new UserDataFunctions();
udf.func(
'greet',
(firstName: string, lastName: string): string => {
return `Hello ${firstName} ${lastName}!`;
},
[],
);| Argument | Description |
|---|---|
name | Function name. It becomes the generated schema key and the invocation route. |
handler | Typed TypeScript function. Its parameters and return type are read by typegen. |
connections | Pass []. Audiences are declared in the RayfinContext type annotation instead; see Connections. |
Do not export bare functions and expect Rayfin to discover them. Typegen and deployment metadata are based on udf.func(...) registrations.
Use RayfinContext for server context
Add a RayfinContext parameter when a handler needs Rayfin data, the caller's identity, secrets, tokens, or runtime metadata. Pass your app's data schema type as the first type argument so getDataClient() is typed.
import {
UserDataFunctions,
type RayfinContext,
} from '@microsoft/fabric-user-data-functions';
export type AppSchema = {
Entry: { id: string; message: string };
};
const udf = new UserDataFunctions();
udf.func(
'getEntries',
async (
ctx: RayfinContext<AppSchema>,
): Promise<{ id: string; message: string }[]> => {
const data = ctx.getDataClient();
return await data.Entry.select(['id', 'message']).execute();
},
[],
);
udf.func(
'addEntry',
async (message: string, ctx: RayfinContext<AppSchema>): Promise<void> => {
const data = ctx.getDataClient();
await data.Entry.create({ message });
},
[],
);RayfinContext is injected by the runtime. Typegen strips it from the generated input type, so addEntry is invoked with { message }, not with a context value. Always annotate the context parameter explicitly: typegen recognizes the context by its RayfinContext<...> annotation and treats an unannotated parameter as caller input.
RayfinContext members
| Member | Description |
|---|---|
ctx.getDataClient() | Returns the typed Rayfin data client. It uses the invocation's Rayfin token, so Rayfin DB access stays caller-scoped. |
ctx.user.id | The caller's subject id — the same value as the frontend session.user.id and the claims.sub that data policies compare. See Stamp the owner. New in 2.0 |
ctx.Secrets | Typed secret values declared in rayfin.yml. See Secrets in functions. New in 1.36 |
ctx.Tokens | Typed external-resource tokens for audiences declared on RayfinContext. Deployed functions use the app identity. See Connections. New in 1.36 |
ctx.sql | Raw SQL against the app database, present only on a context annotated RayfinContext<AppSchema> & WithSql. See Raw SQL. New in 2.0 Experimental |
ctx.getClaims() | The caller's typed claims, including custom claims from the app's claims provider. See Dynamic auth claims. New in 2.0 |
ctx.baseUrl | Rayfin endpoint URL for the invocation. |
ctx.accessToken | The invocation's Rayfin token for caller-scoped Rayfin data access. Do not decode it yourself. |
ctx.publishableKey | The Rayfin publishable key. |
ctx.getSecret(name) | Deprecated untyped secret lookup. Use ctx.Secrets.<NAME>. Deprecated in 1.36 |
ctx.getToken(audienceType) | Deprecated untyped token lookup. Use ctx.Tokens.<Audience>. Deprecated in 1.36 |
Import RayfinContext from @microsoft/fabric-user-data-functions, not from @microsoft/rayfin-functions.
Stamp the owner with ctx.user.id
When an entity's policy compares an owner field with claims.sub, set that field from ctx.user.id and write through ctx.getDataClient(), so the caller's permissions still apply:
import {
UserDataFunctions,
type RayfinContext,
} from '@microsoft/fabric-user-data-functions';
export type AppSchema = {
Entry: { id: string; message: string; owner_id: string };
};
const udf = new UserDataFunctions();
udf.func(
'addMyEntry',
async (message: string, ctx: RayfinContext<AppSchema>): Promise<{ id: string }> => {
const entry = await ctx.getDataClient().Entry.create({
message,
owner_id: ctx.user.id,
});
return { id: entry.id };
},
[],
);ctx.user.idis the value data policies evaluate asclaims.suband the frontend sees assession.user.id. Never decodectx.accessTokento find the caller: the decoded subject may not match what the data layer compares.- Reading
ctx.user.idthrows when the function was invoked without a signed-in Rayfin session. - The context exposes only this id — no email, role, access token, or provider identity.
- Treat the id as personal data. It is a persistent pseudonymous identifier: use it only where the app needs caller identity, do not log it unnecessarily or return it to other callers, and do not send it to external services without a privacy purpose and controls. Apply the same retention and deletion rules as other user-linked data.
Import entity types with import type
Functions can share entity types from rayfin/data/ through TypeScript project references. Use a type-only import with the .js extension:
import type { Entry } from '../../data/Entry.js';Do not use a runtime import for entity classes. A runtime import can pull the data decorator runtime into the functions bundle.
Use console.log(...) and console.error(...) for logging. There is no ctx.log API.
Add custom claims at sign-in
The functions package can also register one udf.authClaims(...) provider that computes custom claims when a user signs in. Rayfin calls it during sign-in and token refresh; it is not added to AppFunctionsSchema and cannot be invoked from the frontend. A functions project whose only function is the provider still generates types and deploys. See Dynamic auth claims.
Generated types.ts
The CLI parses udf.func() registrations and writes rayfin/functions/src/types.ts:
export type AppFunctionsSchema = {
greet: {
input: { firstName: string; lastName: string };
output: string;
};
getEntries: {
input: Record<string, never>;
output: { id: string; message: string }[];
};
};Promise<T>return types are unwrapped toT.- Runtime-injected
RayfinContextparameters, includingRayfinContext<AppSchema> & WithSql, are omitted frominput. - The schema is closed: only listed function names are accepted by
client.functions.<name>.invoke(...). - Never hand-edit
types.ts;rayfin functions initandrayfin dev functions applyregenerate it. - Do not import Node.js packages into
types.ts; the frontend TypeScript compiler reads it.
Keep types current while editing
| Command | Typegen behavior |
|---|---|
npx rayfin functions init | Runs typegen once after scaffolding or refresh. |
npx rayfin dev functions apply | Runs typegen once at startup and keeps a watcher running with a [typegen] prefix. Changed in 1.36 |
npx rayfin dev | Starts the same local functions flow when Functions are enabled. Changed in 1.36 |
Before it writes generated files, typegen checks that the installed @microsoft/fabric-user-data-functions can read the runtime metadata the CLI writes, and stops with an npm install command when it cannot. Keep the package at the CLI's exact version; see Match the worker package to the CLI. Changed in 2.0
In my Rayfin 2.0 project, add a function to rayfin/functions/src/function_app.ts.
Register it with `udf.func('<name>', handler, [])`. Import `RayfinContext` from `@microsoft/fabric-user-data-functions` and annotate the context parameter as `RayfinContext<AppSchema>` when the handler reads or writes Rayfin entities. If the entity has an owner field compared with `claims.sub` in its policy, set that field from `ctx.user.id` and write through `ctx.getDataClient()`; never decode `ctx.accessToken`, and do not log the caller id. If you import entity types from rayfin/data/, use `import type` and include the `.js` extension. Never edit rayfin/functions/src/types.ts manually; run `npx rayfin dev functions apply` so typegen updates it. Show the final handler and the generated `AppFunctionsSchema` entry.Functions
Run server-side TypeScript in Rayfin with typed frontend calls, typed secrets, app-identity connections, and raw SQL for queries the data client cannot express.
Secrets in functions
Declare Rayfin secrets with the CLI, read them as typed ctx.Secrets properties, and supply local values through local.settings.json.