Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

README.md

75 lines2.2 KB

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
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)
75```