Open History to see the last commit
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