### Install dependencies and start development server Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/fetching-external-api.md Install project dependencies and start the development server after project setup. ```bash pnpm i pnpm dev ``` -------------------------------- ### Clone and Run a Basic TanStack Router Example Source: https://tanstack.com/start/latest/docs/framework/react/getting-started.md Clone the 'start-basic' example project to get a foundational TanStack Start application. After cloning, navigate to the project directory, install dependencies, and start the development server. ```bash npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic cd start-basic npm install npm run dev ``` -------------------------------- ### Clone and Run a Custom TanStack Router Example Source: https://tanstack.com/start/latest/docs/framework/react/getting-started.md Clone a TanStack Start example project by replacing 'EXAMPLE_SLUG' with the desired example's slug. This allows for starting with different pre-configured setups. Remember to install dependencies and run the development server afterwards. ```bash npx gitpick TanStack/router/tree/main/examples/react/EXAMPLE_SLUG my-new-project cd my-new-project npm install npm run dev ``` -------------------------------- ### Example Server Startup Output Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md This shows a typical console output when the server starts, detailing asset loading, preloaded files, and the server's running address. ```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 ``` -------------------------------- ### Install Core TanStack Start and React Dependencies Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md Install the essential TanStack Start and React Router packages, followed by React and React DOM, which are fundamental for your application. ```shell npm i @tanstack/react-start @tanstack/react-router ``` ```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 for TanStack Start to configure your build for Netlify deployment and enable local dev emulation. ```bash npm install --save-dev @netlify/vite-plugin-tanstack-start ``` ```bash pnpm add --save-dev @netlify/vite-plugin-tanstack-start ``` -------------------------------- ### Install Core TanStack Start Dependencies with Vite Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md Installs the necessary core packages for TanStack Start when using Vite as the build tool. ```sh npm i @tanstack/react-router @tanstack/react-start nitro vite @vitejs/plugin-react ``` -------------------------------- ### Install Nitro for TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md Install the Nitro package to enable agnostic deployment of your TanStack Start application to various hosting platforms. ```bash npm install nitro ``` -------------------------------- ### Install Core TanStack Start Dependencies with Rsbuild Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md Installs the necessary core packages for TanStack Start when using Rsbuild as the build tool. ```sh npm i @tanstack/react-router @tanstack/react-start @rsbuild/core @rsbuild/plugin-react ``` -------------------------------- ### Integrate Database with TanStack Start Server Functions Source: https://tanstack.com/start/latest/docs/framework/react/guide/databases.md Use any database client within TanStack Start server functions or routes. This example shows abstract database interactions for fetching and creating user data. ```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 }, ) ``` -------------------------------- ### Run npm run start Command Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md Execute the start script defined in package.json to launch the application server. ```sh npm run start ``` -------------------------------- ### Create a new TanStack Start project Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/reading-writing-file.md Initialize a new TanStack Start application named 'devjokes' and navigate into its directory. ```bash pnpx @tanstack/cli@latest create devjokes cd devjokes ``` -------------------------------- ### Configure Static Prerendering with TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/isr.md Integrate TanStack Start's prerendering plugin into your build configuration to generate static routes at build time, improving initial load performance. Examples are provided for Vite and Rsbuild. ```ts import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ tanstackStart({ prerender: { routes: ['/blog', '/blog/posts/*'], crawlLinks: true, }, }), ], }) ``` ```ts import { defineConfig } from '@rsbuild/core' import { pluginReact } from '@rsbuild/plugin-react' import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' export default defineConfig({ plugins: [ pluginReact(), tanstackStart({ prerender: { routes: ['/blog', '/blog/posts/*'], crawlLinks: true, }, }), ], }) ``` -------------------------------- ### Example File Structure for Dynamic Route Source: https://tanstack.com/start/latest/docs/framework/react/guide/routing.md This snippet illustrates the directory structure for defining a dynamic route in TanStack Start, specifically for a post detail page. ```plaintext src/ ├── routes │ ├── posts/$postId.tsx ``` -------------------------------- ### Run Development Server Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md Execute this command in your terminal to start the development server and view your TanStack Start application. ```sh npm run dev ``` -------------------------------- ### Create a New TanStack Start Application Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md Use this command to initialize a new TanStack Start project using the official CLI. ```bash npx @tanstack/cli@latest create ``` -------------------------------- ### Isomorphic Code Example in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/execution-model.md This snippet demonstrates that functions and route loaders in TanStack Start are isomorphic by default, executing on both the server during SSR and the client during navigation. ```tsx // ✅ This runs on BOTH server and client function formatPrice(price: number) { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', }).format(price) } // ✅ Route loaders are ISOMORPHIC export const Route = createFileRoute('/products')({ loader: async () => { // This runs on server during SSR AND on client during navigation const response = await fetch('/api/products') return response.json() }, }) ``` -------------------------------- ### Configure Server Entry for Static Early Hints (TanStack Start) Source: https://tanstack.com/start/latest/docs/framework/react/guide/early-hints.md Add onEarlyHints to your createServerEntry configuration in src/server.ts to send static Early Hints. This example sends hints as early as possible during the 'static' phase, before route loading completes. ```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. }, }) }, }) ``` -------------------------------- ### Install Tailwind CSS v4 with Vite Source: https://tanstack.com/start/latest/docs/framework/react/guide/tailwind-integration.md Install Tailwind CSS and its Vite integration for use with TanStack Start. ```shell npm install tailwindcss @tailwindcss/vite ``` -------------------------------- ### Run TanStack Start Server with New Relic Agent (Bash) Source: https://tanstack.com/start/latest/docs/framework/react/guide/observability.md Use this command to start your TanStack Start server, preloading the New Relic agent for monitoring. ```bash node -r newrelic .output/server/index.mjs ``` -------------------------------- ### Example Nested Route File Structure Source: https://tanstack.com/start/latest/docs/framework/react/guide/routing.md This snippet illustrates how route files are organized in a nested routing setup, with each file corresponding to a component. ```plaintext routes/ ├── __root.tsx <-- Renders the component ├── posts.tsx <-- Renders the component ├── posts.$postId.tsx <-- Renders the component ``` -------------------------------- ### Install content-collections packages Source: https://tanstack.com/start/latest/docs/framework/react/guide/rendering-markdown.md Installs the core and Vite plugin packages for content-collections using npm. ```bash npm install @content-collections/core @content-collections/vite ``` -------------------------------- ### Vite package.json Build and Start Scripts Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md Configure build and start scripts in package.json for building a Vite application and running it on Node.js. ```json "build": "vite build", "start": "node .output/server/index.mjs" ``` -------------------------------- ### CSS URL Rebasing Example Source: https://tanstack.com/start/latest/docs/framework/react/guide/css-styling.md This snippet demonstrates how Start automatically rewrites relative `url(...)` references in inlined stylesheets to absolute paths relative to the emitted CSS asset URL during the build process. ```css .card { background-image: url('./dot.svg'); } ``` ```css .card { background-image: url(/_build/assets/dot.svg); } ``` -------------------------------- ### Project structure of a TanStack Start application Source: https://tanstack.com/start/latest/docs/framework/react/tutorial/fetching-external-api.md Overview of the default directory and file structure for a TanStack Start project, including key configuration and source files. ```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 ``` -------------------------------- ### Configure Vite for TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md Create a `vite.config.ts` file to configure Vite, including server port, path resolution, and integrating the TanStack Start and React plugins. ```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(), ], }) ``` -------------------------------- ### Configure Rsbuild for TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md Create an `rsbuild.config.ts` file to configure Rsbuild, including server port settings and integrating the React and TanStack Start plugins. ```ts import { defineConfig } from '@rsbuild/core' import { pluginReact } from '@rsbuild/plugin-react' import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' export default defineConfig({ server: { port: 3000, }, plugins: [pluginReact(), tanstackStart()], }) ``` -------------------------------- ### Install Markdown Processing Dependencies Source: https://tanstack.com/start/latest/docs/framework/react/guide/rendering-markdown.md Installs all necessary packages for parsing, transforming, and rendering markdown content into HTML, including syntax highlighting and heading linking. ```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 TypeScript for TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/build-from-scratch.md Create a `tsconfig.json` file with these recommended compiler options to ensure proper TypeScript support in your TanStack Start project. ```json { "compilerOptions": { "jsx": "react-jsx", "moduleResolution": "Bundler", "module": "ESNext", "target": "ES2022", "skipLibCheck": true, "strictNullChecks": true } } ``` -------------------------------- ### Advanced Asset Preload Configuration Examples Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md These examples demonstrate how to optimize memory usage, preload specific assets, disable optional features, and customize Gzip settings using various environment variables. ```sh # Optimize for minimal memory usage ASSET_PRELOAD_MAX_SIZE=1048576 bun run server.ts ``` ```sh # Preload only critical assets ASSET_PRELOAD_INCLUDE_PATTERNS="*.js,*.css" \ ASSET_PRELOAD_EXCLUDE_PATTERNS="*.map,vendor-*" \ bun run server.ts ``` ```sh # Disable optional features ASSET_PRELOAD_ENABLE_ETAG=false \ ASSET_PRELOAD_ENABLE_GZIP=false \ bun run server.ts ``` ```sh # Custom Gzip configuration ASSET_PRELOAD_GZIP_MIN_SIZE=2048 \ ASSET_PRELOAD_GZIP_MIME_TYPES="text/,application/javascript,application/json" \ bun run server.ts ``` -------------------------------- ### Start Bun Production Server Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md Launch the custom Bun production server implementation, leveraging Bun's native APIs for optimal performance. ```sh bun run server.ts ``` -------------------------------- ### Create a Static Sitemap XML File Source: https://tanstack.com/start/latest/docs/framework/react/guide/seo.md This example demonstrates placing a static `sitemap.xml` file in the `public` directory for simple sites with known, unchanging structures. ```xml https://myapp.com/ daily 1.0 https://myapp.com/about monthly ``` -------------------------------- ### 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 directory and initialize a `package.json` file for your application. ```shell mkdir myApp cd myApp npm init -y ``` -------------------------------- ### Installing Fontsource for Custom Fonts in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md Install Fontsource packages for desired variable fonts using npm. ```sh npm i -D @fontsource-variable/dm-sans @fontsource-variable/jetbrains-mono ``` -------------------------------- ### Install Tailwind CSS v4 with Rsbuild Source: https://tanstack.com/start/latest/docs/framework/react/guide/tailwind-integration.md Install Tailwind CSS, PostCSS, and the PostCSS integration for use with Rsbuild in TanStack Start. ```shell npm install tailwindcss @tailwindcss/postcss postcss ``` -------------------------------- ### Correctly Define and Bundle Client-Side Environment Variables Source: https://tanstack.com/start/latest/docs/framework/react/guide/environment-variables.md Shows how to correctly prefix client-side environment variables (e.g., VITE_API_KEY) and ensure they are bundled for production builds. ```bash # ❌ Won't work in client code API_KEY=abc123 # ✅ Works in client code VITE_API_KEY=abc123 # ❌ Won't bundle the variable (assuming it is not set in the environment of the build) npm run build # ✅ Works in client code and will bundle the variable for production VITE_API_KEY=abc123 npm run build ``` -------------------------------- ### Build Application with Bun Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md Run the build process using Bun to prepare the application for deployment. ```sh bun run build ``` -------------------------------- ### Migrating Next.js API Routes to TanStack Start Server Routes Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md This snippet demonstrates how to define a server route in TanStack Start, replacing a Next.js `GET` export with `createFileRoute` and `server.handlers`. ```ts - export async function GET() { // [!code --] + export const Route = createFileRoute('/api/hello')({ // [!code ++] + server: { // [!code ++] + handlers: { // [!code ++] + GET: async () => { // [!code ++] + return Response.json("Hello, World!") + } // [!code ++] + } // [!code ++] + } // [!code ++] + }) // [!code ++] ``` -------------------------------- ### Handle Errors in TanStack Start Server Functions Source: https://tanstack.com/start/latest/docs/framework/react/guide/observability.md This example demonstrates how to implement error handling within a TanStack Start server function, logging detailed server errors and returning a user-friendly message. ```tsx // Server function error handling const riskyOperation = createServerFn().handler(async () => { try { return await performOperation() } catch (error) { // Log server errors with context console.error('[SERVER ERROR]:', { error: error.message, stack: error.stack, timestamp: new Date().toISOString(), // Add request context if available }) // Return user-friendly error throw new Error('Operation failed. Please try again.') } }) ``` -------------------------------- ### Define a GET Server Route with createFileRoute (TypeScript) Source: https://tanstack.com/start/latest/docs/framework/react/guide/server-routes.md Use the `server` property within `createFileRoute` to define HTTP handlers for a 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) }, }, }, }) ``` -------------------------------- ### Run Server with Custom Port and Verbose Logging Source: https://tanstack.com/start/latest/docs/framework/react/guide/hosting.md Use these commands to start the server with a specific port or enable detailed asset preloading logs for debugging. ```bash PORT=8080 bun run server.ts ``` ```bash ASSET_PRELOAD_VERBOSE_LOGGING=true bun run server.ts ``` -------------------------------- ### Deploy TanStack Start App with Netlify 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, it will prompt for initialization and configure build settings automatically. ```bash npx netlify deploy ``` -------------------------------- ### Setting Response Headers in TanStack Start GET Handler (TypeScript) Source: https://tanstack.com/start/latest/docs/framework/react/guide/server-routes.md Use this snippet to set custom HTTP headers, such as 'Content-Type', in a server route's GET handler by providing a headers object to the Response constructor. ```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!', { headers: { 'Content-Type': 'text/plain', }, }) }, }, }, }) // Visit /hello to see the response // Hello, World! ``` -------------------------------- ### Create a Static robots.txt File Source: https://tanstack.com/start/latest/docs/framework/react/guide/seo.md This example shows how to place a static `robots.txt` file in the `public` directory to define crawling rules and reference the sitemap. ```txt // public/robots.txt User-agent: * Allow: / Sitemap: https://myapp.com/sitemap.xml ``` -------------------------------- ### Basic Server Entry Point with createServerEntry 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 delegate the fetch request to the default handler. ```tsx // src/server.ts import handler, { createServerEntry } from '@tanstack/react-start/server-entry' export default createServerEntry({ fetch(request) { return handler.fetch(request) } }) ``` -------------------------------- ### Database Connection Configuration with Environment Variables Source: https://tanstack.com/start/latest/docs/framework/react/guide/environment-variables.md Demonstrates how to configure a database connection using server-side environment variables for URL, max connections, and SSL settings. ```typescript // src/lib/database.ts import { createServerFn } from '@tanstack/react-start' const getDatabaseConnection = createServerFn().handler(async () => { const config = { url: process.env.DATABASE_URL, maxConnections: parseInt(process.env.DB_MAX_CONNECTIONS || '10'), ssl: process.env.NODE_ENV === 'production', } return createConnection(config) }) ``` -------------------------------- ### Trace TanStack Start Server Function with OpenTelemetry Source: https://tanstack.com/start/latest/docs/framework/react/guide/observability.md This example demonstrates how to manually trace a TanStack Start server function using OpenTelemetry. It wraps the function's logic in an active span, setting attributes and handling span status based on success or error. ```tsx // Server function tracing import { trace, SpanStatusCode } from '@opentelemetry/api' const tracer = trace.getTracer('tanstack-start') const getUserWithTracing = createServerFn({ method: 'GET' }) .validator((id: string) => id) .handler(async ({ data: id }) => { return tracer.startActiveSpan('get-user', async (span) => { span.setAttributes({ 'user.id': id, operation: 'database.query' }) try { const user = await db.users.findUnique({ where: { id } }) span.setStatus({ code: SpanStatusCode.OK }) return user } catch (error) { span.recordException(error) span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }) throw error } finally { span.end() } }) }) ``` -------------------------------- ### Reuse Hydrate props Source: https://tanstack.com/start/latest/docs/framework/react/guide/deferred-hydration.md Example demonstrating how to reuse `Hydrate` component props using `HydrateOptions` for better organization and type safety in TanStack Start. ```tsx import { Hydrate } from '@tanstack/react-start' import type { HydrateOptions } from '@tanstack/react-start' import { visible } from '@tanstack/react-start/hydration' const belowFoldProps = { when: () => visible({ rootMargin: '800px' }) } satisfies HydrateOptions export function Page() { return ( { await preload() }} > ) } ``` -------------------------------- ### Root Route 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 for a TanStack Start application, integrating Material UI with Emotion for styling. It sets up ThemeProvider, CssBaseline, and CacheProvider to ensure Material UI components are correctly styled throughout the application. ```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} ) } ``` -------------------------------- ### Composing Middleware in TanStack React Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/middleware.md Use the `middleware` method to chain multiple middleware functions, allowing one middleware to depend on another. This example shows `authMiddleware` depending on `loggingMiddleware`. ```tsx import { createMiddleware } from '@tanstack/react-start' const loggingMiddleware = createMiddleware().server(() => { //... }) const authMiddleware = createMiddleware() .middleware([loggingMiddleware]) .server(() => { //... }) ``` -------------------------------- ### Create Health Check Endpoint in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/observability.md This code defines a server-side GET handler for a '/health' route, providing system status, uptime, memory usage, and database connectivity checks. ```tsx // routes/health.ts import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/health')({ server: { handlers: { GET: async () => { const checks = { status: 'healthy', timestamp: new Date().toISOString(), uptime: process.uptime(), memory: process.memoryUsage(), database: await checkDatabase(), version: process.env.npm_package_version, } return Response.json(checks) }, }, }, }) async function checkDatabase() { try { await db.raw('SELECT 1') return { status: 'connected', latency: 0 } } catch (error) { return { status: 'error', error: error.message } } } ``` -------------------------------- ### Sending Server Context to Client in TanStack React Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/middleware.md This example demonstrates how to create server middleware to send data (like the current time) to the client using `sendContext`, and then access that data in client middleware. ```tsx import { createMiddleware } from '@tanstack/react-start' const serverTimer = createMiddleware({ type: 'function' }).server( async ({ next }) => { return next({ sendContext: { // Send the current time to the client timeFromServer: new Date(), }, }) }, ) const requestLogger = createMiddleware({ type: 'function' }) .middleware([serverTimer]) .client(async ({ next }) => { const result = await next() // Woah! We have the time from the server! console.log('Time from the server:', result.context.timeFromServer) return result }) ``` -------------------------------- ### 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 how nested middleware and server functions are processed sequentially. ```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') }) ``` -------------------------------- ### SSR Inheritance Example: Data-Only and False Overrides in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/selective-ssr.md Shows another scenario of SSR inheritance, where `data-only` and `false` settings on child routes can successfully override less restrictive parent settings. ```plaintext root { ssr: undefined } posts { ssr: 'data-only' } $postId { ssr: true } details { ssr: false } ``` -------------------------------- ### Configuring Global Fetch with createStart (TypeScript) Source: https://tanstack.com/start/latest/docs/framework/react/guide/middleware.md Shows how to set a default custom fetch for all server functions globally using `createStart`, useful for application-wide request handling like logging or retry logic. ```tsx // src/start.ts import { createStart } from '@tanstack/react-start' import type { CustomFetch } from '@tanstack/react-start' const globalFetch: CustomFetch = async (url, init) => { console.log('Global fetch:', url) // Add retry logic, telemetry, etc. return fetch(url, init) } export const startInstance = createStart(() => { return { serverFns: { fetch: globalFetch, }, } }) ``` -------------------------------- ### Example blog post markdown file Source: https://tanstack.com/start/latest/docs/framework/react/guide/rendering-markdown.md A sample markdown file demonstrating front matter for title, published date, authors, and description, followed by markdown content including an image and a JavaScript code block. ```markdown ## title: Hello World published: 2024-01-15 authors: - Jane Doe description: My first blog post --- ![Hero Image](/images/hero.jpg) Welcome to my blog! This is my first post. ## Getting Started Here's some content with **bold** and _italic_ text. ```javascript console.log('Hello, world!') ``` ``` -------------------------------- ### Transforming Assets with a Callback in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/cdn-asset-urls.md This example demonstrates configuring `createStartHandler` with a `transformAssets` callback. The callback modifies the asset `href` to point to a CDN and conditionally adds a `crossOrigin` attribute for script assets based on their `kind`. ```tsx // src/server.ts import { createStartHandler, defaultStreamHandler, } from '@tanstack/react-start/server' import { createServerEntry } from '@tanstack/react-start/server-entry' const handler = createStartHandler({ handler: defaultStreamHandler, transformAssets: (asset) => { const href = `https://cdn.example.com${asset.url}` if (asset.kind === 'script') { return { href, crossOrigin: 'anonymous', } } return { href } }, }) export default createServerEntry({ fetch: handler }) ``` -------------------------------- ### Configure Static CDN Prefix with transformAssets in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/cdn-asset-urls.md Configure `createStartHandler` with a string prefix to rewrite all Start-managed asset URLs with a static CDN origin. URLs remain unchanged if the prefix is empty. ```tsx // src/server.ts import { createStartHandler, defaultStreamHandler, } from '@tanstack/react-start/server' import { createServerEntry } from '@tanstack/react-start/server-entry' const handler = createStartHandler({ handler: defaultStreamHandler, transformAssets: process.env.CDN_ORIGIN || '', }) export default createServerEntry({ fetch: handler }) ``` -------------------------------- ### GET /llms.txt Source: https://tanstack.com/start/latest/docs/framework/react/guide/geo.md This endpoint serves a plain text file named 'llms.txt', which provides guidance and information to AI systems, similar to how 'robots.txt' guides web crawlers. It includes general information about the application and links to documentation. ```APIDOC ## GET /llms.txt ### Description This endpoint delivers a plain text file intended for AI systems, offering guidance and context about the application. It can include a description, documentation links, and other relevant information for AI consumption. ### Method GET ### Endpoint /llms.txt ### Response #### Success Response (200) - **content** (string) - A plain text file containing information for AI systems. #### Response Example ```text # My App > My App is a platform for building modern web applications. ## Documentation - Getting Started: https://myapp.com/docs/getting-started - API Reference: https://myapp.com/docs/api ``` ``` -------------------------------- ### Environment File Loading Order Source: https://tanstack.com/start/latest/docs/framework/react/guide/environment-variables.md TanStack Start automatically loads environment files in this specific order, allowing for local overrides and environment-specific configurations. ```text .env.local # Local overrides (add to .gitignore) .env.production # Production-specific variables .env.development # Development-specific variables .env # Default variables (commit to git) ``` -------------------------------- ### Filter Response Link Headers for Static Assets in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/early-hints.md Use the 'responseLinkHeader.filter' option to control which links are included in the HTTP 'Link' header. This example filters to include only static manifest assets, which is useful for CDN caching. ```tsx handler.fetch(request, { responseLinkHeader: { filter: ({ phase }) => phase === 'static', }, }) ``` -------------------------------- ### Create a New TanStack Project with CLI Source: https://tanstack.com/start/latest/docs/framework/react/getting-started.md Use the TanStack CLI to scaffold a new project locally. You will be prompted to select a package manager and optional add-ons. ```bash npx @tanstack/cli@latest create ``` -------------------------------- ### SSR Inheritance Example: Restrictive Override in TanStack Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/selective-ssr.md Demonstrates how child routes inherit SSR configuration from parents, where inherited values can only become more restrictive. A child setting `ssr: true` will not override a parent's `ssr: false`. ```plaintext root { ssr: undefined } posts { ssr: false } $postId { ssr: true } ``` -------------------------------- ### Configure Environment-Specific Logging with TanStack React Start Source: https://tanstack.com/start/latest/docs/framework/react/guide/observability.md This snippet demonstrates how to create an isomorphic logger that adapts its behavior based on the environment (development vs. production) for both server and client contexts. It includes an example of its usage within a server function to log user data fetching operations. ```tsx // utils/logger.ts import { createIsomorphicFn } from '@tanstack/react-start' type LogLevel = 'debug' | 'info' | 'warn' | 'error' const logger = createIsomorphicFn() .server((level: LogLevel, message: string, data?: any) => { const timestamp = new Date().toISOString() if (process.env.NODE_ENV === 'development') { // Development: Detailed console logging console[level](`[${timestamp}] [${level.toUpperCase()}]`, message, data) } else { // Production: Structured JSON logging console.log( JSON.stringify({ timestamp, level, message, data, service: 'tanstack-start', environment: process.env.NODE_ENV, }), ) } }) .client((level: LogLevel, message: string, data?: any) => { if (process.env.NODE_ENV === 'development') { console[level](`[CLIENT] [${level.toUpperCase()}]`, message, data) } else { // Production: Send to analytics service // analytics.track('client_log', { level, message, data }) } }) // Usage anywhere in your app export { logger } // Example usage const fetchUserData = createServerFn().handler(async ({ data: userId }) => { logger('info', 'Fetching user data', { userId }) try { const user = await db.users.findUnique({ where: { id: userId } }) logger('info', 'User data fetched successfully', { userId }) return user } catch (error) { logger('error', 'Failed to fetch user data', { userId, error: error.message, }) throw error } }) ``` -------------------------------- ### Install Tailwind CSS for Vite Source: https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js.md Installs Tailwind CSS and its Vite plugin as development dependencies. ```sh npm i -D @tailwindcss/vite tailwindcss ```