getUser
Reads the signed-in user outside a React component, for example in a helper function or at startup.
Usage
app/components/audit.ts
import { getUser } from "app/hooks";
export function stampNote(text: string) {
const user = getUser();
return user ? `${text} (${user.name})` : text;
}Signature
app/hooks.ts
type SessionUser = { id: number; name: string; email: string; role: string; avatarUrl?: string | null };
function getUser(): SessionUser | null;Parameters
None.
Returns
The user stored by the latest signIn, or null when there is no token.
getUser reads once. Its result doesn’t follow later sign-ins or sign-outs, so inside a component use useSession.
Examples
Send signed-out visitors to the sign-in page from a layout:
app/(staff)/layout.tsx
import { Navigate, Outlet } from "react-router-dom";
import { getUser } from "app/hooks";
export default function StaffLayout() {
return getUser() ? <Outlet /> : <Navigate to="/login" replace />;
}The user stored in the browser is only for drawing the UI. The server doesn’t trust it: permissions are checked with the token on every request.
Next steps
- useSession: the user inside a component, re-rendered on sign-in and sign-out.
- Sign-in and permissions: roles in
app/auth.tsand a handler’saccess.
Last updated