useSanctum()
useSanctum()
is the primary composable for managing authentication within your application. It consolidates various authentication-related functionalities, including logging in, logging out, and accessing the current authenticated user.
Properties
options
This computed property gives you access to the module's configuration options, such as API endpoints and other settings. It mirrors the output ofuseSanctumOptions()
but is conveniently accessible withinuseSanctum()
.user
Theuser
property holds the data of the currently authenticated user. This property is reactive, meaning any changes to the user's state (e.g., login or logout) are automatically reflected in your application. It also supports typed user.Example:
javascriptinterface User { id: number; email: string; name: string; } const { user } = useSanctum<User>();
isLoggedIn
A boolean property that indicates whether a user is currently authenticated. It returnstrue
if the user is logged in andfalse
otherwise.
Methods
login()
The login() function is a key method within the useSanctum() composable, responsible for authenticating users by sending their credentials to the Laravel backend. This method facilitates secure login processes, and provides options for custom handling of the authentication flow.
Function Signature
typescriptasync function login<LoginApiResponse>( credentials: Record<string, any>, clientOptions?: FetchOptions, callback?: (responseData: LoginApiResponse, user: T | null) => any ): Promise<void>;
Example Usage
Here's how you can use the
login()
function in your component:typescriptconst { login } = useSanctum(); const userCredentials = { email: 'user@mail.com', password: '123123', }; await login(userCredentials);
Parameters
credentials: Record<string, any>
An object containing the necessary fields for authentication. This typically includes the user's email and password as required by your Laravel backend.- Example:typescript
const userCredentials = { email: 'user@mail.com', password: '123123', }; await login(userCredentials);
- Example:
clientOptions?: FetchOptions
(optional)
This optional parameter allows you to customize the fetch request sent to the backend. It behaves similarly to the options available in theofetch
client, enabling you to set additional properties such as HTTP headers, request method, and more.- Example:javascript
await login(userCredentials, { headers: { 'custom-header': 'value' }, method: 'POST', });
- Example:
callback?: (responseData: LoginApiResponse, user: T | null) => any
(optional):
This optional callback function is executed after a successful login. It allows you to implement custom logic based on the API response. This is particularly useful for handling scenarios such as two-factor authentication (2FA) or custom redirection.- Example:javascript
await login(userCredentials, {}, async (response) => { if (response.two_factor) { return await navigateTo('/2fa'); // Redirect to 2FA page } return await navigateTo('/dashboard'); // Redirect to dashboard });
- Example:
Functionality
- Authentication: Upon successful login, the
login()
function updates the user property with the authenticated user's data and sets theisLoggedIn
flag to true. - Redirection: If configured, the function automatically redirects the application to the path specified in the module configuration (
laravelSanctum.redirect.redirectToAfterLogin
). This can be overridden using the callback function. - Token Handling: If token-based authentication is used, the function extracts and stores the authentication token for subsequent requests.
- Intended Redirects: The function also supports intended redirects, allowing users to return to the page they were trying to access before logging in.
logout()
:
This method logs out the authenticated user. It clears the user data, sets the
isLoggedIn
flag tofalse
, and ensures the user's session is terminated on the backend.Example:
javascriptconst { logout } = useSanctum(); await logout();
refreshUser()
:
This method lets you manually refresh the current user's data by re-fetching it from the backend. It is handy in scenarios where the user's information might have changed without a full reload of the application.
Example:
javascriptconst { refreshUser } = useSanctum(); await refreshUser();