useUser

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.

If you want to learn more about the User object, check out the User documentation.

Default Usage

Check if the user is authenticated and display the user’s name.

1import { useUser } from "@stackframe/stack";
2
3function MyComponent() {
4 const user = useUser(); // user can be null
5 if (!user) {
6 return <div>Not authenticated</div>;
7 }
8 return <div>Hello, {user.name}</div>;
9}

Redirect when not authenticated

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.

1import { useUser } from "@stackframe/stack";
2
3function MyComponent() {
4 const user = useUser({ or: "redirect" }); // user is garanteed to be non-null
5 return <div>Hello, {user.name}</div>;
6}

The same hook can also be used to protect a page. (You might also want to check out the server-side version here)

1import { useUser } from "@stackframe/stack";
2
3function MyProtectedPage() {
4 useUser({ or: "redirect" });
5 return <div>You can only see this if you are authenticated</div>;
6}

Throw an error when not authenticated

By passing { or: "throw" } into the hook, it will throw an error if the user is not authenticated. This can be used for places where the user should never be unauthenticated if the app is working correctly.

1import { useUser } from "@stackframe/stack";
2
3function MyComponent() {
4 // user is garanteed to be non-null, but an error will be thrown if the user is not authenticated
5 const user = useUser({ or: "throw" });
6
7 return <div>Hello, {user.name}</div>;
8}