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

static-server-functions.md

35 lines1.4 KB

1---
2id: static-server-functions
3title: Static Server Functions
4---
5​
6> [!WARNING]
7> Static Server Functions are experimental!
8​
9## What are Static Server Functions?
10​
11Static server functions are server functions that are executed at build time and cached as static assets when using prerendering/static-generation. They can be set to "static" mode by applying the `staticFunctionMiddleware` middleware to `createServerFn`:
12​
13```tsx
14import { createServerFn } from '@tanstack/react-start'
15import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions'
16​
17const myServerFn = createServerFn({ method: 'GET' })
18 .middleware([staticFunctionMiddleware])
19 .handler(async () => {
20 return 'Hello, world!'
21 })
22```
23​
24Ensure that `staticFunctionMiddleware` is the final middleware!
25​
26This pattern goes as follows:
27​
28- Build-time
29 - During build-time prerendering, a server function with `staticFunctionMiddleware` is executed
30 - The result is cached with your build output as a static JSON file under a derived key (function ID + params/payload hash)
31 - The result is returned as normal during prerendering/static-generation and used to prerender the page
32- Runtime
33 - Initially, the prerendered page's html is served and the server function data is embedded in the html
34 - When the client mounts, the embedded server function data is hydrated
35 - For future client-side invocations, the server function is replaced with a fetch call to the static JSON file