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

request-context.md

119 lines3.4 KB

1---
2title: Send the current user to the server
3id: ui-recipe-request-context
4order: 5
5description: "Pass a user id or tenant from the chat screen to your route with forwardedProps, without putting it in the prompt."
6keywords:
7 - tanstack ai
8 - forwardedProps
9 - useAppChat
10 - runtime context
11 - example
12---
13​
14Pass `forwardedProps` to `useAppChat()`. Every request from that chat carries the value, and the model does not see it.
15​
16## Client
17​
18Put `forwardedProps` on the screen, not on `chatOptions`, because the value changes for each user:
19​
20```tsx group=request-context
21import { fetchServerSentEvents } from '@tanstack/ai-react'
22import { createChatHook } from '@tanstack/ai-react/ui'
23​
24const chatOptions = {
25 connection: fetchServerSentEvents('/api/chat'),
27​
28const { useAppChat, useChatContext } = createChatHook({
29 options: chatOptions,
30 components: {
31 input: () => {
32 const chat = useChatContext()
33 return (
34 <button onClick={() => void chat.sendMessage('What are my invoices?')}>
35 Ask
36 </button>
37 )
38 },
39 layout: ({ Messages, Input }) => (
40 <main>
41 <Messages />
42 <Input />
43 </main>
44 ),
45 message: ({ Parts }) => <article><Parts /></article>,
46 },
47 partsComponents: {
48 text: ({ part }) => <p>{part.content}</p>,
49 fallback: () => null,
50 },
51})
52​
53export function TenantChat({ tenantId }: { tenantId: string }) {
54 const chat = useAppChat({
55 threadId: `tenant-${tenantId}`,
56 forwardedProps: { tenantId },
57 })
58 return <chat.AppChat />
60```
61​
62## Server
63​
64Read the value with `chatParamsFromRequest`. Then put it in `context`, where tools and middleware read it:
65​
66```tsx
67import {
68 chat,
69 chatParamsFromRequest,
70 toServerSentEventsResponse,
71} from '@tanstack/ai'
72import { openaiText } from '@tanstack/ai-openai'
73​
74export async function POST(request: Request) {
75 const params = await chatParamsFromRequest(request)
76​
77 const tenantId =
78 typeof params.forwardedProps.tenantId === 'string'
79 ? params.forwardedProps.tenantId
80 : undefined
81 if (!tenantId) return new Response('Missing tenant', { status: 400 })
82​
83 const stream = chat({
84 adapter: openaiText('gpt-6.1-sol'),
85 messages: params.messages,
86 threadId: params.threadId,
87 context: { tenantId },
88 })
89​
90 return toServerSentEventsResponse(stream)
92```
93​
94Click **Ask**. The route gets `tenantId` from the request, and the model never sees it.
95​
96## How it works
97​
98- `useAppChat()` sends `forwardedProps` with every request from that instance.
99- `chatParamsFromRequest` returns it as `params.forwardedProps`.
100- `context` passes it to your tools and middleware.
101​
102## Validate it on the server
103​
104`forwardedProps` comes from the browser, so a user can change it. Do not trust it for identity or authorization:
105​
1061. Get the user id from the auth of the request (your session or token), not from the client.
1072. Check each forwarded field against a type or a schema.
1083. If a required field is missing, reject the request.
109​
110The example above makes sure that `tenantId` is a string, and rejects the request without it. A real app also makes sure that the signed-in user can use that tenant.
111​
112## One chat for each user
113​
114If a screen can show more than one chat, give each instance its own `threadId`. Two instances with different thread ids keep separate histories.
115​
116## Next
117​
118- Typed server values for tools and middleware: [Runtime context](../../advanced/runtime-context).
119- Browser values that stay on the client: [Client tools](../../tools/client-tools).