Skip to content

Commit e8052ce

Browse files
docs: server entry point
1 parent 6b9b8f6 commit e8052ce

File tree

1 file changed

+35
-6
lines changed

1 file changed

+35
-6
lines changed

docs/start/framework/react/server-entry-point.md

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export default {
3131
}
3232
```
3333

34-
Whether we are statically generating our app or serving it dynamically, the `server.ts` file is the entry point for doing all SSR-related work.
34+
Whether 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.
3535

3636
## Custom Server Handlers
3737

@@ -42,13 +42,13 @@ You can create custom server handlers to modify how your application is rendered
4242
import {
4343
createStartHandler,
4444
defaultStreamHandler,
45+
defineHandlerCallback,
4546
} from '@tanstack/react-start/server'
4647

47-
// Custom handler example
48-
const customHandler = (request, response) => {
49-
// Add custom logic here
50-
return defaultStreamHandler(request, response)
51-
}
48+
const customHandler = defineHandlerCallback((ctx) => {
49+
// add custom logic here
50+
return defaultStreamHandler(ctx)
51+
})
5252

5353
const fetch = createStartHandler(customHandler)
5454

@@ -57,6 +57,35 @@ export default {
5757
}
5858
```
5959

60+
## Request context
61+
62+
When 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. The registered context is delivered as the second argument to the server `fetch` handler and is available throughout the server-side middleware chain — including global middleware, request/function middleware, server routes, server functions, and the router itself.
63+
64+
To add types for your request context, augment the `Register` interface from `@tanstack/react-start` with a `server.requestContext` property. The runtime `context` you pass to `handler.fetch` will then match that type. Example:
65+
66+
```tsx
67+
import handler from '@tanstack/react-start/server-entry'
68+
69+
type MyRequestContext = {
70+
hello: string
71+
foo: number
72+
}
73+
74+
declare module '@tanstack/react-start' {
75+
interface Register {
76+
server: {
77+
requestContext: MyRequestContext
78+
}
79+
}
80+
}
81+
82+
export default {
83+
async fetch(request: Request): Promise<Response> {
84+
return handler.fetch(request, { context: { hello: 'world', foo: 123 } })
85+
},
86+
}
87+
```
88+
6089
## Server Configuration
6190

6291
The server entry point is where you can configure server-specific behavior:

0 commit comments

Comments
 (0)