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(credentials)
    This method is used to authenticate a user with the given credentials. The credentials argument should be an object containing the necessary fields, such as email and password, as required by your Laravel backend.

    Upon successful login, the user property is updated with the authenticated user's data, and the isLoggedIn flag is set to true.

    Example:

    javascript
    const { login } = useSanctum();
    
    const userCredentials = {
        email: 'user@mail.com',
        password: '123123',
    };
    
    await login(userCredentials);
  • 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();