@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
141 lines (105 loc) • 7.29 kB
Markdown
---
name: current-user
description: >-
Read the signed-in Softr visitor: useCurrentUser and the User type,
context.user in a route's beforeLoad, and context.user inside a server
function handler, where Start types it from the app's registered request
middleware. Covers the null guest, the generated SoftrUserGroups that narrows
group ids to the app's own, reading the visitor's role on the server, and the
fields of their row that softr.json declares in user.properties, such as the
Record ID a filter compares a link to Users with.
metadata:
type: sub-skill
library: softr-sdk
library_version: 1.19.0
---
# The current user
One visitor is resolved once per request and published three ways: as a hook in components, as route context in `beforeLoad`, and on the `context` argument inside a server function. All three read the same `SoftrContext`. Which one you reach for depends only on where the code runs.
## Setup
Nothing to install or register, since the app is already wired. Import from the root entrypoint:
```ts
import { useCurrentUser } from '@softr/sdk'
import type { User } from '@softr/sdk'
```
```ts
type User = {
id: string
email: string
fullName: string
userGroupIds: Array<SoftrUserGroupId> // the app's own group ids
avatarUrl: string | null // their photo; show their initials when null
avatarEditable: boolean // whether auth.updateProfile can change the photo
properties: SoftrUserProperties // the fields softr.json declares under user.properties
}
```
`avatarUrl` is the visitor's picture in the column the app's users connection maps, and the only place their photo comes from. When it is `null`, show initials, and never read the visitor's row in the Users table for a photo instead. `null` is also what a visitor without a photo gets, so it does not say whether a column is mapped; the user maps one in Studio, in the app's users settings, and every place that shows the visitor follows.
## Core Patterns
### In a component: `useCurrentUser()`
```tsx
import { useCurrentUser } from '@softr/sdk'
function Header() {
const user = useCurrentUser()
return <p>{user ? `Hello, ${user.fullName}` : 'Please sign in'}</p>
}
```
It returns `User | null` and never suspends or fetches. It selects off root route context, so it is available anywhere below the root, on the server render and in the browser alike.
### In a route: `context.user`
```tsx
export const Route = createFileRoute('/_app/invoices')({
beforeLoad: guardRoute(pageSettings),
loader: async (opts) => {
assertRouteAccess(pageSettings, opts)
return { name: opts.context.user.fullName, invoices: await getMyInvoices() }
},
head: pageHead(pageSettings),
})
```
A `guardRoute` in `beforeLoad` guarantees a visitor at runtime, but it does not change what the compiler sees. `context.user` is still `User | null` in the loader. `assertRouteAccess(pageSettings, opts)` at the top of the loader narrows it there, so prefer that over `!`. Take `opts` whole: a destructured `context` does not narrow. See [routes-and-visibility](../routes-and-visibility/SKILL.md).
Never pass the visitor's id from a loader into a server function. The loader also runs in the browser, so the id arrives as an argument anyone can set. `getMyInvoices` below reads the visitor from its own `context`.
### In a server function: `context`
```ts
import { createServerFn } from '@tanstack/react-start'
import { defineQuery } from '@softr/sdk'
import { ds } from '@softr/sdk/server'
const myInvoices = defineQuery({
id: 'myInvoices',
// The datasource id from the table's registration on the application — not the table id.
datasourceId: '00000000-0000-0000-0000-000000000001',
fields: { amount: 'Vk9cXm2pSz6Ld4' },
filterFields: { owner: 'Gq5wNt8rJy3Hb1' },
filter: { owner: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
})
const getMyInvoices = createServerFn().handler(async ({ context }) => {
if (!context.user) throw new Error('Not signed in')
return await ds.list(myInvoices)
})
```
Here `owner` links to Users, and `USER:::Rk2mVx9pQa4Lz7` is the visitor's value of the Record ID field that `user.properties` declares. The filter needs no lookup of the visitor. See [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records) for the filter every query of the table takes.
`context.user` is typed. Start derives a handler's context from the app's registered request middleware as well as the server function's own, so there is nothing to import and nothing to cast.
### The visitor's role, in a server function
A server function that answers by role reads the role from `context.user.userGroupIds`, never from an argument. Use it to pick the query of that role, as [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records) shows:
```ts
if (!context.user) throw new Error('Not signed in')
if (context.user.userGroupIds.includes('00000000-0000-0000-0000-00000000000a')) {
// read with the staff query
}
```
`context.user.id` is the visitor's account id, not their row in the users table. A link to Users holds the row id, so a filter on such a link compares it with a Record ID field of the users table, declared in `user.properties`.
### Fields of the visitor's row: `user.properties`
`softr.json` declares the fields of the users table that the app reads for the visitor, under `user.properties`. Each key is an alias you choose, and each value is a field id of the users table:
```json
"user": { "properties": { "recordId": "Rk2mVx9pQa4Lz7", "teams": "Tm6cBq1wZe8Ys4" } }
```
- `context.user.properties.<alias>` and `useCurrentUser()?.properties.<alias>` read the visitor's value, typed as the field reads. `docs/user-properties.md` lists the declared fields, once the declaration is saved.
- A `filter` compares a field with the visitor's value as `USER:::<field id>`, here `USER:::Rk2mVx9pQa4Lz7`. Only a declared field works there.
- The visitor's row id is a Record ID field. When the users table has none, add a field of type `RECORD_ID` to it, then declare it. A create sets an owner link from `context.user.properties.recordId` on the server.
- A field id that the users table does not have throws for every signed-in visitor. Copy the id from the users table's datasource doc.
### Group ids are the app's own
For every group's name and id, read `docs/user-groups.md`. It lists every group the app has, the predefined ones included. Copy an id from there; never derive one from a group's name.
`user.userGroupIds` and every `customGroups` the SDK accepts take only those ids, so an id the app does not have stops compiling. A new group appears in the list once it exists on the app.
## References
- [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): `assertRouteAccess` narrows `context.user` while applying the route's rule
- [region-visibility/SKILL.md](../region-visibility/SKILL.md): rendering a region only to the visitors a rule admits
- [record-queries/SKILL.md](../record-queries/SKILL.md): filtering a query by the visitor, and who really authorizes the read
- [auth/SKILL.md](../auth/SKILL.md): what changes the value `useCurrentUser` returns