@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
181 lines (137 loc) • 9.91 kB
Markdown
---
name: softr-sdk
description: >-
Entry point for /sdk: its four entrypoints (@softr/sdk, /server,
/client, /vite) and their client-server boundary, softrAuthMiddleware and the
Softr context, embedding the app in another site's iframe, the app's favicon,
and which sub-skill covers each task. Load it when unsure which sub-skill
applies, when touching the wiring, when the user wants the app embedded
elsewhere, or when the favicon set in Studio does not show.
metadata:
type: core
library: softr-sdk
library_version: 1.4.1
---
# Softr SDK core
`/sdk` is how a Softr application talks to Softr. The visitor's identity, who may see a route, records in a datasource, signing in: all of it goes through this package. Everything else is an ordinary TanStack Start app. Routes, server functions, loaders and middleware are Start's, not Softr's.
> **CRITICAL**: The SDK is split across four entrypoints and the split is enforced. `ds` and `auth` exist only on `/sdk/server` and only run inside a `createServerFn` handler. Importing them anywhere else fails the build.
>
> **CRITICAL**: Every route file must declare its settings with `definePage`, guard itself with them in `beforeLoad` and render them in `head`. There is no default and nothing is inherited from a sibling.
>
> **CRITICAL**: The app is already wired. `src/start.ts`, `src/router.tsx` and `src/routes/__root.tsx` register `softrAuthMiddleware` and resolve the session. Do not add a second registration of it. `softrMcpMiddleware` is the one thing an app adds to `src/start.ts` itself — load the `softr-sdk/mcp` sub-skill before doing so.
>
> **CRITICAL**: `ai.generate` and `ai.stream` live on `/sdk/server` and only run inside a `createServerFn` handler. Use `defineAiAction` from `/sdk` to declare the action with the model it runs on, an id copied from the `ai_list_models` tool. Softr runs the model on its own keys; never ask the user for an API key for the app's own AI feature. Load the `softr-sdk/ai` sub-skill for the full pattern.
>
> **CRITICAL**: `workflow.trigger` lives on `/sdk/server` and only runs inside a `createServerFn` handler. Use `defineWorkflow` from `/sdk` to declare the action, then pass it to `workflow.trigger`. Load the `softr-sdk/workflows` sub-skill for the full pattern.
Each sub-skill stands alone for its task and repeats the boundary above, so most work needs **one** sub-skill and not this file. Load this one when you are unsure which sub-skill applies, or when the wiring below is what you are touching. Add a second sub-skill only when the work genuinely crosses that boundary: a page that lists records behind a group restriction needs `record-queries` plus `routes-and-visibility`.
## Entrypoints
| Import | Runs | Holds |
| --- | --- | --- |
| `/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `useIdleTimeout`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `usePushNotifications`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
| `/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration`, `ai` |
| `/sdk/client` | Browser only | `useFileUpload` |
| `/sdk/vite` | Build | `softr()`, already in `vite.config.ts` |
## Sub-Skills
| Task | Sub-Skill |
| --- | --- |
| Add a route, or change who can see one | [routes-and-visibility/SKILL.md](./routes-and-visibility/SKILL.md) |
| Show part of a page to some visitors only | [region-visibility/SKILL.md](./region-visibility/SKILL.md) |
| Read the signed-in visitor | [current-user/SKILL.md](./current-user/SKILL.md) |
| Fetch records from a datasource | [record-queries/SKILL.md](./record-queries/SKILL.md) |
| Chart, aggregate or count records | [charts-and-metrics/SKILL.md](./charts-and-metrics/SKILL.md) |
| Create, update or delete a record | [record-mutations/SKILL.md](./record-mutations/SKILL.md) |
| Trigger a Softr workflow | [workflows/SKILL.md](./workflows/SKILL.md) |
| Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
| Ask an AI model: a summary, an extraction from a document, a classification, a draft, a chat | [ai/SKILL.md](./ai/SKILL.md) |
| Call a connected third-party API (Slack, Stripe, Gmail, …), or an AI model on the user's own provider account | [integrations/SKILL.md](./integrations/SKILL.md) |
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
| Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
| Let visitors turn on push notifications | [push-notifications/SKILL.md](./push-notifications/SKILL.md) |
| Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
## Quick Decision Tree
```text
Adding a page, or changing who may see one?
load softr-sdk/routes-and-visibility
Hiding a region of a page from some visitors?
load softr-sdk/region-visibility
Showing the visitor's name, email or groups?
load softr-sdk/current-user
Putting records on a page, in a table, a list or a detail view?
load softr-sdk/record-queries
Drawing a chart, a stat tile, or any aggregated number?
load softr-sdk/charts-and-metrics
Submitting a form, editing a record, or deleting one?
load softr-sdk/record-mutations
Triggering a Softr workflow from a button or form?
load softr-sdk/workflows
Wiring a login, signup, or sign-out?
load softr-sdk/auth
Asking an AI model for anything: a summary, fields out of a document, a classification, a draft, a chat?
load softr-sdk/ai — Softr runs the model on its own keys, nothing to connect; pick the model from ai_list_models
Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)?
load softr-sdk/integrations
Running a model on the user's OWN provider account, because they chose that for the feature?
load softr-sdk/integrations: its "Calling an AI model" section
Opening the app to an AI assistant over MCP?
load softr-sdk/mcp
Adding an install button, or making the app installable?
load softr-sdk/pwa
Letting visitors turn on push notifications, or "notify users when …"?
load softr-sdk/push-notifications
Showing a date, a time or a number on a page?
load softr-sdk/formatting
The favicon set in Studio does not show?
read "The app's favicon" below
Writing a server function, loader, or middleware in general?
not a Softr concern. Use the TanStack Start skills.
```
## The wiring
Already present in the app. Read it to understand where the visitor comes from. Do not recreate it. `softrMcpMiddleware` is the exception: it is not wired by default and is added here when the app opens itself to AI assistants.
```ts
// src/start.ts: resolves the visitor once per request
import { createCsrfMiddleware, createStart } from '@tanstack/react-start'
import { softrAuthMiddleware } from '@softr/sdk'
export const startInstance = createStart(() => ({
requestMiddleware: [
createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' }),
softrAuthMiddleware(),
],
}))
```
```tsx
// src/routes/__root.tsx: publishes the visitor as route context
import { createRootRouteWithContext } from '@tanstack/react-router'
import { getSoftrContext } from '@softr/sdk'
import type { SoftrContext } from '@softr/sdk'
export const Route = createRootRouteWithContext<SoftrContext>()({
beforeLoad: async () => await getSoftrContext(),
shellComponent: RootDocument,
})
```
```ts
// src/router.tsx: the context before any request has resolved one
import { createRouter } from '@tanstack/react-router'
import { initialSoftrContext } from '@softr/sdk'
import { routeTree } from './routeTree.gen'
export function getRouter() {
return createRouter({ routeTree, context: initialSoftrContext() })
}
```
`SoftrContext` is what all three produce, and what every guard and every server function reads:
```ts
type SoftrContext = {
user: User | null // null means signed out
}
type User = {
id: string
email: string
fullName: string
userGroupIds: Array<SoftrUserGroupId> // the app's own group ids
}
```
## Embedding the app in another site
The published app refuses to load inside another site's iframe. The Studio preview is not affected. When the user asks to embed the app on their site, list that site's origin in `softr.json`: `"allowEmbedding": ["https://partner.com"]`. Ask for the exact origin if you don't have it. Only listed sites can embed the app. Use `["*"]` only when the user wants any site to embed it. Remove the list to block embedding again. Sign-in then works inside the embed. Session cookies switch from SameSite=Lax to None, so the app loses the browser's CSRF protection. Only set it when the user asks. There are two more limits to tell the user: Safari may not keep the visitor signed in, and links from emails (magic link, password reset) open the app in a new tab, not in the embed.
## The app's favicon
The app's favicon is a Studio setting: Settings → General → Favicon. The app shows it, and shows the Softr icon while the setting is empty. The preview shows a change with no publish. The published app shows it after the next publish.
A `rel: 'icon'` link in `head.links` or a `public/favicon.ico` file wins over the setting. While the code has one, the Studio setting has no effect.
When the user asks why the Studio favicon does not show, check the code for an icon. When only the published app lacks it, the app needs a new publish. The published app keeps the code, the SDK and the favicon of its last publish.