|
1 | | -// your Stream app information |
| 1 | +// Stream Chat credentials for the tutorial example. |
| 2 | +// |
| 3 | +// The example fetches a fresh JWT from pronto.getstream.io for whichever |
| 4 | +// user_id is active, so the app stays runnable without pasting a token |
| 5 | +// that expires, and you can switch users via URL params at runtime: |
| 6 | +// |
| 7 | +// ?user_id=alice // different user |
| 8 | +// ?user_id=alice&user_name=Alice // + display name override |
| 9 | +// |
| 10 | +// Notes: |
| 11 | +// - apiKey is the one thing you still need to set (via VITE_API_KEY). |
| 12 | +// - The token endpoint and environment default to the values shared with |
| 13 | +// the other example apps in this repo; override with VITE_TOKEN_ENDPOINT |
| 14 | +// and VITE_TOKEN_ENVIRONMENT if you're pointing at a different Stream |
| 15 | +// app. |
| 16 | + |
| 17 | +const searchParams = new URLSearchParams(window.location.search); |
| 18 | + |
2 | 19 | export const apiKey = import.meta.env.VITE_API_KEY; |
3 | | -export const userId = import.meta.env.VITE_USER_ID; |
4 | | -export const userName = import.meta.env.VITE_USER_NAME; |
5 | | -export const userToken = import.meta.env.VITE_USER_TOKEN; |
| 20 | + |
| 21 | +export const userId = |
| 22 | + searchParams.get('user_id') || import.meta.env.VITE_USER_ID || 'react-tutorial'; |
| 23 | + |
| 24 | +export const userName = |
| 25 | + searchParams.get('user_name') || import.meta.env.VITE_USER_NAME || userId; |
| 26 | + |
| 27 | +const tokenEndpoint = |
| 28 | + import.meta.env.VITE_TOKEN_ENDPOINT || |
| 29 | + 'https://pronto.getstream.io/api/auth/create-token'; |
| 30 | +const tokenEnvironment = import.meta.env.VITE_TOKEN_ENVIRONMENT || 'demo'; |
| 31 | + |
| 32 | +// Stream's `useCreateChatClient` accepts either a token string or a provider |
| 33 | +// function. A provider lets the SDK refresh the token on reconnect, which is |
| 34 | +// what we want for a long-running example session. |
| 35 | +export const tokenProvider = async (): Promise<string> => { |
| 36 | + const url = `${tokenEndpoint}?environment=${encodeURIComponent( |
| 37 | + tokenEnvironment, |
| 38 | + )}&user_id=${encodeURIComponent(userId)}`; |
| 39 | + const response = await fetch(url); |
| 40 | + if (!response.ok) { |
| 41 | + throw new Error(`Failed to mint token from ${tokenEndpoint} (${response.status})`); |
| 42 | + } |
| 43 | + const data = (await response.json()) as { token: string }; |
| 44 | + return data.token; |
| 45 | +}; |
0 commit comments