Open History to see the last commit
1---
2title: Keep Keys on the Server
3id: server-keys
4order: 10
5description: "Save each user's provider keys on your server with a CredentialStore, and read them in your chat route with storedProviderKeys."
6keywords:
7 - tanstack ai
8 - byok
9 - api key
10 - CredentialStore
11 - storedProviderKeys
12 - encryption
13---
14
15A key in the browser is gone when the user opens your app on a new device. A background job has no browser to send it. For these cases, save the key on your server, one key for each user and provider.
16
17Do these four steps:
18
191. Make a credential store.
202. Add a route that saves the key.
213. Send the key from your form.
224. Read the key in the chat route.
23
24## 1. Make a credential store
25
26Start with the memory store:
27
28```typescript
29import { memoryCredentialStore } from "@tanstack/ai/byok/server";
30
31export const credentials = memoryCredentialStore();
32```
33
34The memory store loses the keys when the process stops. For production, [write a store](#write-a-store-for-production) for your database or your secrets manager.
35
36## 2. Add a route that saves the key
37
38Get the user from your auth, not from the request body:
39
40```typescript
41import { credentials } from "./credentials";
42import { getUser } from "./auth";
43
44export async function POST(request: Request) {
45 const user = await getUser(request);
46 if (!user) return new Response("Unauthorized", { status: 401 });
47
48 const body: unknown = await request.json();
49 if (
50 typeof body !== "object" ||
51 body === null ||
52 !("key" in body) ||
53 typeof body.key !== "string"
54 ) {
55 return new Response("Send { key }", { status: 400 });
56 }
57
58 await credentials.set({
59 scope: { userId: user.id },
60 id: "openai",
61 credential: { type: "api_key", value: body.key },
62 });
63 return new Response(null, { status: 204 });
64}
65```
66
67## 3. Send the key from your form
68
69```tsx
70import { useState } from "react";
71
72export function ServerKeyForm() {
73 const [value, setValue] = useState("");
74
75 return (
76 <form
77 onSubmit={(event) => {
78 event.preventDefault();
79 void fetch("/api/keys", {
80 method: "POST",
81 headers: { "content-type": "application/json" },
82 body: JSON.stringify({ key: value.trim() }),
83 }).then(() => setValue(""));
84 }}
85 >
86 <input
87 type="password"
88 autoComplete="off"
89 value={value}
90 onChange={(event) => setValue(event.target.value)}
91 />
92 <button type="submit">Save</button>
93 </form>
94 );
95}
96```
97
98## 4. Read the key in the chat route
99
100`storedProviderKeys` reads the key that the user saved:
101
102```typescript
103import {
104 chat,
105 chatParamsFromRequest,
106 keyedAdapter,
107 toServerSentEventsResponse,
108} from "@tanstack/ai";
109import { byokMissing, storedProviderKeys } from "@tanstack/ai/byok/server";
110import { createOpenaiChat } from "@tanstack/ai-openai";
111import { openaiByok } from "@tanstack/ai-openai/byok";
112import { credentials } from "./credentials";
113import { getUser } from "./auth";
114
115const gpt = keyedAdapter(openaiByok, (key) =>
116 createOpenaiChat("gpt-6.1-sol", key),
117);
118
119export async function POST(request: Request) {
120 const user = await getUser(request);
121 if (!user) return new Response("Unauthorized", { status: 401 });
122
123 const keys = storedProviderKeys(credentials, { userId: user.id });
124 const apiKey = await keys.get(openaiByok);
125 if (!apiKey) return byokMissing(openaiByok);
126
127 const params = await chatParamsFromRequest(request);
128 const stream = chat({
129 adapter: gpt.create(apiKey),
130 messages: params.messages,
131 threadId: params.threadId,
132 runId: params.runId,
133 });
134 return toServerSentEventsResponse(stream);
135}
136```
137
138How `storedProviderKeys` finds a key:
139
140- It reads the `api_key` credential that the user saved under the provider id.
141- If you add `tenantId` to the scope, a user with no key gets the key of the tenant. A tenant key is saved with `tenantId` and no `userId`.
142- If there is no saved key, it reads the env var of the provider, here `OPENAI_API_KEY`.
143- To give the same keys to your [agents](./byok#keys-inside-agents), pass `keys.get` to `subagents.keys`.
144
145Your users now save a key once, and every device and job uses it.
146
147## Write a store for production
148
149A `CredentialStore` has four methods, and two optional ones for [compare-and-set](#add-compare-and-set). You decide where the secrets live:
150
151- A `credentials` table in the database that you already use, next to your chat tables.
152- A secrets manager, for example AWS Secrets Manager or Vault.
153
154```ts
155import type { CredentialScope } from "@tanstack/ai/byok";
156
157type Credential =
158 | { type: "api_key"; value: string }
159 | { type: "secret_answer"; value: string; expiresAt: number } // epoch ms
160 | {
161 type: "oauth";
162 accessToken: string;
163 refreshToken?: string;
164 expiresAt?: number; // epoch ms
165 scopes?: Array<string>;
166 client?: {
167 clientId: string;
168 clientSecret?: string;
169 redirectUri?: string;
170 issuer?: string;
171 };
172 };
173
174interface CredentialStore {
175 get(key: { scope: CredentialScope; id: string }): Promise<Credential | null>;
176 set(entry: {
177 scope: CredentialScope;
178 id: string;
179 credential: Credential;
180 }): Promise<void>;
181 delete(key: { scope: CredentialScope; id: string }): Promise<void>;
182 list(
183 scope: CredentialScope,
184 ): Promise<Array<{ id: string; type: Credential["type"]; expiresAt?: number }>>;
185 // Optional: compare-and-set.
186 getVersioned?(key: {
187 scope: CredentialScope;
188 id: string;
189 }): Promise<{ credential: Credential; revision: string } | null>;
190 setIf?(entry: {
191 scope: CredentialScope;
192 id: string;
193 credential: Credential;
194 expectedRevision: string | null;
195 }): Promise<{ ok: true; revision: string } | { ok: false; reason: "conflict" }>;
196}
197```
198
199Type your store with `defineCredentialStore` from `@tanstack/ai/byok`. `CredentialScope` has `tenantId` and `userId`. It can also have a `threadId`, which the store ignores.
200
201Rules for the keys:
202
203- Key each credential by `scope.tenantId`, `scope.userId`, and `id`. Do not use `scope.threadId`.
204- A user credential is not visible at the tenant scope. A tenant credential is not visible at the user scope.
205- A scope with no tenant and no user is one bucket that every caller shares. Get the scope from your server-side auth, never from the request body.
206- `client` is the OAuth client that the tokens belong to. A token refresh needs it.
207- A `secret_answer` row is not a user credential. The harness keeps a secret answer there for a short time. Leave this type out of a list of connected accounts. You can delete a row after its `expiresAt`.
208
209Rules for the secrets (`value`, `accessToken`, `refreshToken`, `client.clientSecret`):
210
211- Encrypt them at rest. Keep the encryption key in a KMS or a server-only env var, not in the same database.
212- `list` returns ids and types only. It never returns a secret, not even masked.
213- `delete` removes the row. Do not keep a soft-deleted copy of the secret.
214- Do not write a secret to a log, an error message, or a trace. To remove known secrets from a text, use `scrubSecrets(text, secrets)` from `@tanstack/ai/byok`.
215
216The [harness](../harness/provider-keys) uses the same store: pass it to `createHarnessHost({ credentials })`.
217
218### Add compare-and-set
219
220Two servers can refresh the same OAuth token at the same time. If the service rotates refresh tokens, the second save then keeps a token that no longer works. Add `getVersioned` and `setIf`, so the second save does not remove the first:
221
222- `getVersioned` returns the credential and its revision, or `null` when the key is absent.
223- `setIf` writes only when the stored revision equals `expectedRevision`. Pass `null` to write only when the key is absent. Success returns `{ ok: true, revision }`. A different revision returns `{ ok: false, reason: "conflict" }` and does not write.
224- Every write gives the key a new revision. A plain `set` does this too. After `delete`, the deleted revision is never used again.
225- Add both methods or neither. `memoryCredentialStore()` has both.
226
227To refresh a token in your own route, read it with `readCredentialEntry`. It finds the credential like `readCredential` (the user first, then the tenant), and also returns the scope where it found it and its `revision`:
228
229```typescript
230import { readCredentialEntry } from "@tanstack/ai/byok/server";
231import type { Credential, CredentialStore } from "@tanstack/ai/byok";
232
233export async function refreshGithub(
234 store: CredentialStore,
235 scope: { tenantId: string; userId: string },
236 refresh: (current: Credential) => Promise<Credential>,
237) {
238 const entry = await readCredentialEntry(store, scope, "github");
239 if (!entry) return null;
240 const next = await refresh(entry.credential);
241 // Save to the scope where the credential was, also when it is the tenant's.
242 const key = { scope: entry.scope, id: "github", credential: next };
243 if (!store.setIf || entry.revision === undefined) {
244 await store.set(key);
245 return next;
246 }
247 const saved = await store.setIf({ ...key, expectedRevision: entry.revision });
248 if (saved.ok) return next;
249 // Another server saved first. Use its token, and do not refresh again.
250 return (await readCredentialEntry(store, scope, "github"))?.credential ?? null;
251}
252```
253
254In a harness, `run.credentials.refresh` does this for you. See [Refresh a token](../harness/auth#refresh-a-token).