|
1 | 1 | --- |
2 | | -slug: sdk/use-user |
| 2 | +title: useUser |
3 | 3 | --- |
4 | 4 |
|
5 | | -`useUser` is a hook that returns the user object if the user is authenticated; otherwise, it returns `null` by default. However, if you pass in `{ or: "redirect" }` or `{ or: "throw" }` as an option, it will redirect to the login page or throw an error respectively when the user is not authenticated. |
| 5 | +# useUser |
6 | 6 |
|
7 | | -If you want to learn more about the `User` object, check out the [User](./current-user.mdx) documentation. |
| 7 | +A hook to retrieve the current user information with various options for handling authentication and project matching. |
8 | 8 |
|
9 | | -## Default Usage |
| 9 | +## Parameters |
10 | 10 |
|
11 | | -Check if the user is authenticated and display the user's name. |
12 | | -```jsx |
13 | | -import { useUser } from "@stackframe/stack"; |
| 11 | +- `options` (optional): `GetUserOptions` - Options for retrieving user information. |
| 12 | + - `or` (optional): `'redirect' | 'throw'` - Specifies behavior if user is not authenticated. |
| 13 | + - `projectIdMustMatch` (optional): `'internal'` - Ensures the user belongs to an internal project. |
14 | 14 |
|
15 | | -function MyComponent() { |
16 | | - const user = useUser(); // user can be null |
17 | | - if (!user) { |
18 | | - return <div>Not authenticated</div>; |
19 | | - } |
20 | | - return <div>Hello, {user.name}</div>; |
21 | | -} |
22 | | -``` |
| 15 | +## Example |
23 | 16 |
|
24 | | -## Redirect when not authenticated |
25 | | -By passing `{ or: "redirect" }` to the hook, it will redirect to the login page if the user is not authenticated. You can configure the login page in the StackApp component. |
26 | | -```jsx |
27 | | -import { useUser } from "@stackframe/stack"; |
| 17 | +```tsx |
| 18 | +import { useUser } from '@stackframe/stack'; |
28 | 19 |
|
29 | | -function MyComponent() { |
30 | | - const user = useUser({ or: "redirect" }); // user is garanteed to be non-null |
31 | | - return <div>Hello, {user.name}</div>; |
| 20 | +// Basic usage |
| 21 | +const user = useUser(); |
| 22 | + |
| 23 | +// With options |
| 24 | +const internalUser = useUser({ projectIdMustMatch: 'internal' }); |
| 25 | + |
| 26 | +// With authentication handling |
| 27 | +const authenticatedUser = useUser({ or: 'redirect' }); |
| 28 | + |
| 29 | +// Combined options |
| 30 | +const authenticatedInternalUser = useUser({ |
| 31 | + or: 'throw', |
| 32 | + projectIdMustMatch: 'internal' |
| 33 | +}); |
| 34 | +``` return <div>Hello, {user.name}</div>; |
32 | 35 | } |
33 | 36 | ``` |
34 | 37 |
|
|
0 commit comments