Skip to content

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 of useSanctumOptions() but is conveniently accessible within useSanctum().

  • user
    The user 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:

    javascript
    interface User {
      id: number;
      email: string;
      name: string;
    }
    
    const { user } = useSanctum<User>();
  • isLoggedIn
    A boolean property that indicates whether a user is currently authenticated. It returns true if the user is logged in and false 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

    typescript
    async 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:

    typescript
    const { login } = useSanctum();
    
    const userCredentials = {
        email: 'user@mail.com',
        password: '123123',
    };
    
    await login(userCredentials);

    Parameters

    1. 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);
    2. 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 the ofetch 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',
        });
    3. 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
        });

    Functionality

    • Authentication: Upon successful login, the login() function updates the user property with the authenticated user's data and sets the isLoggedIn 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 to false, and ensures the user's session is terminated on the backend.

    Example:

    javascript
    const { 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:

    javascript
    const { refreshUser } = useSanctum();
    
    await refreshUser();