A comprehensive authentication hook that provides user authentication state and methods for login, registration, password management, and logout.
Import
import useAuth from "@/hooks/useAuth" ;
Type Definitions
export interface RegisterErrors {
name ?: Array < string >;
email ?: Array < string >;
password ?: Array < string >;
}
export interface LoginErrors {
email ?: Array < string >;
}
interface RegisterProps {
setErrors : ( errors : RegisterErrors ) => void ;
name : string ;
email : string ;
password : string ;
password_confirmation : string ;
terms : boolean ;
}
interface LoginProps {
setErrors : ( errors : LoginErrors ) => void ;
email : string ;
password : string ;
remember : boolean ;
}
interface ForgotPasswordProps {
email : string ;
}
interface ResetPasswordProps {
email : string ;
password : string ;
password_confirmation : string ;
token : string ;
}
Usage
const {
me ,
register ,
login ,
forgotPassword ,
resetPassword ,
resendEmailVerification ,
logout ,
} = useAuth ();
Return Value
The current authenticated user object fetched from the API. Contains user details, permissions, and roles. Returns { user: null } when not authenticated. User’s direct permissions
User’s roles with associated permissions
register
(props: RegisterProps) => Promise<void>
Registers a new user account. Handles CSRF protection and validation errors.
login
(props: LoginProps) => Promise<void>
Authenticates a user with email and password. Supports remember me functionality.
forgotPassword
(props: ForgotPasswordProps) => Promise<AxiosResponse>
Initiates the forgot password flow by sending a password reset email.
resetPassword
(props: ResetPasswordProps) => Promise<void>
Resets the user’s password using a reset token.
Resends the email verification notification.
Logs out the current user and invalidates the session.
Examples
Checking Authentication Status
import useAuth from "@/hooks/useAuth" ;
function Navigation () {
const { me } = useAuth ();
return (
< nav >
{ me ?. user ? (
< span > Welcome , { me . user . name }!</ span >
) : (
< button > Login </ button >
)}
</ nav >
);
}
import { useState , type SyntheticEvent } from "react" ;
import useAuth , { type LoginErrors } from "@/hooks/useAuth" ;
function LoginForm () {
const { login } = useAuth ();
const [ email , setEmail ] = useState ( "" );
const [ password , setPassword ] = useState ( "" );
const [ isRemember , setRemember ] = useState ( false );
const [ isBusy , setBusy ] = useState ( false );
const [ errors , setErrors ] = useState < LoginErrors >({});
function performLogin ( event : SyntheticEvent ) {
event . preventDefault ();
setBusy ( true );
login ({
setErrors ,
email ,
password ,
remember: isRemember ,
}). finally (() => setBusy ( false ));
}
return (
< form onSubmit = { performLogin } >
< input
type = "email"
value = { email }
onChange = {(e) => setEmail (e.target.value)}
/>
{ errors . email && < span >{ errors . email [0]}</ span >}
< input
type = "password"
value = { password }
onChange = {(e) => setPassword (e.target.value)}
/>
< label >
< input
type = "checkbox"
checked = { isRemember }
onChange = {(e) => setRemember (e.target.checked)}
/>
Remember me
</ label >
< button type = "submit" disabled = { isBusy } >
Login
</ button >
</ form >
);
}
User Registration
import { useState } from "react" ;
import useAuth , { type RegisterErrors } from "@/hooks/useAuth" ;
function RegisterForm () {
const { register } = useAuth ();
const [ name , setName ] = useState ( "" );
const [ email , setEmail ] = useState ( "" );
const [ password , setPassword ] = useState ( "" );
const [ passwordConfirmation , setPasswordConfirmation ] = useState ( "" );
const [ termsAccepted , setTermsAccepted ] = useState ( false );
const [ errors , setErrors ] = useState < RegisterErrors >({});
async function handleRegister () {
await register ({
setErrors ,
name ,
email ,
password ,
password_confirmation: passwordConfirmation ,
terms: termsAccepted ,
});
}
return (
< form onSubmit = {(e) => { e . preventDefault (); handleRegister (); }} >
< input
value = { name }
onChange = {(e) => setName (e.target.value)}
placeholder = "Name"
/>
{ errors . name && < span >{ errors . name [0]}</ span >}
< input
type = "email"
value = { email }
onChange = {(e) => setEmail (e.target.value)}
placeholder = "Email"
/>
{ errors . email && < span >{ errors . email [0]}</ span >}
< input
type = "password"
value = { password }
onChange = {(e) => setPassword (e.target.value)}
placeholder = "Password"
/>
{ errors . password && < span >{ errors . password [0]}</ span >}
< input
type = "password"
value = { passwordConfirmation }
onChange = {(e) => setPasswordConfirmation (e.target.value)}
placeholder = "Confirm Password"
/>
< label >
< input
type = "checkbox"
checked = { termsAccepted }
onChange = {(e) => setTermsAccepted (e.target.checked)}
/>
I accept the terms and conditions
</ label >
< button type = "submit" > Register </ button >
</ form >
);
}
Logout
import useAuth from "@/hooks/useAuth" ;
function LogoutButton () {
const { logout } = useAuth ();
return (
< button onClick = {() => logout ()} >
Logout
</ button >
);
}
Implementation Details
Uses SWR for data fetching and caching with a 2-second deduping interval
Automatically handles CSRF token management for Laravel Sanctum
Revalidates authentication state globally after login/logout operations
Provides fallback data for server-side rendering
Uses GraphQL for fetching user data
Source: /home/daytona/workspace/source/src/hooks/useAuth.ts:46