DEV Community

Cover image for Laravel Sanctum Authentication for React App using Breeze
Nilanth
Nilanth

Posted on • Edited on • Originally published at javascript.plainenglish.io

Laravel Sanctum Authentication for React App using Breeze

Steps to integrated Laravel Sanctum authentication with React app using Breeze API scaffolding

Laravel breeze is an Authentication scaffolding for web and APIs. Breeze is powered by Laravel Sanctum for Authentication system, by default it includes CSRF protections, session authentication and so we don't require to worry about XSS attacks.

In this article, we can see how to use Breeze API scaffolding for authenticating React Applications. Let's integrate

Laravel Backend Setup

Create a Laravel application and install Laravel breeze API scaffolding using the below commands



# Create a laravel application
composer create-project laravel/laravel react-backend

cd react-backend
# Install Breeze

composer require laravel/breeze
php artisan breeze:install api


Enter fullscreen mode Exit fullscreen mode

After running the above commands, Update FRONTEND_URL in env to localhost:3000 and serve the application using Laravel Sail or php artisan serve command

To test the app, Hit localhost:8000 in the browser, You can get the app version in response as below.



{
  "Laravel": "8.77.1"
}


Enter fullscreen mode Exit fullscreen mode

Now the Laravel backend app is ready to handle requests from React app. Next, let's set up the react app

React App Setup

We will use Create React App to set up a React app using the below command



npx create-react-app breeze-react

cd breeze-react

yarn start


Enter fullscreen mode Exit fullscreen mode

Configure Axios

To handle APIs, we will use Axios. Add global Axios client as below 

set withCredentials true to enable cross-site cookie access. REACT_APP_BACKEND_URL is localhost:8000 in .env file, which is the Laravel backend app created earlier.

CSRF request

Laravel breeze uses sanctum for authentication, So to authenticate the SPA. we need to make the first request to /sanctum/csrf-cookie endpoint. We need to make this request on all non authenticated routes. For instance login, Register, forgot password. 

Create a custom hook in hooks/auth.js file and add the below code to handle csrf request

Integrate Login API

Add the below login function in the useAuth hook 

When the login API is requested, first the CSRF API is requested and on success, login API is requested. Likewise, we can use register, forgot password, reset password APIs. Now we have integrated React App with Laravel breeze API scaffolding.

Laravel Breeze React

Laravel breeze react is the implementation of the Breeze authentication boilerplate for React, available in GitHub. It is preconfigured with all authentication APIs, routes and basic UI using TailwindCSS and CRA.

Features

  1. Prebuild Login, Register, Forgot password, Reset Password and Dashboard UI using Tailwind CSS
  2. Build with Create React App 5
  3. React Router 6 for routing
  4. SWR for revalidation user data
  5. ESLint

Quick Start Guide

Clone the laravel-breeze-react, install dependencies using yarn install, Then, copy the .env.example file to .env and add the URL of your backend as below



REACT_APP_BACKEND_URL=http://localhost:8000


Enter fullscreen mode Exit fullscreen mode

Run yarn start, Now you will see the below screen in the browser

login-image

laravel-breeze-react makes you to concentrate only on business logic, as it takes care of the authentication layer.

Resources

Laravel Breeze Docs
Laravel Breeze React repository
Sanctum Docs

Conclusion

Laravel Breeze makes the SPA Authentication very simple, secure and Laravel Breeze React makes the integration between Laravel Breeze Backend app with React App quickly.

Thank you for reading.

Get more updates on Twitter.

You can support me by buying me a coffee ☕

Free eBook

Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples

ReactJS Optimization Techniques and Development Resources

More Blogs

  1. Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS
  2. Don't Optimize Your React App, Use Preact Instead
  3. How to Reduce React App Loading Time By 70%
  4. Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support
  5. No More ../../../ Import in React
  6. 10 React Packages with 1K UI Components
  7. 5 Packages to Optimize and Speed Up Your React App During Development
  8. How To Use Axios in an Optimized and Scalable Way With React
  9. 15 Custom Hooks to Make your React Component Lightweight
  10. 10 Ways to Host Your React App For Free
  11. How to Secure JWT in a Single-Page Application

Top comments (2)

Collapse
 
franciscocaldeira profile image
Francisco

your code is not identend.. I just saw it on raw to see it better here is:

import axios from 'lib/axios'
import { useNavigate, useParams } from 'react-router-dom';

export const useAuth = () => {
    let navigate = useNavigate();

    const csrf = () => axios.get('/sanctum/csrf-cookie')

    const login = async ({ setErrors, setSuccessResponse }) => {
        await csrf()
        axios
            .post('/login', props)
            .then(() => {
                  setSuccessResponse();
                  navigate('/dashboard');
              });
            .catch(error => {
                setErrors(error);
            })
    }

    return {
        login
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rhenaldkarrel profile image
Rhenald Karrel

Hello, do you know how to access protected resources (like posting a blog) and embed the token on the axios's authorization? Thanks in advance