How to integrate Laravel Sanctum for SPA authentication with ReactJS



Image not found!!

Integrating Laravel Sanctum with a ReactJS Single Page Application (SPA) involves setting up the Laravel backend to handle authentication using Sanctum and configuring your ReactJS application to communicate with the backend for authentication. Below are the general steps to achieve this integration:

Backend (Laravel Sanctum):

  1. Install Laravel Sanctum: Ensure that you have a Laravel project set up. Install Sanctum using Composer:

    bash
    composer require laravel/sanctum
  2. Publish Configuration: Publish the Sanctum configuration file:

    bash
    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  3. Run Migrations: Run the migrations to create the necessary database tables for Sanctum:

    bash
    php artisan migrate
  4. Configure CORS: Update your config/cors.php file to allow requests from your ReactJS application:

    php
    'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['http://your-react-app-url'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true,
  5. Update Middleware: Add the \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class middleware to your api middleware group in app/Http/Kernel.php:

    php
    'api' => [ // ... \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, ],
  6. Enable Sanctum in routes/api.php: Update your routes/api.php file to enable Sanctum:

    php
    use Laravel\Sanctum\Http\Controllers\CsrfCookieController; use Laravel\Sanctum\Http\Controllers\LoginController; use Laravel\Sanctum\Http\Controllers\LogoutController; use Laravel\Sanctum\Http\Controllers\RegisteredUserController; // ... Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); Route::post('/register', [RegisteredUserController::class, 'store']); Route::post('/login', [LoginController::class, 'login']); Route::middleware('auth:sanctum')->post('/logout', [LogoutController::class, 'logout']); Route::post('/sanctum/csrf-cookie', [CsrfCookieController::class, 'show']);
  7. Configure Session Driver: Ensure that your session driver is set to use cookie in config/session.php:

    php
    'driver' => env('SESSION_DRIVER', 'cookie'),
  8. Generate API Tokens (optional): If you want to use API tokens, make sure your User model uses the HasApiTokens trait:

    php
    use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // ... }

Frontend (ReactJS):

  1. Install Axios: Install Axios for making HTTP requests:

    bash
    npm install axios
  2. Configure Axios: Set up Axios to include credentials and the CSRF token for Sanctum:

    jsx
    // src/axios.js import axios from 'axios'; const apiClient = axios.create({ baseURL: 'http://your-laravel-app-url/api', withCredentials: true, }); export default apiClient;
  3. Perform Authentication in React Components: Use Axios to make requests for user registration, login, and logout:

    jsx
    // Example registration component import React, { useState } from 'react'; import apiClient from '../axios'; const Registration = () => { const [formData, setFormData] = useState({ name: '', email: '', password: '', password_confirmation: '', }); const handleRegister = async () => { try { const response = await apiClient.post('/register', formData); console.log(response.data); } catch (error) { console.error(error.response.data); } }; return ( <div> {/* Form fields and submit button */} <button onClick={handleRegister}>Register</button> </div> ); }; export default Registration;
  4. Use Protected Routes: For components that require authentication, check if the user is authenticated before rendering the component. Redirect to the login page if not authenticated.

    jsx
    // Example protected component import React, { useEffect, useState } from 'react'; import apiClient from '../axios'; const ProtectedComponent = () => { const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { try { const response = await apiClient.get('/user'); setUser(response.data); } catch (error) { console.error('User not authenticated'); // Redirect to login or handle authentication failure } }; fetchUser(); }, []); return ( <div> {user && <p>Welcome, {user.name}!</p>} {/* Component content */} </div> ); }; export default ProtectedComponent;

These steps should help you integrate Laravel Sanctum with a ReactJS SPA for authentication. Adjust the code based on your specific requirements and project structure. Additionally, ensure that your Laravel and ReactJS applications are running on the correct URLs and ports.