A frontend does not import the server’s code. It imports a contract: a
.d.ts file of plain types that tetsu-client contract generates from the
application. Add a script to the server:
Where the application is, put before every path —
https://api.example.com or https://example.com/api. A trailing
slash is dropped. Empty by default: the paths stay relative, for a
fetch that resolves them itself.
baseUrl: "https://api.example.com" });
Commit the contract, so every API change shows up as a diff, and check it
in CI:
In a monorepo, run the same command with --watch while you work, and the
frontend sees a new route as soon as it is saved. Importing typeof app
into the frontend also works, but it makes the frontend compile the
server’s code with Bun’s types; keep that for tests and Bun projects.
The same options work with Svelte, Vue and Solid; those adapters take a
function that returns them, such as
createQuery(() => q.get(…).queryOptions(…)). A mutation is
useMutation(q.post("/users").mutationOptions()), and
invalidateQueries({ queryKey: q.get("/users").key() }) refreshes every
query of a route.
Two things are worth setting once. Send authorization from the client, not
from each call: a call’s headers are part of its query key, and would end
up in the cache. And retry only server errors and network failures, since
TanStack Query retries everything three times by default in the browser, and
a 404 would show only after them:
Headers sent with every request, or a function that returns them —
asked again for each request, so a token read from a store is always
the current one. A header a call sets wins over these.
headers: () => ({
authorization: string
authorization: `Bearer ${currentToken()}` }),
});
exportconst
constretry: (count:number, error:Error) =>boolean
retry= (
count: number
count:number,
error: Error
error:Error) =>
!(
error: Error
errorinstanceofClientError&&
error: ClientError<any>
error.
status: any
status<500) &&
count: number
count<3;
exportconst
constqueryClient:QueryClient
queryClient=newQueryClient({
defaultOptions?: DefaultOptions<Error>|undefined
Default options for all queries and mutations created through this client.
Default options applied to every query, unless overridden per-query.
queries: {
retry?: RetryValue<Error>|undefined
If false, failed queries will not retry by default.
If true, failed queries will retry infinitely.
If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number.
If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.
A query of a stream is TanStack Query’s streamedQuery, fed by the call’s
events. The options of
queryUtils read one body and are done, so on a stream they fail the
query with a TypeError rather than leave the connection open. TanStack
Query retries that error like any other, so it shows after the retries.
skipToken is not allowed as a value here — this overload is selected when no initialData is set. If
you don't intend to run the query yet, set enabled: false — omitting queryFn alone still triggers a
fetch that fails with "Missing queryFn" unless enabled is false or a default query function has been
defined. A default query function only supplies queryFn; it doesn't defer the fetch on its own.
The rest of fetch's options — signal, credentials, cache.
init: {
signal?: AbortSignal |null|undefined
An AbortSignal to set request's signal.
signal },
});
if (!res.
ok: boolean
ok) thrownewClientError(
constres:Undeclared<{
readonly200:Raw<"text/event-stream", {
type:"delta";
delta:string;
} | {
type:"done";
}>;
}, ErrorBody>
res);
forawait (const
constevent:ReceivedEvent<{
type:"delta";
delta:string;
} | {
type:"done";
}>
eventof
constres:Success<200, undefined> & {
readonlyevents:AsyncIterable<ReceivedEvent<{
type:"delta";
delta:string;
} | {
type:"done";
}>>;
}
res.
events: AsyncIterable<ReceivedEvent<{
type:"delta";
delta:string;
} | {
type:"done";
}>>
The events of the stream, read as they are iterated. Leaving
the loop closes the connection, and the call's signal aborts
it; a stream that is never read stays open until the signal
aborts it or response.body is cancelled. Read once.
events) {
if (
constevent:ReceivedEvent<{
type:"delta";
delta:string;
} | {
type:"done";
}>
event.
data: {
type: "delta";
delta: string;
} | {
type: "done";
}
data.
type: "delta"|"done"
type==="delta") yield
constevent:ReceivedEvent<{
type:"delta";
delta:string;
} | {
type:"done";
}>
event.
data: {
type: "delta";
delta: string;
}
data.
delta: string
delta;
}
},
reducer: (acc:string, chunk:string) => string
Reduces streamed chunks into the final data shape. Required whenever TData is not an
array, since there is no default way to accumulate non-array chunks.
reducer: (
text: string
text,
delta: string
delta) =>
text: string
text+
delta: string
delta,
initialValue: string
The value used while the first chunk is being fetched, and returned if the stream yields no
values. Required together with a custom reducer.
The time in milliseconds after data is considered stale.
If set to Infinity, the data will never be considered stale.
If set to 'static', the data will never be considered stale.
If set to a function, the function will be executed with the query to compute a staleTime.
@defaultValue ― 0
staleTime: Number.
typePOSITIVE_INFINITY: number
A value greater than the largest number that can be represented in JavaScript.
JavaScript displays POSITIVE_INFINITY values as infinity.
POSITIVE_INFINITY,
retry?: RetryValue<Error>|undefined
If false, failed queries will not retry by default.
If true, failed queries will retry infinitely.
If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number.
If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.
The query shows the text as it grows, and stays fetching until the stream
ends. Its signal goes to the call, so a query that is cancelled or loses
its last observer closes the stream. A stream that starts work on the
server should not start it again by itself: staleTime keeps the query
from refetching when the window regains focus or a component mounts, and
retry: false from running the agent again after a failure.
streamedQuery is still experimental in TanStack Query.
On the server, a component renders for a request whose cookies the client
has to pass on itself. A client is cheap to create, so make one per
request:
src/api.ts
import { createClient } from"@tetsujs/client";
importtype { Api } from"./api.contract";
exportfunctionapi(
cookie: string |undefined
cookie?:string) {
returncreateClient<Api>({
baseUrl?: string |URL|undefined
Where the application is, put before every path —
https://api.example.com or https://example.com/api. A trailing
slash is dropped. Empty by default: the paths stay relative, for a
fetch that resolves them itself.
baseUrl: process.
env: NodeJS.ProcessEnv
The process.env property returns an object containing the user environment.
See environ(7).
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other Worker threads.
In other words, the following example would not work:
Assigning a property on process.env will implicitly convert the value
to a string. This behavior is deprecated. Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
import { env } from'node:process';
env.test =null;
console.log(env.test);
// => 'null'
env.test =undefined;
console.log(env.test);
// => 'undefined'
Use delete to delete a property from process.env.
import { env } from'node:process';
env.TEST=1;
delete env.TEST;
console.log(env.TEST);
// => undefined
On Windows operating systems, environment variables are case-insensitive.
import { env } from'node:process';
env.TEST=1;
console.log(env.test);
// => 1
Unless explicitly specified when creating a Worker instance,
each Worker thread has its own copy of process.env, based on its
parent thread's process.env, or whatever was specified as the env option
to the Worker constructor. Changes to process.env will not be visible
across Worker threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner
unlike the main thread.
Headers sent with every request, or a function that returns them —
asked again for each request, so a token read from a store is always
the current one. A header a call sets wins over these.
headers:
cookie: string |undefined
cookie===undefined?undefined: {
cookie: string
cookie },
});
}
A server component prefetches the query and hands the cache to the browser:
User is a client component that calls useQuery with the same options,
over queryUtils(api()): in the browser, the browser sends the cookies. Its
query client comes from a provider in the root layout, with the retry
above:
Default options applied to every query, unless overridden per-query.
queries: {
retry?: RetryValue<Error>|undefined
If false, failed queries will not retry by default.
If true, failed queries will retry infinitely.
If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number.
If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.
Defaults to 3 on the client and 0 on the server.
retry } } }));
return <QueryClientProvider
client: QueryClient
Required
The QueryClient instance to provide.
client={
constqueryClient:QueryClient
queryClient}>{
children: ReactNode
children}</QueryClientProvider>;
}
For an API on another origin, pass init: { credentials: "include" } to
the client. In a monorepo on Bun, set "types": ["node"] in the Next.js
tsconfig.json, or it picks up Bun’s types from the root.
A load function gets SvelteKit’s fetch, which carries the request’s
cookies on the server. Pass it to the client:
src/lib/api.ts
import { createClient } from"@tetsujs/client";
importtype { Api } from"./api.contract";
exportfunctionapi(
fetch: typeof globalThis.fetch
fetch= globalThis.fetch) {
returncreateClient<Api>({
baseUrl?: string |URL|undefined
Where the application is, put before every path —
https://api.example.com or https://example.com/api. A trailing
slash is dropped. Empty by default: the paths stay relative, for a
fetch that resolves them itself.
baseUrl: "https://api.example.com",
fetch?: Fetch |undefined
The fetch to send with. The global fetch by default.
fetch });
}
While it renders, SvelteKit’s fetch hides the headers of a response unless
a hook lets them through, and the client reads content-type. Without the
hook, every load that calls the client fails with a 500:
In SvelteKit 2, Handle comes from @sveltejs/kit. For an API on another
origin, the server’s fetch asks for CORS headers as a browser does, so the
application needs cors for the frontend’s origin.
With TanStack Query, the root layout creates the query client, with queries
off on the server, where load functions prefetch instead, and the retry
above: a load runs in the browser too, and waits for every retry.
Set this to false or a function that returns false to disable automatic refetching when the query mounts or changes query keys.
To refetch the query, use the refetch method returned from the useQuery instance.
Accepts a boolean or function that returns a boolean.
@defaultValue ― true
enabled: browser,
retry?: RetryValue<Error>|undefined
If false, failed queries will not retry by default.
If true, failed queries will retry infinitely.
If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number.
If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.
The page calls createQuery(() => q.get("/users/:id").queryOptions({ params: { id: data.id } }))
over queryUtils(api()) and finds the user in the cache. Wrap the layout
in QueryClientProvider with data.queryClient, as the
Svelte Query docs
show.
Nuxt, SolidStart and other frameworks follow the same idea: a client per
request that passes its cookies on, and prefetching as TanStack Query’s
guide for that framework describes.
error is the body of any other status the document lists, including the
422 and 500 the framework answers. Branch on its error code. A
refusal from a hook is in the document only when the hook is
documented. To commit the
document and check it in CI, as with the contract, see
Using the document directly.