React integration
Add a Rayfin AuthProvider, useAuth hook, route guard, Fabric SSO startup, and sign-in button with error display to a React app.
Rayfin's auth client is framework-agnostic.
getSession and onSessionChange work the same everywhere, and every supported sign-in flow resolves to the same opaque session shape.
This page wires those APIs into React with a client module, a hook, a shared provider, and route guarding.
Create the Rayfin client and Fabric options
src/services/rayfinClient.ts creates the shared client and the FabricAuthOptions every hook and component uses.
browserSession() gives the client its client.auth session API.
rayfin dev writes the RAYFIN_PUBLIC_* values and maps them to Vite variables before starting the frontend.
import { RayfinClient } from '@microsoft/rayfin-client';
import { browserSession } from '@microsoft/rayfin-auth';
import type { FabricAuthOptions } from '@microsoft/rayfin-auth-provider-fabric';
import { dataService } from '@microsoft/rayfin-data';
import type { AppSchema } from '../../rayfin/data/schema';
export const client = RayfinClient.create({
baseUrl: import.meta.env.VITE_RAYFIN_API_URL,
publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY,
auth: browserSession({ storage: true }),
services: {
data: dataService<AppSchema>(),
},
});
export type AppClient = typeof client;
export const fabricOptions: FabricAuthOptions = {
workspaceId: import.meta.env.VITE_FABRIC_WORKSPACE_ID,
projectId: import.meta.env.VITE_FABRIC_ITEM_ID,
fabricPortalUrl: import.meta.env.VITE_FABRIC_PORTAL_URL,
tenantId: import.meta.env.VITE_FABRIC_TENANT_ID,
returnOrigin: window.location.origin,
};tenantId lets sign-in open directly in the tenant that owns the Fabric item. New in 2.0
Install @microsoft/rayfin-auth and @microsoft/rayfin-auth-provider-fabric alongside @microsoft/rayfin-client; see Fabric SSO.
A minimal useAuth hook
The smallest useful integration runs best-effort embedded sign-in on mount, keeps the session in state, and exposes a signIn that reports errors instead of swallowing them.
Use this for a small single-page app that does not need a shared provider yet.
import { useCallback, useEffect, useState } from 'react';
import type { OpaqueSession } from '@microsoft/rayfin-auth';
import {
ensureSignedInWithFabric,
initEmbeddedAuth,
} from '@microsoft/rayfin-auth-provider-fabric';
import { client, fabricOptions } from '../services/rayfinClient';
function toMessage(error: unknown): string {
return error instanceof Error ? error.message : 'Sign-in failed.';
}
export function useAuth() {
const [session, setSession] = useState<OpaqueSession | null>(null);
const [error, setError] = useState<string | null>(null);
// On load: best-effort embedded sign-in. initEmbeddedAuth() never rejects; it
// resolves to null when the app is not embedded or embedded sign-in fails.
// Read the session only after it settles: an embedded host may discard a
// stored session before the handoff.
useEffect(() => {
let mounted = true;
let unsubscribe: (() => void) | undefined;
void initEmbeddedAuth(client.auth, fabricOptions).then(() => {
if (!mounted) return;
setSession(client.auth.getSession());
unsubscribe = client.auth.onSessionChange(setSession);
});
return () => {
mounted = false;
unsubscribe?.();
};
}, []);
// On click: embedded handoff or popup sign-in. Call it from a click handler.
const signIn = useCallback(async () => {
setError(null);
try {
const result = await ensureSignedInWithFabric(client.auth, fabricOptions);
setSession(result);
return result;
} catch (err) {
setError(toMessage(err));
return null;
}
}, []);
return {
session,
error,
isAuthenticated: session?.isAuthenticated ?? false,
signIn,
signOut: () => client.auth.signOut(),
};
}Render error on your sign-in screen, for example {error && <p role="alert">{error}</p>}.
Most apps need one more piece: a shared provider so every component sees the same session without re-subscribing.
The rest of this page builds that provider.
Add AuthProvider and useAuth
The provider owns session state, exposes loading and error state during sign-in, and hands the same signIn and signOut functions to every consumer.
Await initEmbeddedAuth() before the initial loading state completes.
This gives Fabric embedded auth and an external embed host a chance to replace a stale stored session before the UI trusts it. Changed in 1.36
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import type { OpaqueSession } from '@microsoft/rayfin-auth';
import {
ensureSignedInWithFabric,
initEmbeddedAuth,
} from '@microsoft/rayfin-auth-provider-fabric';
import { client, fabricOptions } from '../services/rayfinClient';
interface AuthContextValue {
session: OpaqueSession | null;
loading: boolean;
error: string | null;
signIn: () => Promise<OpaqueSession | null>;
signOut: () => Promise<void>;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
function toMessage(error: unknown, fallback: string): string {
return error instanceof Error ? error.message : fallback;
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [session, setSession] = useState<OpaqueSession | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let mounted = true;
let unsubscribe: (() => void) | undefined;
// initEmbeddedAuth() never rejects: it resolves to null when the app is not
// embedded or embedded sign-in fails. Subscribe only after it settles, so a
// stored session is not published before the SDK has checked it.
void initEmbeddedAuth(client.auth, fabricOptions).then(() => {
if (!mounted) return;
setSession(client.auth.getSession());
unsubscribe = client.auth.onSessionChange(setSession);
setLoading(false);
});
return () => {
mounted = false;
unsubscribe?.();
};
}, []);
const signIn = useCallback(async () => {
setError(null);
setLoading(true);
try {
const result = await ensureSignedInWithFabric(client.auth, fabricOptions);
setSession(result);
return result;
} catch (err) {
// error.message is user-safe; the sign-in page renders it.
setError(toMessage(err, 'Sign-in failed.'));
return null;
} finally {
setLoading(false);
}
}, []);
const signOut = useCallback(async () => {
try {
await client.auth.signOut();
setError(null);
} catch (err) {
// The local session is cleared even when the server call fails.
setError(toMessage(err, 'Sign-out failed.'));
} finally {
setSession(client.auth.getSession());
}
}, []);
const value = useMemo<AuthContextValue>(
() => ({
session,
loading,
error,
signIn,
signOut,
isAuthenticated: session?.isAuthenticated ?? false,
}),
[session, loading, error, signIn, signOut]
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth(): AuthContextValue {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}The provider talks to client.auth directly and owns session state.
Every component that calls useAuth() sees the same session without subscribing to onSessionChange itself.
isAuthenticated is true only while the access token is unexpired; see When the access token lapses. Changed in 2.0
Guard routes
A guard component reads useAuth() and redirects based on isAuthenticated.
It shows a loading state until the first session check and embedded startup flow resolve.
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { AuthPage } from './components/AuthPage';
import { useAuth } from './hooks/AuthContext';
import { HomePage } from './pages/HomePage';
function AuthGuard({
children,
requireAuth,
}: {
children: React.ReactNode;
requireAuth: boolean;
}) {
const { isAuthenticated, loading } = useAuth();
if (loading) return <div>Loading…</div>;
if (requireAuth && !isAuthenticated) return <Navigate to="/auth" replace />;
if (!requireAuth && isAuthenticated) return <Navigate to="/" replace />;
return <>{children}</>;
}
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route
path="/auth"
element={
<AuthGuard requireAuth={false}>
<AuthPage />
</AuthGuard>
}
/>
<Route
path="/"
element={
<AuthGuard requireAuth={true}>
<HomePage />
</AuthGuard>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
);
}Add a sign-in button
ensureSignedInWithFabric() can open a popup.
Call it directly from a click handler, not from a page-load effect, and render the error the provider stores.
import { useAuth } from '../hooks/AuthContext';
export function AuthPage() {
const { signIn, loading, error } = useAuth();
return (
<main>
<button onClick={() => void signIn()} disabled={loading}>
Sign in with Microsoft Fabric
</button>
{error && <p role="alert">{error}</p>}
</main>
);
}signIn() never rejects: it stores error.message — for example the FABRIC_AUTH_POPUP_CLOSED message when the user closes the sign-in window — and resolves to null.
See Handle sign-in errors for the error codes.
Wrap the app
Wrap the app in AuthProvider at the entry point.
Keep the static import of @microsoft/rayfin-auth-provider-fabric in a module that loads with the entry point, so the SDK captures ?fabricEmbedded=true before client-side navigation strips it.
import { createRoot } from 'react-dom/client';
import App from './App';
import { AuthProvider } from './hooks/AuthContext';
createRoot(document.getElementById('root')!).render(
<AuthProvider>
<App />
</AuthProvider>
);Note
The popup flow works from a local Vite origin when that origin is in allowedRedirectUris.
The embedded iframe flow runs only when the app is loaded by Fabric or by an external embed host.
In my Rayfin 2.0 React app, add authentication wiring.
In src/services/rayfinClient.ts, create the client with RayfinClient.create({ baseUrl: import.meta.env.VITE_RAYFIN_API_URL, publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY, auth: browserSession({ storage: true }), services: { ... } }), importing browserSession from @microsoft/rayfin-auth. Export FabricAuthOptions built from VITE_FABRIC_WORKSPACE_ID, VITE_FABRIC_ITEM_ID, VITE_FABRIC_PORTAL_URL, VITE_FABRIC_TENANT_ID (as tenantId), and window.location.origin.
Add an AuthProvider that awaits initEmbeddedAuth(client.auth, fabricOptions) on mount (it resolves to null instead of rejecting), then reads client.auth.getSession(), subscribes with client.auth.onSessionChange(...), and clears the initial loading state. Expose { session, loading, error, signIn, signOut, isAuthenticated } through a useAuth() hook. signIn() must call ensureSignedInWithFabric(client.auth, fabricOptions) from a button click path, catch the AuthError, store error.message, and render it on the sign-in page — never swallow sign-in errors.
Add an AuthGuard that redirects unauthenticated users to /auth and authenticated users away from /auth. Do not use onAuthStateChange.Delegated and application access
Which identity each server-side Rayfin surface uses — the signed-in user or the app — and what access to grant at each data source.
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.