@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
500 lines (364 loc) • 22.8 kB
Markdown
---
name: auth
description: >-
Sign a visitor in, out or up from a server function with auth from
/sdk/server: password, code, Google and magic link, sign-up and its
confirmation, the emailed-code and authenticator-app steps, password reset
links, updateProfile, getAuthSettings and useAuthSettings, and
useIdleTimeout for "End session if idle". Covers the Result shape, its error
codes, and toReturnPath.
metadata:
type: sub-skill
library: softr-sdk
library_version: 1.4.1
---
**Boundary.** `auth` lives on `/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
# Auth
`auth` is what changes who the visitor is.
Reading how the app signs people in:
| Call | Does |
| --- | --- |
| `auth.settings()` | Returns the sign-in and sign-up settings the builder chose in Studio |
Signing in:
| Call | Does |
| --- | --- |
| `auth.signIn({ email, password })` | Signs a visitor in with an email and password |
| `auth.sendSignInCode({ email })` | Emails a one-time sign-in code |
| `auth.signInWithCode({ email, code })` | Signs a visitor in with that code |
| `auth.signInWithGoogle({ email, token, fullName? })` | Signs a visitor in with a Google id token the browser obtained, creating the account the first time |
| `auth.signInWithMagicLink({ token })` | Signs a visitor in with the token from a magic link they followed |
Signing up:
| Call | Does |
| --- | --- |
| `auth.signUp({ email, name? })` | Emails a verification code, creates no account |
| `auth.confirmSignUp({ email, code, name?, password? })` | Creates the account and signs the visitor in |
Setting a password from an emailed link, for a password reset or an invitation:
| Call | Does |
| --- | --- |
| `auth.requestPasswordReset({ email })` | Emails a link to set a new password |
| `auth.checkPasswordLink({ token })` | Returns the `email` the link was sent to, and leaves the link usable |
| `auth.setPasswordWithLink({ token, password })` | Sets the password and signs the visitor in |
Signing out:
| Call | Does |
| --- | --- |
| `auth.signOut()` | Ends every session that visitor has in this app, on every device |
Finishing a sign-in that wants a code from the visitor's inbox:
| Call | Does |
| --- | --- |
| `auth.verifyEmailCode({ code })` | Answers it with the code that was emailed |
| `auth.resendEmailCode()` | Emails that code again |
Finishing a sign-in that wants an authenticator app:
| Call | Does |
| --- | --- |
| `auth.verifyAuthenticator({ code })` or `({ backupCode })` | Answers the challenge with the code their app shows |
| `auth.startAuthenticatorSetup()` | Hands back a QR code for enrolling an app |
| `auth.confirmAuthenticatorSetup({ code })` | Enrols it on its first code, and returns the backup codes once |
| `auth.skipAuthenticatorSetup()` | Skips enrolment, where the app allows skipping |
Changing an authenticator from a settings page:
| Call | Does |
| --- | --- |
| `auth.sendAuthenticatorResetCode()` | Emails the code the next two ask for |
| `auth.resetAuthenticator({ code })` | Unpairs the app, so a new one can be enrolled |
| `auth.removeAuthenticator({ code })` | Turns the authenticator off |
Changing the visitor's own profile:
| Call | Does |
| --- | --- |
| `auth.updateProfile({ fullName?, avatar? })` | Changes their name, their photo, or both |
| `auth.removeAvatar()` | Removes their photo |
## Setup
`auth` is server-only, so every call sits inside a `createServerFn` handler:
```ts
import { createServerFn } from '@tanstack/react-start'
import { redirect } from '@tanstack/react-router'
import { auth } from '@softr/sdk/server'
import { z } from 'zod'
```
Pass a zod schema straight to `.validator`. Start accepts it directly and types `data` from it:
```ts
const Credentials = z.object({ email: z.string(), password: z.string() })
const signIn = createServerFn({ method: 'POST' })
.validator(Credentials)
.handler(async ({ data }) => { /* data is { email, password } */ })
```
Keep the schema to the shape the call needs. Softr is what decides whether an email exists, whether a password is right, and whether a code is still valid, and it answers with the codes below. A second set of rules in the app is just a second place to be wrong.
A form that posts `FormData` instead validates with a function, since a zod object schema does not accept `FormData`:
```ts
.validator((fields: FormData) => Credentials.parse(Object.fromEntries(fields)))
```
Every call except `signOut` answers with a `Result` rather than throwing on something the visitor can fix. `signOut` returns nothing.
```ts
type Result<T> =
| { success: true; data: T }
| { success: false; error: { code: AuthErrorCode; message: string } }
type AuthErrorCode =
| 'invalidCredentials' // signIn, signInWithGoogle, signInWithMagicLink: wrong password, or a token Softr would not take
| 'tooManyAttempts' // any call: rate limited
| 'emailTaken' // signUp, confirmSignUp: that email already has an account
| 'invalidDetails' // signUp, sendSignInCode, setPasswordWithLink: details Softr rejected
| 'invalidCode' // any call that takes a code: wrong or expired
| 'notAuthenticated' // a call that needs a signed-in visitor, made by one who is not
| 'emailDomainNotAllowed' // signUp, signInWithGoogle: the app lets only some email domains sign up, and this is not one
| 'linkExpired' // checkPasswordLink, setPasswordWithLink: the link is used, expired or no longer valid
```
Branch on `error.code` with a `switch` and write your own wording. Never put `error.message` in front of the visitor.
`code` is typed as every code the SDK produces, not the ones a given call can answer, so a `switch` needs a `default` even when the cases above it are complete. Give it a message rather than leaving it out.
## Render only the methods the app has enabled
`getAuthSettings` from `/sdk` loads which ways in the app offers. Call it in the loader of a route that sits above every page needing it, and wrap that route's children in `AuthSettingsProvider`. If the auth pages share a layout route, that route is the usual place:
```tsx
import { AuthSettingsProvider, getAuthSettings } from '@softr/sdk'
// in the route options
loader: () => getAuthSettings(),
staleTime: 60_000,
// in the route's component
const authSettings = Route.useLoaderData()
return (
<AuthSettingsProvider value={authSettings}>
<Outlet />
</AuthSettingsProvider>
)
```
Any page or component below it reads them with `useAuthSettings()`, which needs the provider above it:
```tsx
const options = useAuthSettings()
return options.password && <PasswordForm />
```
Each field names the `auth` call it unlocks:
| Field | When on, offer |
| --- | --- |
| `password` | the password form, `auth.signIn` |
| `emailCode` | sign-in with a code, `auth.sendSignInCode` |
| `magicLink` | the route that calls `auth.signInWithMagicLink` |
| `google` | a Google button started with `google.clientId`. `null` means no Google. Never hardcode a client id. |
| `signUp` | sign-up, `auth.signUp` |
| `strongPasswords` | the strong-password rules, on every form that sets a new password. Check the password against them before submitting. |
When the builder turns sign-in off, every field is off.
Render nothing for a field that is off. A page for a flow that is off answers 404 from its loader. Throw `notFound()` there, never from the component: a component that renders nothing answers 200 with an empty page. `auth.settings()` returns the full settings, for a server function that needs more than these.
## A successful sign-in is not always a session
`signIn`, `signInWithCode`, `signInWithGoogle`, `signInWithMagicLink`, `setPasswordWithLink` and `confirmSignUp` all answer the same two ways:
```ts
{ status: 'signedIn', user }
{ status: 'authenticatorRequired', step: 'verify' | 'setup' | 'setupOptional' }
```
`signedIn` is a session. Send the visitor to the return target, see [Landing after sign-in](#landing-after-sign-in).
`authenticatorRequired` is not. The app asks for an authenticator app as well, and the visitor has no session until they produce one. Redirecting into the app here sends them to a page they cannot see, and a guarded page bounces them back to the login form with nothing on screen explaining why.
Show the second factor as the next step of the page that signed them in, not on a page of its own. Pick what it shows by `step`:
| `step` | Show them | Finish with |
| --- | --- | --- |
| `verify` | a code field | `auth.verifyAuthenticator({ code })`, or `({ backupCode })` |
| `setup` | the QR from `auth.startAuthenticatorSetup()` | `auth.confirmAuthenticatorSetup({ code })` |
| `setupOptional` | the same, plus a skip button | the same, or `auth.skipAuthenticatorSetup()` |
Those calls take only what the visitor typed. The sign-in they finish is the one already in progress for this browser, so nothing has to be carried through the UI. It does not stay open indefinitely, and a visitor who abandons the page signs in again from the start.
An app with no authenticator app configured never answers `authenticatorRequired`. The type still has both arms either way, so `result.data.user` does not exist until you have narrowed on `status`.
`signIn` has a third answer, `{ status: 'emailCodeRequired' }`, for an app that asks a password sign-in for a code from the visitor's inbox as well. The code is already on its way. Show a code field as the next step and finish with `auth.verifyEmailCode({ code })`, see [Finishing a sign-in that needs an emailed code](#finishing-a-sign-in-that-needs-an-emailed-code). That call answers like `signIn` does, so an app that also wants an authenticator app goes on to that step after it.
## Landing after sign-in
A guard that turns a signed-out visitor away sends them to the page `softr.json` names for that, usually the login page. The page they wanted rides along in the search param named for the login page. `toReturnPath` from `/sdk` reads it back:
```tsx
import { useLocation, useNavigate } from '@tanstack/react-router'
import { toReturnPath } from '@softr/sdk'
const location = useLocation()
const navigate = useNavigate()
// once the visitor is signed in
await navigate(toReturnPath(location))
```
A loader that signs the visitor in throws it instead: `throw redirect(toReturnPath(location))`, with the loader's own `location`.
It goes to the page they wanted when that is a path on this app. Otherwise it goes where `auth.guard.alreadyAuthenticated` in `softr.json` points, or to `/` when that setting throws. It reloads the page, so the app sees the visitor as signed in. Pass its answer as is. Never read the param yourself: anyone can put a link to another site in it.
Every page that ends a sign-in lands there: login, sign-up, the magic link, a password link and the second-factor step. A link from one auth page to another keeps the search param, or the target is lost on the way.
## Core Patterns
### Sign in
```ts
const signIn = createServerFn({ method: 'POST' })
.validator(Credentials)
.handler(async ({ data }) => {
const result = await auth.signIn(data)
if (!result.success) {
switch (result.error.code) {
case 'invalidCredentials':
return { message: 'Please ensure your email and password are correct.' }
case 'tooManyAttempts':
return { message: 'Too many attempts. Please try again in a few minutes.' }
default:
return { message: 'Could not sign you in. Please try again.' }
}
}
return { message: null, outcome: result.data }
})
```
The component takes it from there:
```tsx
import { useServerFn } from '@tanstack/react-start'
const submit = useServerFn(signIn)
const answer = await submit({ data: { email, password } })
if (answer.message !== null) return setMessage(answer.message)
if (answer.outcome.status === 'authenticatorRequired') {
return setStep({ name: 'secondFactor', opensOn: answer.outcome.step })
}
if (answer.outcome.status === 'emailCodeRequired') {
return setStep({ name: 'emailCode' })
}
await navigate({ href: target })
```
Four exits: a message for the form to render, the emailed-code step, the authenticator step, the return target.
A server function that throws `redirect` needs the hook. Call the imported function directly and the throw never reaches the router, so a successful sign-in leaves the visitor on the form.
A login page is a `NON_LOGGED_IN_USERS` route, which is what keeps an already-signed-in visitor off it. See [routes-and-visibility](../routes-and-visibility/SKILL.md).
### Sign in with an emailed code
For an app that signs people in with a code instead of a password.
```ts
// Step 1: emails the code.
const sent = await auth.sendSignInCode({ email })
// Step 2: same two-armed result as signIn.
const result = await auth.signInWithCode({ email, code })
```
Step one succeeds whether or not that address has an account, so the form cannot be used to find out who is registered. Say "check your email" either way, and never branch the UI on it.
### Sign in with Google
```ts
const result = await auth.signInWithGoogle({
email,
token, // the id token Google Identity Services handed the page
fullName, // names a first-time visitor, ignored for an existing one
})
```
Only an id token works. An access token, a token minted for another app, and an email that does not match it all fail as `invalidCredentials`.
### Sign in with a magic link
For the route the link in the email points at.
```ts
// Same two-armed result as signIn.
const result = await auth.signInWithMagicLink({ token })
```
The token keeps working after it is used, so anyone holding the link can sign in as that visitor. Never log it, and redirect away from the URL that carried it.
### Set a password from an emailed link
A password reset and an invitation both email a link with a token. The same two calls redeem either.
```ts
// The forgot-password form. Succeeds whether or not the address has an account.
const sent = await auth.requestPasswordReset({ email })
// The loader of the page the link opens. Show an expired message on linkExpired, before any form.
const link = await auth.checkPasswordLink({ token })
// The form's submit. Same two-armed result as signIn.
const result = await auth.setPasswordWithLink({ token, password })
```
Say "check your email" after `requestPasswordReset` either way, and never branch the UI on it.
`setPasswordWithLink` uses up the link on any success, `authenticatorRequired` included, and signs the visitor out everywhere else.
### Sign out
```ts
const signOut = createServerFn({ method: 'POST' }).handler(async () => {
await auth.signOut()
throw redirect({ to: '/login', search: { signedOut: true } })
})
```
`signedOut` keeps a login page that sends visitors straight to single sign-on from signing them back in at once: see [references/single-sign-on.md](./references/single-sign-on.md). If the redirect fails the type check with `'signedOut' does not exist`, the app's login route does not declare it yet. Add `signedOut: z.boolean().optional().catch(undefined)` to that route's `validateSearch`. Never remove `signedOut` from the redirect to pass the check.
It returns nothing and has no failure the visitor can act on, so send them somewhere and let the redirect re-resolve the context. It ends every session that visitor has in this app, on every device, so a "sign out of this device only" button is not something you can build on it. For Studio's "End session if idle", call `useIdleTimeout()` from `/sdk` once in `RootDocument` in `src/routes/__root.tsx`, next to `useUserTimezone()`. It signs out this browser only and sends the visitor to `/`. Don't build your own idle timer.
### Sign up, in two steps
```ts
const Details = z.object({ email: z.string(), name: z.string() })
const Confirmation = Details.extend({ password: z.string(), code: z.string() })
// Step 1: emails a code. No account exists yet.
const startSignUp = createServerFn({ method: 'POST' })
.validator(Details)
.handler(async ({ data }) => {
const result = await auth.signUp(data)
if (!result.success) {
switch (result.error.code) {
case 'emailTaken':
return { message: 'That email already has an account.' }
case 'invalidDetails':
return { message: 'Please check the details and try again.' }
case 'emailDomainNotAllowed':
return { message: 'Sign-up is open only to some email domains, and yours is not one.' }
case 'tooManyAttempts':
return { message: 'Too many attempts. Please try again in a few minutes.' }
default:
return { message: 'Could not start the sign-up. Please try again.' }
}
}
return { message: null } // now show the code field
})
// Step 2: creates the account and signs the visitor in.
const finishSignUp = createServerFn({ method: 'POST' })
.validator(Confirmation)
.handler(async ({ data }) => {
const result = await auth.confirmSignUp(data)
if (!result.success) {
switch (result.error.code) {
case 'emailTaken':
return { message: 'That email already has an account. Please sign in instead.' }
case 'invalidCode':
return { message: 'That code is not valid. Please try again.' }
case 'tooManyAttempts':
return { message: 'Too many attempts. Please try again in a few minutes.' }
default:
return { message: 'Could not finish the sign-up. Please try again.' }
}
}
return { message: null, outcome: result.data } // handled as sign-in's is
})
```
The UI has to carry email into step two, plus the name if step one collected one. `confirmSignUp` is the only call that creates the account.
`password` is what the account is created with. Leave it out only for an app that signs people in with an emailed code. An app that expects a password rejects a sign-up without one, and an app that does not expect one rejects a sign-up that sends it.
### Finishing a sign-in that needs an emailed code
After `signIn` answers `emailCodeRequired`, the visitor owes the code that was just emailed to them:
```ts
// invalidCode for a wrong or expired code, otherwise the same two-armed result as signIn.
const result = await auth.verifyEmailCode({ code })
// For a "Resend code" link.
const sent = await auth.resendEmailCode()
```
Send `authenticatorRequired` on to the authenticator step, never into the app.
Asking for a resend too soon sends nothing and still succeeds. It answers `notAuthenticated` once the sign-in has run out of time, and the visitor then signs in again from the start.
### Finishing a sign-in that needs an authenticator app
On `step: 'verify'` the visitor already has an app, and owes a code from it:
```ts
const verify = createServerFn({ method: 'POST' })
.validator(z.object({ code: z.string() }))
.handler(async ({ data }) => {
const result = await auth.verifyAuthenticator(data)
if (!result.success) {
switch (result.error.code) {
case 'invalidCode':
return { message: 'That code is not valid. Please try again.' }
case 'tooManyAttempts':
return { message: 'Too many attempts. Please try again in a few minutes.' }
default:
return { message: 'Could not check that code. Please try again.' }
}
}
return { message: null } // signed in: the component goes to the target
})
```
A visitor without their phone sends `{ backupCode }` instead of `{ code }`. Each backup code works once.
On `step: 'setup'` or `'setupOptional'` they have no app yet:
```ts
const start = await auth.startAuthenticatorSetup()
if (!start.success) return { message: 'Could not start setup. Please try again.' }
start.data.otpauthUri // what an authenticator app reads
start.data.qrPngBase64 // the same URI as a PNG, for
// <img src={`data:image/png;base64,${qrPngBase64}`} />
```
Neither of those enrols anybody. `confirmAuthenticatorSetup` does, once it accepts a first code:
```ts
const done = await auth.confirmAuthenticatorSetup({ code })
if (done.success) {
return { backupCodes: done.data.backupCodes } // returned once. Render them now, nothing fetches them again.
}
```
The visitor is signed in while the codes are on screen, often on a page only signed-out visitors may see. Invalidating the router or navigating re-runs that page's guard, which sends them away and the codes are gone. Do neither until they click "Continue", then go to the target.
Call `startAuthenticatorSetup` again to hand back a fresh QR code, for a visitor who lost the first one. Only the newest one enrols them.
`skipAuthenticatorSetup` finishes the sign-in without enrolling, and only on `setupOptional`. Later sign-ins stop asking.
### Changing an authenticator from a settings page
```ts
await auth.sendAuthenticatorResetCode() // emails the code the next two ask for
await auth.resetAuthenticator({ code }) // unpairs the app, so a new one can be enrolled
await auth.removeAuthenticator({ code }) // turns the authenticator off
```
All three need a signed-in visitor and answer `notAuthenticated` when there is not one. Both changes ask for a code from the visitor's inbox as well, because both change how that visitor signs in.
After a reset, enrol the new app with `startAuthenticatorSetup` and `confirmAuthenticatorSetup`, which is also where the new backup codes come from. After a removal, an app that requires an authenticator asks the visitor to set one up again on their next sign-in.
### Changing the visitor's name and photo
```ts
const result = await auth.updateProfile({ fullName: 'Ann Lee' })
const result = await auth.updateProfile({ avatar: file }) // a File from an <input type="file">
const result = await auth.removeAvatar() // removes the photo
```
It answers with the updated `User`. Pass the file through a server function that takes `FormData`. The photo must be a PNG, JPEG or GIF of at most 5 MB, or it answers `notAnImage` or `fileTooLarge`. A blank or unacceptable name answers `invalidName`.
Only some apps can store a photo. Show the photo controls only when `user.avatarEditable` is true; elsewhere a photo answers `avatarNotSupported`.
The page keeps showing the old name and photo until its route context loads again, so call `router.invalidate()` after a success.
## References
- [current-user/SKILL.md](../current-user/SKILL.md): reading the visitor these calls establish
- [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): `NON_LOGGED_IN_USERS` and the `alreadyAuthenticated` redirect that keeps a signed-in visitor off a login page