Skip to content
typebox-standard-schema

SvelteKit remote functions

SvelteKit's remote functions, query, command and form, validate their argument with any Standard Schema. A schema built with this package's Type goes in as is, and form fields, which always arrive as strings, are coerced to the types the schema asks for.

bun

bun add typebox-standard-schema

A form

// src/routes/signup/user.remote.ts
import { form } from '$app/server'
import { Type } from 'typebox-standard-schema'

const User = Type.Object({
  id: Type.Readonly(Type.Integer()),
  email: Type.String({ format: 'email' }),
  age: Type.Integer({ minimum: 13 }),
  password: Type.Writeonly(Type.String({ minLength: 8 })),
})

export const signup = form(Type.Write(User), async (user) => {
  // user: { email: string, age: number, password: string }
  await db.insertUser(user)
})
<!-- src/routes/signup/+page.svelte -->
<script lang="ts">
  import { signup } from './user.remote'
</script>

<form {...signup}>
  <input {...signup.fields.email.as('email')} />
  <input {...signup.fields.age.as('number')} />
  <input {...signup.fields.password.as('password')} />

  {#each signup.fields.allIssues() ?? [] as issue}
    <p>{issue.message}</p>
  {/each}

  <button>Sign up</button>
</form>

db stands for your data layer. The age arrives as the string '42' and reaches the handler as the number 42; 'abc' is reported on the age field. Type.Write(User) has no id, so a crafted request can't set one.

Queries and commands

query and command take a schema the same way:

import { command, query } from '$app/server'
import { Type } from 'typebox-standard-schema'

export const getUser = query(Type.Object({ id: Type.Integer() }), ({ id }) => db.findUser(id))

export const rename = command(
  Type.Object({ id: Type.Integer(), name: Type.String({ minLength: 1 }) }),
  ({ id, name }) => db.renameUser(id, name),
)

For these two, SvelteKit answers an invalid argument with a bare 400 by design; the issues are only sent back for form.