Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

server-entry-point.md

282 lines12.6 KB

1---
2id: server-entry-point
3title: Server Entry Point
4---
5​
6> [!NOTE]
7> A custom server entry point is **optional**. Without one, TanStack Start uses its built-in entry, which renders requests and converts uncaught errors into HTTP responses automatically.
8​
9The Server Entry Point supports the universal fetch handler format, commonly used by [Cloudflare Workers](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/) and other WinterCG-compatible runtimes.
10​
11The default export must provide a `fetch` method that accepts a `Request` and Start's request options, then returns a `Response` or `Promise<Response>`. Use `createServerEntry` to infer these types and keep the complete callback inside the request's context, including custom error handling. For example, this custom `src/server.ts` delegates to the built-in entry:
12​
13```tsx
14// src/server.ts
15import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
16​
17export default createServerEntry({
18 fetch(request, opts) {
19 return handler.fetch(request, opts)
20 },
21})
22```
23​
24Whether we are statically generating our app or serving it dynamically, the `server.ts` file is the entry point for doing all SSR-related work as well as for handling server routes and server function requests.
25​
26## Configuring a Custom Server Entry
27​
28Start automatically detects `src/server.ts`. If that file is absent, it uses the built-in entry. For a custom entry at another path, configure `server.entry` in your bundler plugin. This path is resolved relative to `srcDirectory`, which defaults to `src`.
29​
30<!-- ::start:tabs variant="bundler" -->
31​
32# Vite
33​
34```ts title="vite.config.ts"
35import { defineConfig } from 'vite'
36import { tanstackStart } from '@tanstack/react-start/plugin/vite'
37import viteReact from '@vitejs/plugin-react'
38​
39export default defineConfig({
40 plugins: [
41 tanstackStart({
42 server: {
43 entry: './server-entry.ts',
44 },
45 }),
46 viteReact(),
47 ],
48})
49```
50​
51# Rsbuild
52​
53```ts title="rsbuild.config.ts"
54import { defineConfig } from '@rsbuild/core'
55import { pluginReact } from '@rsbuild/plugin-react'
56import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
57​
58export default defineConfig({
59 plugins: [
60 pluginReact(),
61 tanstackStart({
62 server: {
63 entry: './server-entry.ts',
64 },
65 }),
66 ],
67})
68```
69​
70<!-- ::end:tabs -->
71​
72## Custom Server Handlers
73​
74You can create custom server handlers to modify how your application is rendered:
75​
76```tsx
77// src/server.ts
78import {
79 createStartHandler,
80 defaultStreamHandler,
81 defineHandlerCallback,
82} from '@tanstack/react-start/server'
83import { createServerEntry } from '@tanstack/react-start/server-entry'
84​
85const customHandler = defineHandlerCallback((ctx) => {
86 // add custom logic here
87 return defaultStreamHandler(ctx)
88})
89​
90const startHandler = createStartHandler(customHandler)
91​
92export default createServerEntry({
93 fetch(request, opts) {
94 return startHandler(request, opts)
95 },
96})
97```
98​
99## Error Handling
100​
101The built-in entry uses `createServerEntry` to catch errors that escape the Start handler and call `handleStartError(error)` inside the active request context. This works without a custom `src/server.ts`. Response helpers such as `setResponseStatus`, `setResponseHeader`, and `setCookie` are applied to the error response.
102​
103For an uncaught error, Start returns a generic JSON error body with status `500` unless a response helper or HTTP-style error property supplies an error status. A thrown `Response` keeps its body and response metadata, with response helpers applied, and loses its body for `HEAD` requests and for statuses `204`, `205`, and `304`, including one selected by a helper. The generic error body Start generates always uses an error status, so only `HEAD` removes it.
104​
105For example, a request to this server route returns `401` with a `WWW-Authenticate` header:
106​
107```tsx
108// src/routes/api/protected.ts
109import { createFileRoute } from '@tanstack/react-router'
110import { createMiddleware } from '@tanstack/react-start'
111import {
112 setResponseHeader,
113 setResponseStatus,
114} from '@tanstack/react-start/server'
115​
116const authMiddleware = createMiddleware().server(() => {
117 setResponseStatus(401, 'Unauthorized')
118 setResponseHeader('www-authenticate', 'Bearer')
119 throw new Error('Unauthorized')
120})
121​
122export const Route = createFileRoute('/api/protected')({
123 server: {
124 middleware: [authMiddleware],
125 handlers: {
126 GET: () => new Response('Protected content'),
127 },
128 },
129})
130```
131​
132Error conversion preserves:
133​
134- Error statuses (`400`-`599`) and their status text from `setResponseStatus`
135- Header operations from the response helpers
136- Cookies from `setCookie` and `appendResponseHeader('set-cookie', ...)`, including multiple `Set-Cookie` headers
137- HTTP-style error metadata such as `error.status`, `error.statusText`, `error.headers`, and `error.cause.headers`
138​
139Start builds a new JSON body for an error, so it never copies the framing and connection headers `Content-Length`, `Content-Encoding`, `Transfer-Encoding`, `Trailer`, `Connection`, `Keep-Alive`, `Proxy-Connection`, and `TE` from error metadata. When `error.cause` is a `Response`, such as a failed upstream `fetch` from any fetch implementation, Start uses its status and status text but none of its headers, because they were written for that upstream reply.
140​
141Explicit helper error statuses, their status text, and header operations take precedence over error metadata. An error response only uses an error status (`400`-`599`). A status set with `setResponseStatus` before the error applies only when it is an error status. A success, redirect, or bodyless status such as `200`, `201`, `302`, or `204` describes the response that the failure replaced, so Start discards it together with its status text and uses the error's own status or `500`. Error metadata such as `error.status` or `error.statusCode` likewise applies only when it is `400` or higher.
142​
143Start logs the error to the server console unless the error's own metadata marks it as an HTTP error with a status of `400` or higher, even when a helper selected the status. The generic JSON body does not expose the error's message or stack.
144​
145Errors that Router handles through route error components do not reach this top-level catch. Server function calls and their request middleware use a separate error response path that preserves the RPC serialization protocol. Failures during initialization, before that path is established, fall back to the top-level error response. Errors in a streamed body after the entry has returned its `Response` cannot replace that response's status or headers.
146​
147You can use `createServerEntry` with your own `try`/`catch`, including for error reporting with Sentry. Your catch runs first; the wrapper converts only errors that escape your callback. Call the handler returned by `createStartHandler(...)` inside that catch, because it rethrows the original uncaught value:
148​
149```tsx
150// src/server.ts
151import {
152 createStartHandler,
153 defaultStreamHandler,
154 handleStartError,
155} from '@tanstack/react-start/server'
156import { createServerEntry } from '@tanstack/react-start/server-entry'
157​
158const startHandler = createStartHandler(defaultStreamHandler)
159​
160export default createServerEntry({
161 async fetch(request, opts) {
162 try {
163 return await startHandler(request, opts)
164 } catch (error) {
165 // Report the original error here, for example to Sentry.
166 return handleStartError(error)
167 }
168 },
169})
170```
171​
172After reporting, choose how to finish the catch:
173​
174- Return `handleStartError(error)` to obtain Start's error response explicitly.
175- Rethrow `error` to let `createServerEntry` produce that same error response.
176- Return your own `Response` to choose its body, status, and headers.
177​
178All three options keep `createServerEntry` and its request context. The first two preserve Start's response-helper state.
179​
180The wrapper creates the request context before calling your `fetch` callback. The entire callback, including its own catch and code after `await`, runs inside that context. Calling the Start handler with the same `Request` reuses it. `handleStartError` therefore uses the correct request's state even when the thrown value is a primitive, or several requests throw the same `Error` object. Start does not attach request state to errors or remember them for a later catch. A catch outside this wrapper cannot recover a completed request's helper state from the error.
181​
182The default export from `@tanstack/react-start/server-entry` is already wrapped. Calling its `fetch` method converts uncaught errors before an outer catch can see them. Use the handler returned by `createStartHandler(...)` inside your callback when you need to catch the original error, as above.
183​
184Delegating to the default entry or another wrapped entry with the same `Request` object shares the current request context. A cloned or rewritten `Request` starts a separate context. When passing a new request to a raw `createStartHandler` handler, wrap that invocation with `createServerEntry` too, so errors are converted before leaving the new context:
185​
186```tsx
187import {
188 createStartHandler,
189 defaultStreamHandler,
190} from '@tanstack/react-start/server'
191import { createServerEntry } from '@tanstack/react-start/server-entry'
192​
193const rewrittenEntry = createServerEntry({
194 fetch: createStartHandler(defaultStreamHandler),
195})
196​
197export default createServerEntry({
198 fetch(request, opts) {
199 const url = new URL(request.url)
200 if (url.pathname === '/legacy-home') {
201 url.pathname = '/'
202 }
203 return rewrittenEntry.fetch(new Request(url, request), opts)
204 },
205})
206```
207​
208The rewritten request owns its response helper state. Catching a raw rewritten handler's error only in the original request's scope would not recover the rewritten request's headers or cookies.
209​
210To replace an uncaught error response completely, return your own response from the custom catch:
211​
212```tsx
213// src/server.ts
214import {
215 createStartHandler,
216 defaultStreamHandler,
217} from '@tanstack/react-start/server'
218import { createServerEntry } from '@tanstack/react-start/server-entry'
219​
220const startHandler = createStartHandler(defaultStreamHandler)
221​
222export default createServerEntry({
223 async fetch(request, opts) {
224 try {
225 return await startHandler(request, opts)
226 } catch (error) {
227 console.error(error)
228 return new Response('Internal Server Error', { status: 500 })
229 }
230 },
231})
232```
233​
234`createServerEntry` returns custom responses as-is, whether they come from a catch or a successful callback. Such responses do not automatically inherit helper state. Likewise, helper writes after `await handler.fetch(...)` are not automatically applied to its returned response; modify that response directly or put the helper writes in Start middleware. Call `handleStartError` in a catch when the error response should inherit helper state.
235​
236## Request context
237​
238When your server needs to pass additional, typed data into request handlers (for example, authenticated user info, a database connection, or per-request flags), register a request context type via TypeScript module augmentation. Pass the runtime values through the `context` property of the second argument to `handler.fetch`. Type registration does not create these values. The context is available throughout the server-side middleware chain β€” including global middleware, request/function middleware, server routes, server functions, and the router itself.
239​
240To add types for your request context, augment the `Register` interface from `@tanstack/react-router` with a `server.requestContext` property. The runtime `context` you pass to `handler.fetch` will then match that type. Example:
241​
242```tsx
243import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
244​
245type MyRequestContext = {
246 hello: string
247 foo: number
249​
250declare module '@tanstack/react-router' {
251 interface Register {
252 server: {
253 requestContext: MyRequestContext
254 }
255 }
257​
258export default createServerEntry({
259 fetch(request, opts) {
260 return handler.fetch(request, {
261 ...opts,
262 context: { hello: 'world', foo: 123 },
263 })
264 },
265})
266```
267​
268## Server Configuration
269​
270The server entry point is where you can configure server-specific behavior:
271​
272- Request/response middleware
273- Custom error handling
274- Authentication logic
275- Database connections
276- Logging and monitoring
277​
278This flexibility allows you to customize how your TanStack Start application handles server-side rendering while maintaining the framework's conventions.
279​
280## Cloudflare Workers
281​
282When deploying to Cloudflare Workers, you can extend `server.ts` to handle additional Workers features like queues, scheduled events, and Durable Objects. For a comprehensive guide, see the [Cloudflare Workers documentation for TanStack Start](https://developers.cloudflare.com/workers/framework-guides/web-apps/tanstack-start/#custom-entrypoints).