SolidStart Data — SolidJS

A function with "use server" on its first line only runs on the server; the browser calls it through a request. query(fn, "catalog") wraps a data fetcher and…

A buyer presses Add on The Rainbow Troops. The stock has to drop in the database, the cart has to grow, and the page has to show the latest numbers. That database lives on the server, so the page may not touch it directly.

SolidStart gives you three tools from @solidjs/router for this: query for a function that fetches data, createAsync to read it in a component, and action to change it. A function marked "use server" only runs on the server. Think of Nadia's Bookshop's cashier and the warehouse. The cashier (the page) may not open the warehouse cupboards (the database) herself, so she phones the warehouse. The warehouse's answer is jotted on a slip on the cashier's desk, so two buyers asking the same thing don't make two calls. When there is an order, the cashier sends a slip to the warehouse, then phones again for the latest stock numbers.

"use server": code that only runs on the server

// src/lib/shop.ts
import { query } from "@solidjs/router"
import { db } from "./db"

export const getCatalog = query(async () => {
  "use server"
  return db.allBooks()
}, "catalog")

query and createAsync: reading data in a page

// src/routes/index.tsx
import { createAsync } from "@solidjs/router"
import { For, Suspense } from "solid-js"
import { getCatalog } from "~/lib/shop"

export default function Home() {
  const books = createAsync(() => getCatalog())

  return (
    <Suspense fallback={<p>Loading catalogue...</p>}>
      <ul>
        <For each={books()}>{(b) => <li>{b.title} · stock {b.stock}</li>}</For>
      </ul>
    </Suspense>
  )
}

Tested with @solidjs/router 1.0 and a fake server that answers 800 ms later:

Time books() Page
0 ms undefined, getCatalog is called Loading catalogue...
800 ms an array of 3 books The Rainbow Troops · stock 4, This Earth of Mankind · stock 2, Beauty Is a Wound · stock 0

action: changing data through a form

import { action, useSubmission } from "@solidjs/router"

export const addToCart = action(async (formData) => {
  "use server"
  const id = Number(formData.get("id"))
  const book = await db.findBook(id)
  if (book.stock === 0) throw new Error("Out of stock")
  await db.addToCart(id)
}, "addToCart")

On the page, every book has a small form:

const submission = useSubmission(addToCart)

<Show when={submission.pending}><p>Adding...</p></Show>
<Show when={submission.error}><p>Failed: {submission.error.message}</p></Show>
<form action={addToCart} method="post">
  <input type="hidden" name="id" value={b.id} />
  <button type="submit">Add</button>
</form>

⚠️ Anyone can call a server function. The browser calls it with a normal HTTP request, so someone else can send the same request with any id, without opening your page. Inside a "use server" function, check the login session when the action needs a login, and check the input before you use it. In the example above, Number("abc") is NaN, and db.findBook can return null for an id that does not exist:

const id = Number(formData.get("id"))
if (!Number.isInteger(id)) throw new Error("Invalid book ID")
const book = await db.findBook(id)
if (!book) throw new Error("Book not found")

After an action: revalidation

You press Add on The Rainbow Troops (stock 4), and you write no code to reload the list. Take a guess first: after the action finishes, does the list show stock 3, or stay at 4?

The action takes 300 ms, getCatalog 800 ms, getCart 200 ms. Tested with @solidjs/router 1.0:

Since the click What happens Page
0 ms the form is sent, the action runs on the server Adding..., the old list stays
300 ms the action is done, the router calls getCatalog and getCart again still the old list
1,100 ms the new data arrives The Rainbow Troops · stock 3, Cart: 1 book, Adding... gone

The stock drops to 3 by itself. After a successful action, the router revalidates (reloads) every query on that page, so the list and the cart match the server again. Meanwhile the old list stays on screen; the fallback doesn't come back.

The exercise: query and createAsync in the sandbox

The exercise sandbox has no SolidStart server, but query and createAsync there work as in @solidjs/router: calls with the same arguments share one request, and createAsync holds <Suspense> until the data arrives. A "use server" function runs in the preview.

const getItems = query(async () => {
  "use server"
  setRequests((n) => n + 1)
  await new Promise((r) => setTimeout(r, 200))
  return [
    { id: 1, name: "Item 1" },
    { id: 2, name: "Item 2" },
  ]
}, "items")

function List() {
  const items = createAsync(() => getItems())
  return (
    <ul>
      <For each={items()}>{(item) => <li>{item.name}</li>}</For>
    </ul>
  )
}

The Count component calls createAsync(() => getItems()) too, but the counter stays at Server requests: 1: query shares its answer between the two components. Without query, the same function is asked twice.

⚠️ Server functions that run in the browser, and data that hasn't arrived

TL;DR: A function with "use server" on its first line only runs on the server; the browser calls it through a request. query(fn, "catalog") wraps a data fetcher and keeps its result by name, and createAsync(() => getCatalog()) reads it in a page: undefined at first, read inside <Suspense>. action(fn, "name") receives FormData from <form action={...} method="post">, useSubmission gives pending and error, and after a successful action the router revalidates every query on the page, so the stock and the cart change by themselves. In the exercise sandbox, query and createAsync work the same way, and a "use server" function runs in the preview.

⚡ "use server": runs only on the server

Write:

export const getCatalog = query(async () => {
  "use server"
  return db.allBooks()
}, "catalog")

Meaning: "use server" is written as the first line of the function body. Its body only exists on the server, and the browser gets a stand-in that sends a request. So a database connection or an API key inside it is never sent to the browser.

⚡ query and createAsync

Write:

const books = createAsync(() => getCatalog())

<Suspense fallback={<p>Loading catalogue...</p>}>
  <For each={books()}>{(b) => <li>{b.title}</li>}</For>
</Suspense>

Meaning: createAsync returns a reader like a signal, undefined until the data arrives. query keeps its result by name, so two components that both call getCatalog() on one page trigger only one request. This exercise checks that through #requests.

⚡ After an action: revalidation

Guess first: you press Add on The Rainbow Troops (stock 4) through an action, with no code to reload the list. After the action finishes, is the stock 3, or still 4?

3, by itself. After a successful action, the router reloads every query on that page.

Meaning: <form action={addToCart} method="post"> sends its contents as FormData, and useSubmission gives pending and error. An action that throws doesn't trigger a revalidation.

What you will learn