Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท SolidStart and Routing

Server Functions, Actions and API Routes

Run code on the server with use server, mutate data with actions and forms, track submissions, add API routes and middleware, and keep secrets out of the browser.

A big advantage of a full-stack framework is that front end and back end live in one project. In SolidStart you can write a function that runs on the server and call it from a component as if it were local, handle form submissions without writing fetch code, and expose plain HTTP endpoints when you need them.

Server code needs a server, so the real SolidStart code on this page is read-only. The live examples are labelled stand-ins that simulate the server with timers, so you can see the client-side behavior (pending state, errors, optimistic feedback) that the framework gives you.

Server functions with "use server"

Put the string "use server" as the first statement of a function and the build marks it as server-only. In the browser bundle the function is replaced by a small stub that makes an RPC call to the server; the real body (and anything it imports, such as a database client) never ships to the client.

TypeScript
// src/lib/todos.ts
import { query } from "@solidjs/router";
import { db } from "./db";                      // server-only dependency

export const getTodos = query(async () => {
  "use server";
  return db.todos.findMany();                    // runs on the server
}, "todos");

Because the arguments and the return value travel over the network, they must be serialisable: strings, numbers, booleans, plain objects and arrays, dates, Map, Set, undefined and so on, but not class instances with methods or functions. Treat every argument as untrusted user input: validate it on the server, exactly as you would in any HTTP handler.

Secrets belong in server functions. process.env.DATABASE_URL read inside a "use server" function is never exposed to the browser.

Actions for mutations

Queries read; actions change data. An action wraps an async function and works with forms:

TSX
import { action, redirect } from "@solidjs/router";

export const addTodo = action(async (formData: FormData) => {
  "use server";
  const title = String(formData.get("title") ?? "").trim();
  if (title.length < 2) return { error: "Title is too short" };
  await db.todos.create({ title });
  throw redirect("/todos");                      // or just return, see below
}, "addTodo");

Use it as the action of a form:

TSX
<form action={addTodo} method="post">
  <input name="title" />
  <button type="submit">Add</button>
</form>

Two benefits follow. The form works before JavaScript has loaded (it is a real form post), and once JavaScript is ready the router intercepts the submit and calls the action without a page reload. After the action finishes, the router revalidates all queries automatically, so the todo list refreshes by itself. You can control that with redirect(path, { revalidate: [...] }) or by returning json(result, { revalidate: [getTodos.key] }).

Tracking a submission

useSubmission(action) gives a reactive view of the most recent submission, and useSubmissions a list of all:

TSX
import { useSubmission } from "@solidjs/router";

const submission = useSubmission(addTodo);

<button disabled={submission.pending}>
  {submission.pending ? "Saving..." : "Add"}
</button>
<Show when={submission.result?.error}>
  <p class="error">{submission.result.error}</p>
</Show>

submission.pending, submission.result (what the action returned), submission.error (what it threw) and submission.input (the form data) let you show a spinner, validation errors and an optimistic row for the item being saved. For a non-form trigger, useAction(addTodo) returns a function you can call from a button.

Stand-in: a form action with pending and errors

Stand-in: submit a form to a pretend server

Submit an empty form to see the validation message, and a real title to see "Saving..." followed by the new item. In SolidStart the router supplies pending and result for you; the shape of your component is the same.

Never trust client-side validation alone. The check in the action above runs on the server in the real framework, and a client check is only a convenience.

API routes

Sometimes you want a plain HTTP endpoint: for a mobile app, a webhook, or a third party. Files in src/routes that export HTTP method functions become endpoints:

TypeScript
// src/routes/api/todos/[id].ts
import type { APIEvent } from "@solidjs/start/server";

export async function GET({ params }: APIEvent) {
  const todo = await db.todos.find(params.id);
  if (!todo) return new Response("Not found", { status: 404 });
  return Response.json(todo);
}

export async function DELETE({ params }: APIEvent) {
  await db.todos.remove(params.id);
  return new Response(null, { status: 204 });
}

They use the standard Request and Response objects, so they behave like any Fetch-API handler. Use an API route when something outside your Solid app needs to call you, and a server function or action when your own components do.

Middleware

Middleware runs before routes and server functions, which makes it the place for cross-cutting concerns such as authentication checks, security headers and logging:

TypeScript
// src/middleware/index.ts
import { createMiddleware } from "@solidjs/start/middleware";

export default createMiddleware({
  onRequest: (event) => {
    event.response.headers.set("x-frame-options", "DENY");
  },
});

It is registered in app.config.ts (middleware: "src/middleware/index.ts"). For per-user data, read the session from the cookie in a server function or middleware, and keep the decision "may this user do this?" on the server, next to the data.

A note on security

  • Every server function is an HTTP endpoint, even if you never call it by URL. Anyone can call it with any arguments, so authorise and validate inside it.
  • Never return more than the client needs: select fields rather than returning a whole database row (password hashes!).
  • Keep secrets in environment variables read only on the server.
  • Forms that change data should be protected against cross-site requests; SolidStart's actions use POST and you should keep session cookies SameSite.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a function marked with "use server" in the browser bundle?

    The real body stays on the server; the client gets a small RPC stub.
  2. 2. Why does a form with an action work before JavaScript loads?

    Progressive enhancement: the browser can submit the form normally, and the router intercepts it once ready.
  3. 3. What does useSubmission(action) give you?

    It is how you show spinners, validation messages and optimistic UI for an action.
  4. 4. Where must validation and authorisation of server function arguments happen?

    Server functions are public endpoints, so the server must check everything.

Summary

  • "use server" keeps a function's body on the server; arguments and results must be serialisable and are untrusted.
  • Actions handle mutations and forms, work without JavaScript, and revalidate queries afterwards.
  • useSubmission exposes pending, result and error state for UI feedback.
  • API routes export GET/POST/... handlers using the standard Request and Response.
  • Middleware centralises auth checks and headers; secrets stay in server-only code.

Next: Testing Solid Components