A React application that fetches data from an API in the browser works, but it leaves a few problems: the API address and tokens are visible in network traffic, the content appears only after JavaScript runs, and types end at the network boundary. TanStack Start addresses this with two mechanisms: server-side rendering (SSR) and server functions. Below are both, with their costs.
Part 1: why SSR
Search engines and messengers get ready HTML. The server answers with a document that has the content, the title and the meta tags, so a crawler does not have to run JavaScript to see the page. Messengers read Open Graph tags from the HTTP response and usually execute nothing, so a link preview in WhatsApp, LinkedIn or Slack depends on what is in the HTML. Google can run JavaScript, but that is an extra step you can avoid.
Content shows up sooner. The first paint comes from the server, and hydration (attaching interactivity to the finished HTML) happens afterwards. The page is readable before the browser downloads and runs all the code, which helps on a slow phone and can improve Core Web Vitals. I give no numbers, because they depend on your site. Measure your own.
Head per route. You set the title, description and Open Graph in the route definition, next to the loader that supplies the data:
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => {
const post = await getPost({ data: { id: params.postId } })
return { post }
},
head: ({ loaderData }) => ({
meta: [
{ title: loaderData.post.title },
{ name: 'description', content: loaderData.post.excerpt },
{ property: 'og:title', content: loaderData.post.title },
{ property: 'og:description', content: loaderData.post.excerpt },
{ name: 'twitter:card', content: 'summary_large_image' },
],
}),
component: PostPage,
})Use an absolute URL in og:image, because a messenger does not know your domain.
Honestly about the costs. SSR is a server to maintain. The documentation describes building with Vite and Nitro and starting with node .output/server/index.mjs, so you have a Node process to deploy, monitor and update. There is also the question of what renders on the server and what only in the browser. Code that assumes window, or formats a date according to local settings, gives a different result on the server than in the browser, and that ends in a hydration error.
For a panel behind a login the SEO gain is zero, because no crawler gets in. What matters there is speed and security. That is why a route can turn off component rendering: the ssr: false option turns it off entirely, and ssr: 'data-only' keeps the loader on the server but renders the component in the browser.
Part 2: server functions
The browser does not call the backend directly. It calls a server function, and only that function calls the .NET API. The API address, tokens and secrets stay on the server, because the function body never reaches the browser.
GET for reads, POST for changes. You set the method in createServerFn. Everything that changes data should be method: 'POST'. A POST response does not land in the cache or the browser history, it cannot be triggered by an ordinary link or an image on someone else's page, and combined with a session cookie with SameSite and an Origin header checked on the server it closes the typical CSRF scenarios. The documentation shows such a check as middleware:
import { createMiddleware } from '@tanstack/react-start'
import { getRequest } from '@tanstack/react-start/server'
export const csrfMiddleware = createMiddleware().server(async ({ next }) => {
const request = getRequest()
if (request.method !== 'GET' && request.method !== 'HEAD') {
const origin = request.headers.get('origin')
if (!origin || new URL(origin).origin !== process.env.APP_ORIGIN) {
throw new Error('Origin check failed')
}
}
return next()
})You attach it as a global request middleware in src/start.ts. These are three layers, not one: none of them is enough alone.
Validation and a typed result. Data from the network is untrusted, even when your own front end sends it. The zod schema lives in one file, and the server function checks it again and returns the result as a union of types, not a bare HTTP status.
Example: newsletter sign-up
The schema and the server function:
// src/server/subscribe.ts
import { createServerFn } from '@tanstack/react-start'
import { z } from 'zod'
export const subscribeSchema = z.object({
email: z.string().email('Enter a valid e-mail address'),
consent: z.boolean().refine((value) => value, 'Please tick the consent box'),
})
export type SubscribeInput = z.infer<typeof subscribeSchema>
export type SubscribeResult =
| { ok: true }
| { ok: false; message?: string; fieldErrors: Record<string, string> }
export const subscribe = createServerFn({ method: 'POST' })
.validator((data: SubscribeInput) => data)
.handler(async ({ data }): Promise<SubscribeResult> => {
const parsed = subscribeSchema.safeParse(data)
if (!parsed.success) {
const fieldErrors: Record<string, string> = {}
for (const issue of parsed.error.issues) {
fieldErrors[String(issue.path[0])] = issue.message
}
return { ok: false, fieldErrors }
}
const response = await fetch(process.env.API_URL + '/subscriptions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Api-Key': process.env.API_KEY ?? '' },
body: JSON.stringify(parsed.data),
})
if (response.status === 409) {
return { ok: false, fieldErrors: { email: 'This address is already subscribed' } }
}
if (!response.ok) {
return { ok: false, message: 'Could not sign you up. Please try again.', fieldErrors: {} }
}
return { ok: true }
})API_URL and API_KEY are read only by the server. The browser gets nothing but the result.
The form with TanStack Form and the mutation with TanStack Query:
import { useForm } from '@tanstack/react-form'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { subscribe, subscribeSchema, type SubscribeInput } from '../server/subscribe'
function SubscribeForm() {
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: (value: SubscribeInput) => subscribe({ data: value }),
onSuccess: (result) => {
if (result.ok) return queryClient.invalidateQueries({ queryKey: ['subscribers'] })
},
})
const form = useForm({
defaultValues: { email: '', consent: false },
validators: {
onChange: subscribeSchema,
onSubmitAsync: async ({ value }) => {
const result = await mutation.mutateAsync(value)
return result.ok ? null : { form: result.message, fields: result.fieldErrors }
},
},
})
return (
<form onSubmit={(e) => { e.preventDefault(); form.handleSubmit() }}>
<form.Field
name="email"
children={(field) => (
<>
<input
type="email"
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
{field.state.meta.errors.map((error) => (
<em key={String(error)}>{String(error)}</em>
))}
</>
)}
/>
<button type="submit">Sign me up</button>
</form>
)
}The consent field looks analogous.
The same schema does three things. TanStack Form validates the fields with it in the browser, the server function checks it again, and the SubscribeInput type is derived from it, so changing a rule changes it everywhere. TanStack Query calls the server function like an ordinary async function. When the sign-up succeeds, it invalidates the ['subscribers'] key and the list is fetched again. Errors from the API come back to the form through onSubmitAsync, which can set an error on a specific field.
Summary
SSR buys visibility and a faster first paint, and you pay with a Node server and attention to differences between the server and the browser. Server functions buy a trust boundary: secrets stay behind the server, and data changes go only through POST. Both are optional route by route, so you can leave the panel without SSR and render the public pages.