Open History to see the last commit
1<img src="https://static.scarf.sh/a.png?x-pxid=d988eb79-b0fc-4a2b-8514-6a1ab932d188" />
2β
3# TanStack Server Functions Plugin
4β
5## Configuration
6β
7Create a new instance of the plugin with the following options:
8β
9```ts
10TanStackServerFnPlugin({
11 // This is the ID that will be available to look up and import
12 // our server function manifest and resolve its module
13 manifestVirtualImportId: 'tanstack:server-fn-manifest',
14 generateFunctionId: startPluginOpts?.serverFns?.generateFunctionId,
15 client: {
16 getRuntimeCode: () =>
17 `import { createClientRpc } from '@tanstack/${corePluginOpts.framework}-start/client-rpc'`,
18 replacer: (d) => `createClientRpc('${d.functionId}')`,
19 envName: 'client',
20 },
21 server: {
22 getRuntimeCode: () =>
23 `import { createServerRpc } from '@tanstack/${corePluginOpts.framework}-start/server-rpc'`,
24 replacer: (d) => `createServerRpc('${d.functionId}', ${d.fn})`,
25 envName: 'ssr',
26 },
27}),
28```
29β
30## Providing the wrapper implementations
31β
32Each runtime replacement should be implemented by your framework. Generally, on the client runtime, you'll end up using a `fetch` call to call the server function your desired endpoint, like this:
33β
34```ts
35function createClientRpc(functionId: string) {
36 const url = `${process.env.YOUR_SERVER_BASE}/_serverFn/${functionId}`
37β
38 const fn = async (...args: any[]) => {
39 const res = await fetch(url, {
40 method: 'POST',
41 // You'll likely want to use a better serializer here
42 body: JSON.stringify(args),
43 })
44β
45 return await res.json()
46 }
47β
48 // You can also assign any other properties you want to the function
49 // for things like form actions, or debugging
50 Object.assign(fn, {
51 url: url,
52 })
53β
54 return fn
55}
56```
57β
58## Using the manifest
59β
60In your server handler, you can import the manifest and use it to look up and dynamically import the server function you want to call.
61β
62```ts
63import { getServerFnById } from 'tanstack:server-fn-manifest'
64β
65export const handler = async (req: Request) => {
66 const functionId = req.url.split('/').pop()
67 invariant(functionId, 'No function ID provided')
68β
69 const serverFn = await getServerFnById(functionId)
70β
71 const args = await req.json()
72β
73 return await serverFn(...args)
74}
75```