Laravel Api Auth with React and Sanctum: All You Need To Know

One of the ways to become a full-stack developer is to adapt Laravel + React pair. And part of that is authentication. In this tutorial, we will explore how to use Laravel, React, and Laravel Sanctum together to build an API authentication, in two ways:

  • In two-in-one Laravel + React SPA
  • Or, as separate React + API projects

Are you ready? Let's dive in!


Project 1. Laravel SPA: Breeze React Example

To have a quick head start, Laravel Breeze starter kit provides a minimal, simple implementation of all Laravel's authentication features. Laravel Breeze also offers React scaffolding via an Inertia frontend implementation.

First, create a new Laravel project and install Laravel Breeze:

composer require laravel/breeze --dev

After that execute breeze:install Artisan command with React stack and all auth scaffolding will be installed, you should also compile your application's frontend assets:

php artisan breeze:install react
php artisan migrate
npm install
npm run dev

Now you have a full working Single Page Application (SPA). Authentication controllers are placed in the app/Http/Controllers/Auth folder. Let's lookup at the app/Http/Controllers/Auth/AuthenticatedSessionController.php file's store method:

public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
 
$request->session()->regenerate();
 
return redirect()->intended(RouteServiceProvider::HOME);
}

This method is called when you log in to your application. As we can see there are no references to tokens. That's right, React and Inertia scaffolding uses the laravel_session cookie for authenticated sessions and is handled automatically, so no additional implementation is needed.

Let's move forward with the current setup and create a "protected" demo component...

The full tutorial [18 mins, 3413 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials