### Clone and run TanStack Start examples
Source: https://tanstack.com/start/latest/docs/framework/react/getting-started.md
These commands demonstrate how to clone an official TanStack Start example, install its dependencies, and start the development server. Replace `EXAMPLE_SLUG` for other examples.
```bash
npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic
cd start-basic
npm install
npm run dev
```
```bash
npx gitpick TanStack/router/tree/main/examples/react/EXAMPLE_SLUG my-new-project
cd my-new-project
npm install
npm run dev
```
--------------------------------
### Install dependencies and start development server
Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/fetching-external-api.md
Installs project dependencies using pnpm and then starts the development server for the TanStack Start application.
```bash
pnpm i
pnpm dev
```
--------------------------------
### Install TanStack Start and Router Packages
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Install the core TanStack Start and TanStack Router packages using npm.
```shell
npm i @tanstack/react-start @tanstack/react-router
```
--------------------------------
### Sentry Quick Setup for TanStack Start
Source: https://tanstack.com/start/latest/docs/framework/react/guide/observability.md
This snippet provides a quick setup guide for integrating Sentry with a TanStack Start application. It includes configurations for both client-side React applications and server-side functions to capture errors and monitor performance.
```tsx
// Client-side (app.tsx)
import * as Sentry from '@sentry/react'
Sentry.init({
dsn: import.meta.env.VITE_SENTRY_DSN,
environment: import.meta.env.NODE_ENV,
})
```
```tsx
// Server functions
import * as Sentry from '@sentry/node'
const serverFn = createServerFn().handler(async () => {
try {
return await riskyOperation()
} catch (error) {
Sentry.captureException(error)
throw error
}
})
```
--------------------------------
### Connecting and Interacting with a Database using TanStack Start Server Functions
Source: https://tanstack.com/start/latest/docs/framework/react/guide/databases.md
This abstract example demonstrates how to connect to a database and perform read/write operations within TanStack Start server functions. It showcases using `createServerFn` to define server-side logic for data access.
```tsx
import { createServerFn } from '@tanstack/react-start'
const db = createMyDatabaseClient()
export const getUser = createServerFn().handler(async ({ context }) => {
const user = await db.getUser(context.userId)
return user
})
export const createUser = createServerFn({ method: 'POST' }).handler(
async ({ data }) => {
const user = await db.createUser(data)
return user
},
)
```
--------------------------------
### Install React and ReactDOM
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Install React and ReactDOM, which are required for building React-based applications with TanStack Start.
```shell
npm i react react-dom
```
--------------------------------
### Install Netlify Vite Plugin for TanStack Start
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Install the official Netlify Vite plugin to configure your TanStack Start project for Netlify deployment and local development emulation.
```bash
npm install --save-dev @netlify/vite-plugin-tanstack-start
# or...
pnpm add --save-dev @netlify/vite-plugin-tanstack-start
# or yarn, bun, etc.
```
--------------------------------
### Implement First TanStack Start Route with Server Functions
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
This example demonstrates creating a route with server-side functions for reading and updating a count, and a client-side component to interact with it.
```tsx
// src/routes/index.tsx
import * as fs from 'node:fs'
import { createFileRoute, useRouter } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
const filePath = 'count.txt'
async function readCount() {
return parseInt(
await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
)
}
const getCount = createServerFn({
method: 'GET',
}).handler(() => {
return readCount()
})
const updateCount = createServerFn({ method: 'POST' })
.validator((d: number) => d)
.handler(async ({ data }) => {
const count = await readCount()
await fs.promises.writeFile(filePath, `${count + data}`)
})
export const Route = createFileRoute('/')({
component: Home,
loader: async () => await getCount(),
})
function Home() {
const router = useRouter()
const state = Route.useLoaderData()
return (
)
}
```
--------------------------------
### Run Application Start Command
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Execute this command to start your application using the configured `start` script.
```sh
npm run start
```
--------------------------------
### Install Core Dependencies with Rsbuild
Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md
Use this command to install the core TanStack Start, React, and Rsbuild dependencies when using Rsbuild as your bundler.
```sh
npm i @tanstack/react-router @tanstack/react-start @rsbuild/core @rsbuild/plugin-react
```
--------------------------------
### Create a new TanStack Start project
Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/fetching-external-api.md
Initializes a new TanStack Start application named 'movie-discovery' and navigates into its directory.
```bash
pnpx create-start-app movie-discovery
cd movie-discovery
```
--------------------------------
### Install Core Dependencies with Vite
Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md
Use this command to install the core TanStack Start, React, Vite, and Nitro dependencies when using Vite as your bundler.
```sh
npm i @tanstack/react-router @tanstack/react-start nitro vite @vitejs/plugin-react
```
--------------------------------
### Install content-collections packages
Source: https://tanstack.com/start/latest/docs/framework/react/guide/rendering-markdown.md
Install the necessary `content-collections` packages using npm.
```bash
npm install @content-collections/core @content-collections/vite
```
--------------------------------
### Configure TypeScript for TanStack Start
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Create a `tsconfig.json` file with these compiler options to ensure proper TypeScript setup for a TanStack Start project.
```json
{
"compilerOptions": {
"jsx": "react-jsx",
"moduleResolution": "Bundler",
"module": "ESNext",
"target": "ES2022",
"skipLibCheck": true,
"strictNullChecks": true
}
}
```
--------------------------------
### Configure Vite Build and Start Scripts in package.json
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Add these scripts to your `package.json` to build your Vite application and start the server from the output files.
```json
"build": "vite build",
"start": "node .output/server/index.mjs"
```
--------------------------------
### Root Route and Clerk Integration in TanStack Start
Source: https://tanstack.com/start/latest/docs/framework/react/examples/start-clerk-basic
This snippet demonstrates the complete setup for the root route in a TanStack Start application, integrating Clerk for authentication. It uses `createServerFn` to fetch user authentication status on the server and `ClerkProvider` to wrap the application for client-side Clerk functionality.
```tsx
///
import {
ClerkProvider,
SignInButton,
SignedIn,
SignedOut,
UserButton,
} from '@clerk/tanstack-react-start'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { createServerFn } from '@tanstack/react-start'
import { auth } from '@clerk/tanstack-react-start/server'
import * as React from 'react'
import {
HeadContent,
Link,
Outlet,
Scripts,
createRootRoute,
} from '@tanstack/react-router'
import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js'
import { NotFound } from '~/components/NotFound.js'
import appCss from '~/styles/app.css?url'
const fetchClerkAuth = createServerFn({ method: 'GET' }).handler(async () => {
const { userId } = await auth()
return {
userId,
}
})
export const Route = createRootRoute({
beforeLoad: async () => {
const { userId } = await fetchClerkAuth()
return {
userId,
}
},
head: () => ({
meta: [
{
charSet: 'utf-8',
},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1',
},
],
links: [
{ rel: 'stylesheet', href: appCss },
{
rel: 'apple-touch-icon',
sizes: '180x180',
href: '/apple-touch-icon.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '32x32',
href: '/favicon-32x32.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '16x16',
href: '/favicon-16x16.png',
},
{ rel: 'manifest', href: '/site.webmanifest', color: '#fffff' },
{ rel: 'icon', href: '/favicon.ico' },
],
}),
errorComponent: (props) => {
return (
)
},
notFoundComponent: () => ,
component: RootComponent,
})
function RootComponent() {
return (
)
}
function RootDocument({ children }: { children: React.ReactNode }) {
return (
Home
{' '}
Posts
{children}
)
}
```
--------------------------------
### Root Route and Authentication Setup in TanStack Start with Auth.js
Source: https://tanstack.com/start/latest/docs/framework/react/examples/start-basic-authjs
This code defines the root route for a TanStack Start application, integrating Auth.js for session management. It includes `beforeLoad` logic to fetch the user session, sets up global head content, and renders the main application layout with a navigation bar that dynamically displays sign-in/sign-out options based on the session status.
```typescript
///
import type { ReactNode } from 'react'
import type { AuthSession } from 'start-authjs'
import {
HeadContent,
Link,
Outlet,
Scripts,
createRootRouteWithContext,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { createServerFn } from '@tanstack/react-start'
import { getRequest } from '@tanstack/react-start/server'
import { getSession } from 'start-authjs'
import { authConfig } from '~/utils/auth'
import appCss from '~/styles/app.css?url'
interface RouterContext {
session: AuthSession | null
}
const fetchSession = createServerFn({ method: 'GET' }).handler(async () => {
const request = getRequest()
const session = await getSession(request, authConfig)
return session
})
export const Route = createRootRouteWithContext()({
beforeLoad: async () => {
const session = await fetchSession()
return {
session,
}
},
head: () => ({
meta: [
{
charSet: 'utf-8',
},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1',
},
{
title: 'TanStack Start Auth Example',
},
],
links: [{ rel: 'stylesheet', href: appCss }],
}),
component: RootComponent,
})
function RootComponent() {
return (
)
}
function RootDocument({ children }: { children: ReactNode }) {
return (
{children}
)
}
function NavBar() {
const routeContext = Route.useRouteContext()
return (
)
}
```
--------------------------------
### Root Component and Material UI Setup in TanStack Start
Source: https://tanstack.com/start/latest/docs/framework/react/examples/start-material-ui
This snippet defines the root route and components for a TanStack Start application, integrating Material UI's theming and CSS baseline. It sets up `CacheProvider`, `ThemeProvider`, and `CssBaseline` to apply Material UI styles globally.
```tsx
///
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import {
HeadContent,
Outlet,
Scripts,
createRootRoute,
} from '@tanstack/react-router'
import { CacheProvider } from '@emotion/react'
import { Container, CssBaseline, ThemeProvider } from '@mui/material'
import createCache from '@emotion/cache'
import fontsourceVariableRobotoCss from '@fontsource-variable/roboto?url'
import React from 'react'
import { theme } from '~/setup/theme'
import { Header } from '~/components/Header'
export const Route = createRootRoute({
head: () => ({
links: [{ rel: 'stylesheet', href: fontsourceVariableRobotoCss }],
}),
component: RootComponent,
})
function RootComponent() {
return (
)
}
function Providers({ children }: { children: React.ReactNode }) {
const emotionCache = createCache({ key: 'css' })
return (
{children}
)
}
function RootDocument({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
```
--------------------------------
### Scaffold a new TanStack Start project with the CLI
Source: https://tanstack.com/start/latest/docs/framework/react/getting-started.md
Use this command to interactively create a new TanStack Start project, selecting your preferred package manager and optional features.
```bash
npx @tanstack/cli@latest create
```
--------------------------------
### Configure Rsbuild Build and Start Scripts in package.json
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Add these scripts to your `package.json` to build your Rsbuild application and start it using `srvx`.
```json
"build": "rsbuild build",
"start": "srvx --prod -s dist/client dist/server/index.js"
```
--------------------------------
### Root Route and Document Setup for TanStack Start React App
Source: https://tanstack.com/start/latest/docs/framework/react/examples/start-trellaux
This comprehensive snippet defines the main application structure, including the root route with context, head content (meta, links, SEO), error/not found components, and the `RootDocument` component for the HTML shell. It integrates TanStack Router and React Query devtools.
```tsx
///
import { ReactQueryDevtools } from '@tanstack/react-query-devtools/production'
import {
HeadContent,
Link,
Outlet,
Scripts,
createRootRouteWithContext,
useRouterState,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import * as React from 'react'
import { Toaster } from 'react-hot-toast'
import type { QueryClient } from '@tanstack/react-query'
import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary'
import { IconLink } from '~/components/IconLink'
import { NotFound } from '~/components/NotFound'
import appCss from '~/styles/app.css?url'
import { seo } from '~/utils/seo'
import { Loader } from '~/components/Loader'
export const Route = createRootRouteWithContext<{
queryClient: QueryClient
}>()({
head: () => ({
meta: [
{
charSet: 'utf-8',
},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1',
},
...seo({
title:
'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework',
description: `TanStack Start is a type-safe, client-first, full-stack React framework. `,
}),
],
links: [
{ rel: 'stylesheet', href: appCss },
{
rel: 'apple-touch-icon',
sizes: '180x180',
href: '/apple-touch-icon.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '32x32',
href: '/favicon-32x32.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '16x16',
href: '/favicon-16x16.png',
},
{ rel: 'manifest', href: '/site.webmanifest', color: '#fffff' },
{ rel: 'icon', href: '/favicon.ico' },
],
}),
errorComponent: (props) => {
return (
)
},
notFoundComponent: () => ,
component: RootComponent,
})
function RootComponent() {
return (
)
}
function RootDocument({ children }: { children: React.ReactNode }) {
return (
Trellaux
a TanStack Demo
{/*
*/}
{children}
)
}
function LoadingIndicator() {
const isLoading = useRouterState({ select: (s) => s.isLoading })
return (
)
}
```
--------------------------------
### TanStack Start Default Project Structure
Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/reading-writing-file.md
This snippet illustrates the default directory and file structure of a newly created TanStack Start project, showing the organization of routes, components, and configuration files.
```plaintext
/devjokes
├── src/
│ ├── routes/
│ │ ├── demo/ # Demo routes
│ │ ├── __root.tsx # Root layout
│ │ └── index.tsx # Home page
│ ├── components/ # React components
│ ├── data/ # Data files
│ ├── router.tsx # Router configuration
│ ├── routeTree.gen.ts # Generated route tree
│ └── styles.css # Global styles
├── public/ # Static assets
├── vite.config.ts or rsbuild.config.ts # TanStack Start configuration
├── package.json # Project dependencies
└── tsconfig.json # TypeScript configuration
```
--------------------------------
### Install TypeScript and React Type Definitions
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Installs TypeScript and essential type definitions for React, React DOM, and Node.js as development dependencies.
```shell
npm i -D typescript @types/react @types/react-dom @types/node
```
--------------------------------
### Install Markdown Processing Dependencies
Source: https://tanstack.com/start/latest/docs/framework/react/guide/rendering-markdown.md
Install the necessary packages for parsing, transforming, and rendering markdown content into HTML, including support for GitHub Flavored Markdown and heading autolinking.
```bash
npm install unified remark-parse remark-gfm remark-rehype rehype-raw rehype-slug rehype-autolink-headings rehype-stringify shiki html-react-parser gray-matter
```
--------------------------------
### Configure Vite for TanStack Start
Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md
This configuration file sets up Vite with TanStack Start, React, Tailwind CSS, and Nitro plugins, defining server port, path resolution, and router directory.
```ts
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { nitro } from 'nitro/vite'
export default defineConfig({
server: {
port: 3000,
},
resolve: {
// Enables Vite to resolve imports using path aliases.
tsconfigPaths: true,
},
plugins: [
tailwindcss(),
tanstackStart({
srcDirectory: 'src', // This is the default
router: {
// Specifies the directory TanStack Router uses for your routes.
routesDirectory: 'app', // Defaults to "routes", relative to srcDirectory
},
}),
viteReact(),
nitro(),
],
})
```
--------------------------------
### Bun Server Startup and Asset Loading Output
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Example console output showing the Bun server's startup, asset preloading, and on-demand serving details.
```txt
📦 Loading static assets from ./dist/client...
Max preload size: 5.00 MB
📁 Preloaded into memory:
/assets/index-a1b2c3d4.js 45.23 kB │ gzip: 15.83 kB
/assets/index-e5f6g7h8.css 12.45 kB │ gzip: 4.36 kB
💾 Served on-demand:
/assets/vendor-i9j0k1l2.js 245.67 kB │ gzip: 86.98 kB
✅ Preloaded 2 files (57.68 KB) into memory
🚀 Server running at http://localhost:3000
```
--------------------------------
### Start Bun Server with Verbose Logging
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Enable detailed logging for asset preloading to observe server behavior during startup and operation.
```sh
ASSET_PRELOAD_VERBOSE_LOGGING=true bun run server.ts
```
--------------------------------
### Install Nitro for TanStack Start Deployment
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Installs the Nitro package, which provides an agnostic layer for deploying TanStack Start applications to various hostings.
```bash
npm install nitro
```
--------------------------------
### Understand the project structure
Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/fetching-external-api.md
Illustrates the directory and file structure of a newly created TanStack Start project, highlighting key files and folders.
```text
/movie-discovery
├── src/
│ ├── routes/
│ │ ├── __root.tsx # Root layout
│ │ ├── index.tsx # Home page
│ │ └── fetch-movies.tsx # Movie fetching route
│ ├── types/
│ │ └── movie.ts # Movie type definitions
│ ├── router.tsx # Router configuration
│ ├── routeTree.gen.ts # Generated route tree
│ └── styles.css # Global styles
├── public/ # Static assets
├── vite.config.ts or rsbuild.config.ts # TanStack Start configuration
├── package.json # Project dependencies
└── tsconfig.json # TypeScript configuration
```
--------------------------------
### Install Tailwind CSS v4 with Vite
Source: https://tanstack.com/start/latest/docs/framework/react/guide/tailwind-integration.md
Installs Tailwind CSS and its Vite integration for use in a TanStack Start project.
```shell
npm install tailwindcss @tailwindcss/vite
```
--------------------------------
### Install Tailwind CSS v4 with Rsbuild
Source: https://tanstack.com/start/latest/docs/framework/react/guide/tailwind-integration.md
Installs Tailwind CSS, PostCSS, and the PostCSS integration for Rsbuild in a TanStack Start project.
```shell
npm install tailwindcss @tailwindcss/postcss postcss
```
--------------------------------
### Create a new TanStack Start project
Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/reading-writing-file.md
Use the TanStack CLI to initialize a new project named 'devjokes' and navigate into its directory.
```bash
pnpx @tanstack/cli@latest create devjokes
cd devjokes
```
--------------------------------
### Run Development Server
Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md
Executes the development server command to start the application after migration.
```sh
npm run dev
```
--------------------------------
### Install Rsbuild and React Plugin Dev Dependencies
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Installs Rsbuild and its official React plugin as development dependencies for a new React project setup.
```shell
npm i -D @rsbuild/core @rsbuild/plugin-react
```
--------------------------------
### Start Bun Production Server (Default)
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Run the custom Bun server implementation with default configurations to serve your React application.
```sh
bun run server.ts
```
--------------------------------
### Initialize a New Project Directory
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Use these shell commands to create a new project folder, navigate into it, and initialize a new npm project.
```shell
mkdir myApp
cd myApp
npm init -y
```
--------------------------------
### Install Vite and React Plugin Dev Dependencies
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Installs Vite and its official React plugin as development dependencies for a new React project setup.
```shell
npm i -D vite @vitejs/plugin-react
```
--------------------------------
### Deploy to Netlify using CLI
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Use the Netlify CLI to deploy your application. If it's a new project, the CLI will guide you through initialization and build settings.
```bash
npx netlify deploy
```
--------------------------------
### Install Cloudflare Vite Plugin and Wrangler (pnpm)
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Installs the necessary development dependencies for deploying a TanStack Start application to Cloudflare Workers using pnpm.
```bash
pnpm add -D @cloudflare/vite-plugin wrangler
```
--------------------------------
### Define a GET Server Route with createFileRoute
Source: https://tanstack.com/start/latest/docs/framework/react/guide/server-routes.md
Use the `server` property within `createFileRoute` to define HTTP method handlers for a specific route. This example shows a basic GET handler returning a text response.
```typescript
// routes/hello.ts
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/hello')({
server: {
handlers: {
GET: async ({ request }) => {
return new Response('Hello, World! from ' + request.url)
}
}
}
})
```
--------------------------------
### Set Custom Headers in React Router GET Handler
Source: https://tanstack.com/start/latest/docs/framework/react/guide/server-routes.md
Use the `Response` constructor's second argument to define custom HTTP headers for a server route's GET handler. This example sets the `Content-Type` header to `text/plain`.
```ts
// routes/hello.ts
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/hello')({
server: {
handlers: {
GET: async ({ request }) => {
return new Response('Hello, World!', {
headers: {
'Content-Type': 'text/plain',
},
})
},
},
},
})
// Visit /hello to see the response
// Hello, World!
```
--------------------------------
### Create a Static Sitemap XML File
Source: https://tanstack.com/start/latest/docs/framework/react/guide/seo.md
Provides an example of a static sitemap.xml file to be placed in the public directory for simple sites with known, unchanging structures.
```xml
https://myapp.com/daily1.0https://myapp.com/aboutmonthly
```
--------------------------------
### Import CSS Modules in React Start
Source: https://tanstack.com/start/latest/docs/framework/react/guide/css-styling.md
Use this import pattern for CSS modules to get scoped class names attached to a route chunk, leveraging Start's manifest discovery for matched routes and supporting static Early Hints or CSS inlining.
```javascript
import styles from './card.module.css'
```
--------------------------------
### Create .env File
Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/fetching-external-api.md
Use the `touch` command to create an empty `.env` file in the project root for storing environment variables.
```bash
touch .env
```
--------------------------------
### Create a Static robots.txt File
Source: https://tanstack.com/start/latest/docs/framework/react/guide/seo.md
Shows a basic static robots.txt file to be placed in the public directory, allowing all user-agents and specifying the sitemap location.
```txt
// public/robots.txt
User-agent: *
Allow: /
Sitemap: https://myapp.com/sitemap.xml
```
--------------------------------
### Root Route and Document Setup in TanStack Start React
Source: https://tanstack.com/start/latest/docs/framework/react/examples/start-convex-trellaux
This snippet defines the root route for a TanStack Start application, including head content, error boundaries, and the main document structure with devtools integration. It sets up global meta tags, links, and defines the main layout components.
```typescript
///
import { ReactQueryDevtools } from '@tanstack/react-query-devtools/production'
import {
Link,
Outlet,
createRootRouteWithContext,
useRouterState,
HeadContent,
Scripts,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import * as React from 'react'
import { Toaster } from 'react-hot-toast'
import type { QueryClient } from '@tanstack/react-query'
import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary'
import { IconLink } from '~/components/IconLink'
import { NotFound } from '~/components/NotFound'
import appCss from '~/styles/app.css?url'
import { seo } from '~/utils/seo'
import { Loader } from '~/components/Loader'
export const Route = createRootRouteWithContext<{
queryClient: QueryClient
}>()({
head: () => ({
meta: [
{
charSet: 'utf-8',
},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1',
},
...seo({
title:
'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework',
description: `TanStack Start is a type-safe, client-first, full-stack React framework. `,
}),
],
links: [
{ rel: 'stylesheet', href: appCss },
{
rel: 'apple-touch-icon',
sizes: '180x180',
href: '/apple-touch-icon.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '32x32',
href: '/favicon-32x32.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '16x16',
href: '/favicon-16x16.png',
},
{ rel: 'manifest', href: '/site.webmanifest', color: '#fffff' },
{ rel: 'icon', href: '/favicon.ico' },
],
}),
errorComponent: (props) => {
return (
)
},
notFoundComponent: () => ,
component: RootComponent,
})
function RootComponent() {
return (
)
}
function RootDocument({ children }: { children: React.ReactNode }) {
return (
Trellaux
a TanStack Demo
{/*
*/}
{children}
)
}
function LoadingIndicator() {
const isLoading = useRouterState({ select: (s) => s.isLoading })
return (
)
}
```
--------------------------------
### Original Relative CSS URL Reference
Source: https://tanstack.com/start/latest/docs/framework/react/guide/css-styling.md
This example shows a relative URL reference within a CSS file before Start performs URL rebasing for inlined stylesheets.
```css
.card {
background-image: url('./dot.svg');
}
```
--------------------------------
### Demonstrate Middleware Execution Order
Source: https://tanstack.com/start/latest/docs/framework/react/guide/middleware.md
This example illustrates the dependency-first execution order of global and server function middleware, showing the sequence of console logs.
```tsx
import { createMiddleware, createServerFn } from '@tanstack/react-start'
const globalMiddleware1 = createMiddleware({ type: 'function' }).server(
async ({ next }) => {
console.log('globalMiddleware1')
return next()
},
)
const globalMiddleware2 = createMiddleware({ type: 'function' }).server(
async ({ next }) => {
console.log('globalMiddleware2')
return next()
},
)
const a = createMiddleware({ type: 'function' }).server(async ({ next }) => {
console.log('a')
return next()
})
const b = createMiddleware({ type: 'function' })
.middleware([a])
.server(async ({ next }) => {
console.log('b')
return next()
})
const c = createMiddleware({ type: 'function' })
.middleware()
.server(async ({ next }) => {
console.log('c')
return next()
})
const d = createMiddleware({ type: 'function' })
.middleware([b, c])
.server(async () => {
console.log('d')
})
const fn = createServerFn()
.middleware([d])
.server(async () => {
console.log('fn')
})
```
--------------------------------
### Start Bun Server with Custom Port
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Launch the Bun server on a specified port by setting the PORT environment variable.
```sh
PORT=8080 bun run server.ts
```
--------------------------------
### Create Isomorphic Function with Client-Only Implementation (React Start)
Source: https://tanstack.com/start/latest/docs/framework/react/guide/environment-functions.md
This example shows `createIsomorphicFn()` with only a client-side implementation. The function will execute on the client and return `undefined` (no-op) on the server.
```tsx
import { createIsomorphicFn } from '@tanstack/react-start'
const clientImplementationOnly = createIsomorphicFn().client(() => 'client')
const client = clientImplementationOnly()
// ℹ️ On the **server**, it is no-op (returns `undefined`)
// ℹ️ On the **client**, it returns `'client'`.
```
--------------------------------
### Create Isomorphic Function with Server-Only Implementation (React Start)
Source: https://tanstack.com/start/latest/docs/framework/react/guide/environment-functions.md
This example demonstrates `createIsomorphicFn()` with only a server-side implementation. The function will execute on the server and return `undefined` (no-op) on the client.
```tsx
import { createIsomorphicFn } from '@tanstack/react-start'
const serverImplementationOnly = createIsomorphicFn().server(() => 'server')
const server = serverImplementationOnly()
// ℹ️ On the **server**, it returns `'server'`.
// ℹ️ On the **client**, it is no-op (returns `undefined`)
```
--------------------------------
### Chaining Middleware with Fetch Overrides in TanStack React Start
Source: https://tanstack.com/start/latest/docs/framework/react/guide/middleware.md
This example illustrates how fetch implementations are prioritized when multiple middlewares are chained. The fetch provided by the last middleware in the chain takes precedence over earlier ones.
```tsx
import { createMiddleware, createServerFn } from '@tanstack/react-start'
import type { CustomFetch } from '@tanstack/react-start'
const firstMiddleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
const firstFetch: CustomFetch = (url, init) => {
const headers = new Headers(init?.headers)
headers.set('X-From', 'first-middleware')
return fetch(url, { ...init, headers })
}
return next({ fetch: firstFetch })
},
)
const secondMiddleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
const secondFetch: CustomFetch = (url, init) => {
const headers = new Headers(init?.headers)
headers.set('X-From', 'second-middleware')
return fetch(url, { ...init, headers })
}
return next({ fetch: secondFetch })
},
)
const myServerFn = createServerFn()
.middleware([firstMiddleware, secondMiddleware])
.handler(async () => {
// Request will have X-From: 'second-middleware'
// because secondMiddleware's fetch overrides firstMiddleware's fetch
return { message: 'Hello' }
})
```
--------------------------------
### Analyze Client Bundle for Server-Only Code (Bash)
Source: https://tanstack.com/start/latest/docs/framework/react/guide/execution-model.md
Use these commands to build the client bundle and then manually inspect the output directory for any unintended server-only imports.
```bash
# Analyze client bundle
npm run build
# Check dist/client for any server-only imports
```
--------------------------------
### Integrate New Relic with TanStack Start SSR Handler
Source: https://tanstack.com/start/latest/docs/framework/react/guide/observability.md
This `server.tsx` example demonstrates how to integrate New Relic into the `createStartHandler` to set controller names and add custom attributes based on route IDs for SSR transactions. Ensure `newrelic` is the first import.
```tsx
// server.tsx
import newrelic from 'newrelic' // Make sure this is the first import
import {
createStartHandler,
defaultStreamHandler,
defineHandlerCallback,
} from '@tanstack/react-start/server'
import type { ServerEntry } from '@tanstack/react-start/server-entry'
const customHandler = defineHandlerCallback(async (ctx) => {
// We do this so that transactions are grouped under the route ID instead of unique URLs
const matches = ctx.router?.state?.matches ?? []
const leaf = matches[matches.length - 1]
const routeId = leaf?.routeId ?? new URL(ctx.request.url).pathname
newrelic.setControllerName(routeId, ctx.request.method ?? 'GET')
newrelic.addCustomAttributes({
'route.id': routeId,
'http.method': ctx.request.method,
'http.path': new URL(ctx.request.url).pathname,
// Any other custom attributes you want to add
})
return defaultStreamHandler(ctx)
})
export default {
fetch(request) {
const handler = createStartHandler(customHandler)
return handler(request)
},
} satisfies ServerEntry
```
--------------------------------
### Build React Application with Bun
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Use this command to build your React application for production deployment using the Bun runtime.
```sh
bun run build
```
--------------------------------
### Configure Global Request Middleware
Source: https://tanstack.com/start/latest/docs/framework/react/guide/middleware.md
To apply middleware to every request handled by Start, create `src/start.ts` and use `createStart` to define `requestMiddleware`.
```tsx
// src/start.ts
import { createStart, createMiddleware } from '@tanstack/react-start'
const myGlobalMiddleware = createMiddleware().server(() => {
//...
})
export const startInstance = createStart(() => {
return {
requestMiddleware: [myGlobalMiddleware]
}
})
```
--------------------------------
### Run Application Build Command
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Execute this command to build your application using the configured `build` script.
```sh
npm run build
```
--------------------------------
### Configure Early Hints in React Start Server Entry
Source: https://tanstack.com/start/latest/docs/framework/react/guide/early-hints.md
Add the `onEarlyHints` callback to your `createServerEntry` configuration in `src/server.ts` to send static early hints. This callback receives `phase` and `links` to process.
```tsx
// src/server.ts
import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
export default createServerEntry({
fetch(request) {
return handler.fetch(request, {
onEarlyHints: ({ phase, links }) => {
if (phase !== 'static' || !links.length) return
// Send `links` with your runtime-specific 103 API.
},
})
},
})
```
--------------------------------
### Configure Vite with TanStack Start and React Plugins
Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md
Defines the Vite configuration, including server port, TypeScript path resolution, and plugins for TanStack Start and React. Ensure the React plugin is listed after the Start plugin.
```ts
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'
export default defineConfig({
server: {
port: 3000,
},
resolve: {
tsconfigPaths: true,
},
plugins: [
tanstackStart(),
// react's vite plugin must come after start's vite plugin
viteReact(),
],
})
```
--------------------------------
### Install Vite RSC Dependencies
Source: https://tanstack.com/start/latest/docs/framework/react/guide/server-components.md
Install the necessary `@vitejs/plugin-rsc` dependency for Vite projects to enable Server Components.
```bash
npm install -D @vitejs/plugin-rsc
# or
pnpm add -D @vitejs/plugin-rsc
# or
yarn add -D @vitejs/plugin-rsc
# or
bun add -D @vitejs/plugin-rsc
```
--------------------------------
### Manual Netlify Configuration with netlify.toml
Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md
Manually configure Netlify build and development settings by creating a `netlify.toml` file in your project root.
```toml
[build]
command = "vite build"
publish = "dist/client"
[dev]
command = "vite dev"
port = 3000
```
--------------------------------
### Create Type-Safe Server Entry Point
Source: https://tanstack.com/start/latest/docs/framework/react/guide/server-entry-point.md
Shows how to create a type-safe server entry point using `createServerEntry` and the default handler from `@tanstack/react-start/server-entry`.
```tsx
// src/server.ts
import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
export default createServerEntry({
fetch(request) {
return handler.fetch(request)
},
})
```
--------------------------------
### Install Tailwind CSS with Rsbuild
Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md
Install Tailwind CSS and its PostCSS plugin as development dependencies for projects using Rsbuild.
```sh
npm i -D @tailwindcss/postcss tailwindcss
```
--------------------------------
### Install Tailwind CSS with Vite
Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md
Install Tailwind CSS and its Vite plugin as development dependencies for projects using Vite.
```sh
npm i -D @tailwindcss/vite tailwindcss
```