@fabrico/sdk
v1.15.72
Published
The official SDK for Fabrico Cloud
Readme
@fabrico/sdk
The official TypeScript SDK for Fabrico Cloud — a backend-as-a-service platform. It gives you a unified client for authentication, file storage, database queries, AI inference, real-time WebSocket channels, and transactional email, all from a single import.
Works in browser and Node.js server environments. Ships with ESM + CJS builds, full TypeScript types, and a React integration package.
Installation
npm install @fabrico/sdk
# or
pnpm add @fabrico/sdk
# or
yarn add @fabrico/sdkPeer dependencies
# React integration
npm install react react-domQuick Start
Browser / Client
import { createClient } from "@fabrico/sdk";
const fabrico = createClient({
publishableKey: "pk_your_publishable_key",
apiKey: "sk_your_api_key", // required for AI, Storage, and DB
});
// Send an OTP
await fabrico.auth.sendOtp("[email protected]");
// Upload a file
const bucket = fabrico.storage.bucket("avatars");
await bucket.upload("profile.png", file);
// Query your database
const users = await fabrico.db.query("SELECT * FROM users WHERE active = ?", [true]);
// Atomic transaction
const results = await fabrico.db.transaction([
{ sql: "INSERT INTO posts (id, title) VALUES (?, ?)", args: ["1", "Hello"] },
{ sql: "UPDATE users SET post_count = post_count + 1 WHERE id = ?", args: [userId] },
]);
// Subscribe to a realtime channel
const channel = fabrico.realtime.channel("public:chat-room");
channel.on((message) => console.log("New message:", message));
// Send an email
await fabrico.email.send({
to: "[email protected]",
subject: "Welcome!",
html: "<h1>Hello!</h1>",
text: "Hello!",
});Server-Side (Any Framework)
The server helpers are framework-agnostic — pass the raw X-Fabrico-Session header string.
import { createClient } from "@fabrico/sdk";
import { getAuth, getUser } from "@fabrico/sdk/server";
const client = createClient({
publishableKey: "pk_...",
apiKey: "sk_...",
});
// Hono
app.get("/me", async (c) => {
const user = await getUser(c.req.header("X-Fabrico-Session") || "", client);
if (!user) return c.json({ error: "Unauthorized" }, 401);
return c.json({ user });
});
// Express
app.get("/me", async (req, res) => {
const user = await getUser(req.headers["x-fabrico-session"] as string || "", client);
if (!user) return res.status(401).json({ error: "Unauthorized" });
res.json({ user });
});
// Next.js
export async function GET(request: Request) {
const user = await getUser(request.headers.get("X-Fabrico-Session") || "", client);
if (!user) return new Response("Unauthorized", { status: 401 });
return Response.json({ user });
}React
import { createClient } from "@fabrico/sdk";
import { FabricoProvider, useUser, SignedIn, SignedOut } from "@fabrico/sdk/react";
const fabrico = createClient({
publishableKey: "pk_your_publishable_key",
});
function App() {
return (
<FabricoProvider client={fabrico}>
<SignedIn><Dashboard /></SignedIn>
<SignedOut><LoginPage /></SignedOut>
</FabricoProvider>
);
}
function Dashboard() {
const { user } = useUser();
return <h1>Welcome, {user?.name}</h1>;
}fetchApi — authenticated fetch wrapper
Use fetchApi from the React context to make authenticated requests. It automatically injects the X-Fabrico-Session header and silently retries on 401 by refreshing the session.
import { useFabrico } from "@fabrico/sdk/react";
function Dashboard() {
const { fetchApi } = useFabrico();
const loadData = async () => {
const res = await fetchApi("/api/protected-route");
const data = await res.json();
};
}Configuration
const fabrico = createClient({
publishableKey: "pk_...",
apiKey: "sk_...",
appUrl: "https://my-preview-url.dev",
});| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| publishableKey | string | Yes | — | Your project's publishable key. |
| apiKey | string | No | "" | Secret API key. Required for AI, Storage, Database, Email, and server-side auth. Never expose on the client. |
| baseUrl | string | No | "https://cloud.fabrico.diy/api" | Base URL for the Fabrico Cloud API. |
| appUrl | string | No | — | External URL of your application. Used to build absolute OAuth redirect URLs, especially when running in an embedded sandbox. |
Entry Points
| Import path | Description | Environment |
|---|---|---|
| @fabrico/sdk | Core client — Auth, AI, Storage, DB, Realtime, Email | Browser & Server |
| @fabrico/sdk/react | React Provider, hooks, conditional components | Browser (React) |
| @fabrico/sdk/server | Framework-agnostic getAuth() / getUser() helpers | Server (any framework) |
Modules
Auth (fabrico.auth)
Email OTP, OAuth (GitHub, Google, Discord), session management, and user profiles.
sendOtp(email)— send a 6-digit code (expires in 10 min)verifyOtp(email, code)— verify and receive tokens; auto-creates users when public signups are enabledgetOAuthUrl(provider, options?)— returns the OAuth initiation URLsignInOAuth(provider, options?)— popup-based OAuth initiation (resolves with tokens)refreshSession(refreshToken)— rotate tokensverifySession(token)— validate an access token (server, requiresapiKey)getSession()— get the current sessionsignOut()— invalidate the sessiongetConfig()— retrieve enabled auth methodsupdateUser(data)— update name/imageadminCreateUser(data)— create a user directly (requiresapiKey)
Database (fabrico.db)
Raw SQL against your project's Turso DB.
const rows = await fabrico.db.query("SELECT * FROM users WHERE active = ?", [true]);
await fabrico.db.execute("INSERT INTO posts (title) VALUES (?)", ["Hello"]);
// Atomic transaction
await fabrico.db.transaction([
{ sql: "INSERT INTO orders (user_id, total) VALUES (?, ?)", args: [userId, 99.99] },
{ sql: "UPDATE users SET order_count = order_count + 1 WHERE id = ?", args: [userId] },
]);AI (fabrico.ai)
An @ai-sdk/openai-compatible provider pointed at /v1/ai.
import { generateText } from "ai";
import { AI_MODELS } from "@fabrico/sdk";
const { text } = await generateText({
model: fabrico.ai(AI_MODELS.chat.KIMI_K2),
prompt: "Hello!",
});Storage (fabrico.storage)
Bucket-based R2 storage.
const bucket = fabrico.storage.bucket("avatars");
await bucket.upload("profile.png", file);
const blob = await bucket.download("profile.png");
const list = await bucket.list({ prefix: "profile" });
await bucket.delete("profile.png");
const url = bucket.getPublicUrl("profile.png");Realtime (fabrico.realtime)
WebSocket channels with auto-reconnect and presence.
const channel = fabrico.realtime.channel("public:chat");
channel.on((data) => console.log(data));
channel.onPresence((e) => console.log(e.event, e.user));
channel.send({ text: "hi" });Email (fabrico.email)
Transactional email. Sender must end with @cloud.fabrico.diy.
await fabrico.email.send({
to: "[email protected]",
subject: "Welcome!",
html: "<h1>Hello!</h1>",
text: "Hello!",
});Cloud (fabrico.cloud) — generic API passthrough
A fetch-like escape hatch for calling any Cloud endpoint directly.
const res = await fabrico.cloud.call("/ai/chat/completions", {
method: "POST",
body: { model: "@fabrico/kimi-k2", messages: [{ role: "user", content: "Hi" }] },
});
const data = await res.json();Server-Side Auth (@fabrico/sdk/server)
Framework-agnostic helpers for validating session tokens on your backend.
Browser (X-Fabrico-Session) → Your Server → Fabrico Cloud (Validation)getAuth(tokenOrHeader, client)— verifies the access token and returns{ user, session }ornull.getUser(tokenOrHeader, client)— shorthand returning just the user.
The helpers accept a raw token string or the full X-Fabrico-Session: <token> header. They are stateless — no cookies, no caching, no framework-specific objects.
If the token is expired, return a 401. The frontend fetchApi will automatically refresh and retry.
Development
pnpm install
pnpm run build # tsup (CJS + ESM + dts) -> dist/
pnpm run dev # tsup --watchLayout
src/
index.ts # FabricoClient facade — wires options into all sub-clients
auth.ts # FabricoAuthClient
ai.ts # createAiClient -> @ai-sdk/openai-compatible
storage.ts # FabricoStorageClient.bucket() -> FabricoBucket
database.ts # FabricoDbClient.execute/query/transaction
realtime.ts # FabricoRealtimeClient.channel() -> RealtimeChannel
email.ts # FabricoEmailClient.send
models.ts # AI_MODELS constants (mirror cloud's model aliases)
react.tsx # FabricoProvider + hooks
server.ts # getAuth/getUser (framework-agnostic X-Fabrico-Session token validation)
tsup.config.ts # three entry points: index, react, serverLicense
MIT
