Call the server
A function that runs on the server and is called like any other function from the page.
Write the function once, on the server, and import it where you need it.
Compare the server source with the client stub produced by Dusk.
import { notFound, serverFn } from "@shadow-js/dusk/server";
import { users } from "./db.server";
import { userId } from "./schema";
export const getUser = serverFn({ method: "GET", input: userId }, ({ id }) => {
const user = users.get(id);
if (user === undefined) throw notFound();
return user;
});
On the server, getUser is the function above. In the browser, the build replaces it with a small stub that sends a request to /_dusk/fn/<id> and returns the answer. The body, the users import and the database never reach the browser. A file whose name ends in .server.ts is the same: the build refuses to put it in a browser bundle.
Input is checked#
input takes a schema. A call with the wrong shape is refused with a 400 before your code runs, and the types of the argument and the result carry over to the caller.
What the browser gets#
After the build, the browser receives the files that run there: layouts, pages and the stubs. Middleware, server functions and anything that touches the database stay on the server. The first load of the starter is a few tens of kilobytes of JavaScript for this reason.
Streaming#
Pass stream: true and make the handler an async generator, and each yield is one item the page receives as it is produced.
Next: forms. Methods, errors across the wire and streaming limits are in Server functions.