Open History to see the last commit
1import { Link, createFileRoute } from '@tanstack/react-router';
2import { Badge, Box, Button, Callout, Code, Flex, Heading, Text, TextField } from '@radix-ui/themes';
3import { useAccessToken, useAuth } from '@workos/authkit-tanstack-react-start/client';
4import { useState } from 'react';
5β
6export const Route = createFileRoute('/client')({
7 component: RouteComponent,
8});
9β
10function RouteComponent() {
11 const {
12 user,
13 loading,
14 sessionId,
15 organizationId,
16 role,
17 roles,
18 permissions,
19 entitlements,
20 featureFlags,
21 impersonator,
22 signOut,
23 switchToOrganization,
24 } = useAuth();
25 const { accessToken, loading: tokenLoading, error: tokenError, refresh, getAccessToken } = useAccessToken();
26β
27 const handleRefreshToken = async () => {
28 try {
29 await refresh();
30 } catch (err) {
31 console.error('Token refresh failed:', err);
32 }
33 };
34β
35 const handleGetFreshToken = async () => {
36 try {
37 const token = await getAccessToken();
38 console.log('Fresh token:', token);
39 } catch (err) {
40 console.error('Get fresh token failed:', err);
41 }
42 };
43β
44 const handleClientSignOut = async () => {
45 console.log('π§ͺ Testing client-side signOut() from useAuth()...');
46 try {
47 await signOut({ returnTo: '/' });
48 console.log('β
signOut() completed');
49 } catch (err) {
50 console.error('β signOut() failed:', err);
51 }
52 };
53β
54 const [orgIdInput, setOrgIdInput] = useState('');
55 const [switchOrgResult, setSwitchOrgResult] = useState<string | null>(null);
56β
57 const handleSwitchOrg = async () => {
58 if (!orgIdInput.trim()) {
59 setSwitchOrgResult('Please enter an organization ID');
60 return;
61 }
62β
63 console.log(`π Switching to organization: ${orgIdInput}...`);
64 setSwitchOrgResult(null);
65β
66 try {
67 const result = await switchToOrganization(orgIdInput.trim());
68 if (result && 'error' in result) {
69 console.error('β Switch failed:', result.error);
70 setSwitchOrgResult(`Error: ${result.error}`);
71 } else {
72 console.log('β
Successfully switched organizations');
73 setSwitchOrgResult('β
Success! Check updated claims above.');
74 }
75 } catch (err) {
76 const message = err instanceof Error ? err.message : String(err);
77 console.error('β Switch error:', message);
78 setSwitchOrgResult(`Error: ${message}`);
79 }
80 };
81β
82 if (loading) {
83 return (
84 <Flex direction="column" gap="2" align="center">
85 <Heading size="8">Loading...</Heading>
86 </Flex>
87 );
88 }
89β
90 if (!user) {
91 return (
92 <Flex direction="column" gap="4" align="center" maxWidth="600px">
93 <Heading size="8" align="center">
94 Client-Side Hooks Demo
95 </Heading>
96 <Text size="5" align="center" color="gray">
97 This page demonstrates the client-side hooks from <Code>@workos/authkit-tanstack-start/client</Code>
98 </Text>
99 <Callout.Root>
100 <Callout.Text>βΉοΈ Please sign in to see the client-side hooks in action.</Callout.Text>
101 </Callout.Root>
102 </Flex>
103 );
104 }
105β
106 return (
107 <Flex direction="column" gap="5" maxWidth="800px">
108 <Flex direction="column" gap="2" mb="2">
109 <Heading size="8" align="center">
110 Client-Side Hooks Demo
111 </Heading>
112 <Text size="5" align="center" color="gray">
113 Using <Code>useAuth()</Code> and <Code>useAccessToken()</Code>
114 </Text>
115 </Flex>
116β
117 <Callout.Root>
118 <Callout.Text>
119 βΉοΈ This page uses client-side React hooks to access authentication data. Unlike server-side loaders, these
120 hooks work in client components and automatically update when auth state changes.
121 </Callout.Text>
122 </Callout.Root>
123β
124 <Flex direction="column" gap="3">
125 <Heading size="5">useAuth() Hook</Heading>
126 <Flex direction="column" gap="2">
127 <Flex align="center" gap="2">
128 <Text weight="bold" style={{ width: 150 }}>
129 User ID:
130 </Text>
131 <TextField.Root value={user.id} readOnly style={{ flexGrow: 1 }} />
132 </Flex>
133 <Flex align="center" gap="2">
134 <Text weight="bold" style={{ width: 150 }}>
135 Email:
136 </Text>
137 <TextField.Root value={user.email} readOnly style={{ flexGrow: 1 }} />
138 </Flex>
139 <Flex align="center" gap="2">
140 <Text weight="bold" style={{ width: 150 }}>
141 First Name:
142 </Text>
143 <TextField.Root value={user.firstName || ''} readOnly style={{ flexGrow: 1 }} />
144 </Flex>
145 <Flex align="center" gap="2">
146 <Text weight="bold" style={{ width: 150 }}>
147 Last Name:
148 </Text>
149 <TextField.Root value={user.lastName || ''} readOnly style={{ flexGrow: 1 }} />
150 </Flex>
151 <Flex align="center" gap="2">
152 <Text weight="bold" style={{ width: 150 }}>
153 Session ID:
154 </Text>
155 <TextField.Root value={sessionId || ''} readOnly style={{ flexGrow: 1 }} />
156 </Flex>
157 {organizationId && (
158 <Flex align="center" gap="2">
159 <Text weight="bold" style={{ width: 150 }}>
160 Organization ID:
161 </Text>
162 <TextField.Root value={organizationId} readOnly style={{ flexGrow: 1 }} />
163 </Flex>
164 )}
165 {role && (
166 <Flex align="center" gap="2">
167 <Text weight="bold" style={{ width: 150 }}>
168 Role:
169 </Text>
170 <TextField.Root value={role} readOnly style={{ flexGrow: 1 }} />
171 </Flex>
172 )}
173 {roles && roles.length > 0 && (
174 <Flex align="center" gap="2">
175 <Text weight="bold" style={{ width: 150 }}>
176 Roles:
177 </Text>
178 <Flex gap="2" wrap="wrap" style={{ flexGrow: 1 }}>
179 {roles.map((r) => (
180 <Badge key={r}>{r}</Badge>
181 ))}
182 </Flex>
183 </Flex>
184 )}
185 {permissions && permissions.length > 0 && (
186 <Flex align="center" gap="2">
187 <Text weight="bold" style={{ width: 150 }}>
188 Permissions:
189 </Text>
190 <Flex gap="2" wrap="wrap" style={{ flexGrow: 1 }}>
191 {permissions.map((p) => (
192 <Badge key={p} color="blue">
193 {p}
194 </Badge>
195 ))}
196 </Flex>
197 </Flex>
198 )}
199 {entitlements && entitlements.length > 0 && (
200 <Flex align="center" gap="2">
201 <Text weight="bold" style={{ width: 150 }}>
202 Entitlements:
203 </Text>
204 <Flex gap="2" wrap="wrap" style={{ flexGrow: 1 }}>
205 {entitlements.map((e) => (
206 <Badge key={e} color="green">
207 {e}
208 </Badge>
209 ))}
210 </Flex>
211 </Flex>
212 )}
213 {featureFlags && featureFlags.length > 0 && (
214 <Flex align="center" gap="2">
215 <Text weight="bold" style={{ width: 150 }}>
216 Feature Flags:
217 </Text>
218 <Flex gap="2" wrap="wrap" style={{ flexGrow: 1 }}>
219 {featureFlags.map((f) => (
220 <Badge key={f} color="purple">
221 {f}
222 </Badge>
223 ))}
224 </Flex>
225 </Flex>
226 )}
227 {impersonator && (
228 <Flex align="center" gap="2">
229 <Text weight="bold" style={{ width: 150 }}>
230 Impersonator:
231 </Text>
232 <TextField.Root value={impersonator.email} readOnly style={{ flexGrow: 1 }} />
233 </Flex>
234 )}
235 </Flex>
236 </Flex>
237β
238 <Flex direction="column" gap="3">
239 <Heading size="5">useAccessToken() Hook</Heading>
240 <Flex direction="column" gap="2">
241 <Flex align="center" gap="2">
242 <Text weight="bold" style={{ width: 150 }}>
243 Token Status:
244 </Text>
245 <Badge color={tokenLoading ? 'yellow' : accessToken ? 'green' : 'gray'}>
246 {tokenLoading ? 'Loading' : accessToken ? 'Available' : 'None'}
247 </Badge>
248 </Flex>
249 {tokenError && (
250 <Flex align="center" gap="2">
251 <Text weight="bold" style={{ width: 150 }}>
252 Error:
253 </Text>
254 <Badge color="red">{tokenError.message}</Badge>
255 </Flex>
256 )}
257 {accessToken && (
258 <Flex align="center" gap="2">
259 <Text weight="bold" style={{ width: 150 }}>
260 Access Token:
261 </Text>
262 <Box style={{ flexGrow: 1, maxWidth: '100%', overflow: 'hidden' }}>
263 <Code size="2" style={{ wordBreak: 'break-all', display: 'block' }}>
264 ...{accessToken.slice(-20)}
265 </Code>
266 </Box>
267 </Flex>
268 )}
269 <Flex gap="2" mt="2">
270 <Button onClick={handleRefreshToken} disabled={tokenLoading}>
271 Refresh Token
272 </Button>
273 <Button onClick={handleGetFreshToken} disabled={tokenLoading} variant="soft">
274 Get Fresh Token (Console)
275 </Button>
276 </Flex>
277 </Flex>
278 </Flex>
279β
280 <Flex direction="column" gap="3">
281 <Heading size="5">Organization Management</Heading>
282 <Text size="2" color="gray">
283 Switch to a different organization. Requires multi-organization setup in WorkOS.
284 </Text>
285 <Callout.Root>
286 <Callout.Text>
287 <strong>Setup required:</strong> This feature requires your WorkOS user to be a member of multiple
288 organizations. Create organizations in the WorkOS dashboard and add your user to them.
289 </Callout.Text>
290 </Callout.Root>
291 <Flex direction="column" gap="2">
292 <Flex align="center" gap="2">
293 <Text weight="bold" style={{ width: 150 }}>
294 Current Org:
295 </Text>
296 <Badge color={organizationId ? 'green' : 'gray'} size="2">
297 {organizationId || 'None'}
298 </Badge>
299 </Flex>
300 <Flex align="center" gap="2">
301 <Text weight="bold" style={{ width: 150 }}>
302 Switch to Org:
303 </Text>
304 <TextField.Root
305 placeholder="org_..."
306 value={orgIdInput}
307 onChange={(e) => setOrgIdInput(e.target.value)}
308 style={{ flexGrow: 1 }}
309 />
310 <Button onClick={handleSwitchOrg} disabled={!orgIdInput.trim()}>
311 Switch
312 </Button>
313 </Flex>
314 {switchOrgResult && (
315 <Callout.Root color={switchOrgResult.startsWith('β
') ? 'green' : 'red'}>
316 <Callout.Text>{switchOrgResult}</Callout.Text>
317 </Callout.Root>
318 )}
319 </Flex>
320 </Flex>
321β
322 <Flex direction="column" gap="3">
323 <Heading size="5">Sign Out Methods</Heading>
324 <Text size="2" color="gray">
325 Test different sign out approaches. Check the browser console for logs.
326 </Text>
327 <Flex gap="2" wrap="wrap">
328 <Button onClick={handleClientSignOut} color="red">
329 Sign Out (Client-Side useAuth)
330 </Button>
331 <Button asChild color="red" variant="soft">
332 <Link to="/logout" reloadDocument>
333 Sign Out (Route Loader)
334 </Link>
335 </Button>
336 </Flex>
337 <Callout.Root color="blue">
338 <Callout.Text>
339 <strong>Client-Side useAuth:</strong> Calls <Code>signOut()</Code> from the provider context. This tests the
340 redirect handling logic we just fixed.
341 <br />
342 <strong>Route Loader:</strong> Uses the <Code>/logout</Code> route which calls the server function directly
343 in a loader.
344 </Callout.Text>
345 </Callout.Root>
346 </Flex>
347 </Flex>
348 );
349}