Skip to content

TanStack Start routing and server functions example GitHub

Explore file-based routes, nested layouts, server functions, and server-rendered pages in a runnable React application.

Browse posts and users, open a detail URL directly, and follow links between nested layouts. The post loaders call server functions, so you can follow the request from a route to the server and back to the page.

Run locally

Use Node.js 22.12 or newer and pnpm 11. These examples fetch public sample data from JSONPlaceholder, so an internet connection is required. No API key or database is needed.

shell
git clone https://github.com/TanStack/router.git
cd router
pnpm install
cd examples/react/start-basic
pnpm dev

Open the local URL printed by Vite. Try a post detail URL in a new tab to see a direct server-rendered request.

Run pnpm build from the example directory to build the app and check its types.

Files to follow

Routing guide

/src/utils/posts.tsx
import { notFound } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'

export type PostType = {
  id: number
  title: string
  body: string
}

export const fetchPost = createServerFn({ method: 'POST' })
  .validator((d: string) => d)
  .handler(async ({ data }) => {
    console.info(`Fetching post with id ${data}...`)
    const res = await fetch(
      `https://jsonplaceholder.typicode.com/posts/${data}`,
    )
    if (!res.ok) {
      if (res.status === 404) {
        throw notFound()
      }

      throw new Error('Failed to fetch post')
    }

    const post = await res.json()

    return post as PostType
  })

export const fetchPosts = createServerFn().handler(async () => {
  console.info('Fetching posts...')
  const res = await fetch('https://jsonplaceholder.typicode.com/posts')
  if (!res.ok) {
    throw new Error('Failed to fetch posts')
  }

  const posts = await res.json()

  return (posts as Array<PostType>).slice(0, 10)
})