npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-laravel-sanctum

v1.0.3

Published

Easily integrate Laravel Sanctum and Breeze authentication into your React app.

Readme

Introduction

A simple and flexible React package for authenticating your React application using Laravel Sanctum.

  • Effortless integration of Laravel Sanctum authentication in your React app
  • Built-in support for email verification with Laravel Breeze
  • Minimal dependencies — only requires axios
  • Simplifies the creation of protected routes

Installation

Install from NPM

npm i react-laravel-sanctum

Usage

Wrap your react application in a <AuthProvider> component

import React from "react";
import { AuthProvider } from "react-laravel-sanctum";
import { axios } from "axios";
const authConfig = {
  axiosInstance: axios,
  signInRoute: "/login",
  authenticationCheckRoute: "/auth-check",
  signOutRoute: "/logout",
};

const App = () => (
  <AuthProvider config={authConfig}>/* Your application code */</AuthProvider>
);

You can then use the useAuth() hook to access authentication and verification status, user data, and other related methods in any component wrapped by the <AuthProvider> component.

import { useAuth } from "react-laravel-sanctum";

const LoginForm = () => {
  const { signIn } = useAuth();

  const handleLogin = () => {
    const credentials = {
      email: "[email protected]",
      password: "example",
    };

    signIn(credentials)
      .then(({ mustVerifyEmail }) => {
        if (mustVerifyEmail) {
          console.log("Must Verify Email Message");
        }
      })
      .catch((error) => {
        console.log("Error Message");
      });
  };

  return <button onClick={() => handleLogin()}>Login</button>;
};
import { useAuth } from "react-laravel-sanctum";

const UserComponent = () => {
  const { user } = useAuth();

  return <div>Hello {user?.first_name}</div>;
};

Methods & Properties Available with useAuth()

The useAuth hook gives you access to the AuthContext.

| | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | user | The authenticated user object returned from your API. null if not authenticated. | | authenticated | Boolean if has authentication has been checked, or null if authentication has not yet been checked. | | verified | Boolean if has verification has been checked, or null if verification has not yet been checked. | | loading | true while checking user authentication, false when the check is complete. | | signIn() | Accepts ({}: Credentials), returns a promise, resolves with {mustVerifyEmail: boolean, signedIn: boolean, user: {}}. | | signUp() | Accepts ({}: Credentials), resolves with {mustVerifyEmail: boolean, signedIn: boolean, user: {}}. | | signOut() | Returns a promise, resolves with no values. | | setUser() | Accepts (user, authenticated, verified), allows you to manually set the user by providing the user object, authentication and verfication status (boolean). | | sendEmailVerification() | Return a promise, resolves with no values. | | verifyEmail() | Accepts (id: string, hash: string, expires: string, signature: string), returns a promise, resolves with {user: {}}. | | handleSessionTimeout() | Accepts (error: AxiosError), returns nothing. |

Config Setup

Not all URLS in the config are required. These need to be defined in your Laravel application.

const authConfig = {
  // An axiosInstance is required to be used by react-laravel-sanctum.
  axiosInstance: AxiosInstance;
  /*
  * Required
  * Sends a POST request to this endpoint to log in the user.
  */
  signInRoute: "/login";
  /*
  * Optional (unless signUp() will be used)
  * Sends a POST request to this endpoint to register the user.
  */
  signUpRoute: "/register";
  /*
  * Required
  * Sends a GET request to this endpoint to this endpoint to check the user authentication status.
  * Returns a user object that is represented as `user` in the React application.
  */
  authenticationCheckRoute: "/auth-check";
  /*
  * Optional (unless sendEmailVerification() will be used)
  * Sends a POST request to this endpoint to send an email verification notification.
  */
  sendEmailVerificationRoute: "/verification-notification";
  /*
  * Optional (unless verifyEmail() will be used)
  * Sends a GET request to this endpoint to verify the user.
  */
  verifyEmailRoute: (id: string, hash: string, expires: string, signature: string) => `/verify-email/${id}/${hash}?expires=${expires}&signature=${signature}`;
  /*
  * Required
  * Sends a POST request to this endpoint to logout the user.
  */
  signOutRoute: '/logout';
};

react-laravel-sanctum automatically checks if the user is signed in when the <AuthProvider> component is mounted. By default, it also assumes emailVerification is set to true and will check if the user’s email is verified. If you’d like to disable this behavior, simply set emailVerification to false like this:

<AuthProvider config={authConfig} emailVerification={false}>

Similarly, onInitCheck is set to false by default. When set to true, it checks if the user is authenticated when <AuthProvider> mounts. If you would like to enable this behavior, set onInitCheck to true like this:

<AuthProvider config={authConfig} onInitCheck={true}>

Handling Session Timeout

This function updates the authentication state in the event that the user's session has timed out. It is particularly useful when implementing protected routes, as it ensures that users are redirected or logged out when their session expires.

const { handleSessionTimeout } = useAuth();

axiosInstance
  .get("/protected-resource")
  .then((response) => {
    // handle successful response
  })
  .catch((error) => {
    // handle session timeout error
    handleSessionTimeout(error);
  });

Email Verification

This package supports email verification using Laravel Breeze out of the box.

  1. Install Laravel Breeze as an API using the following instructions https://laravel.com/docs/11.x/starter-kits#laravel-breeze-installation

  2. Ensure the User Model implements MustVerifyEmail interface.

Example for implementation:

This is the <SignUpForm> Component:

import { useAuth } from "react-laravel-sanctum";
import { useNavigate } from "react-router-dom";

const SignUpForm = () => {
  const { signUp } = useAuth();
  const navigate = useNavigate();

  const handleRegistration = () => {
    const credentials = {
      name: "user",
      email: "[email protected]",
      password: "example",
    };

    signUp(credentials)
      .then(({ mustVerifyEmail }) => {
        if (mustVerifyEmail) {
          navigate("Email verification notification component"); // to allow users to resend the email verification notification
        }
      })
      .catch((error) => {
        console.log("Error Message");
      });
  };

  return <button onClick={() => handleRegistration()}>SignUp</button>;
};

This is the <EmailVerificationProcessing> Component, The URL is obtained from the verification email sent to the user:

import { useEffect } from "react";
import { useAuth } from "react-laravel-sanctum";
import { useLocation, useParams } from "react-router-dom";

const EmailVerificationProcessing = () => {
  const { verifyEmail } = useAuth();

  useEffect(() => {
    const id = "example";
    const hash = "example";
    const expires = "example";
    const signature = "example";

    verifyEmail(id, hash, expires, signature).catch((error) => {
      console.log(error);
    });
  }, []);

  return <div>Verifying....</div>;
};

Axios

react-laravel-sanctum assumes that setting the CSRF token is handled within the provided Axios instance. This is done through request interceptors, allowing users to fully control their own interceptor implementations and customize their Axios instance configuration.