Seamless Integration of Laravel Breeze API Scaffolding with React Applications
Nilanth
Posted on April 30, 2024
Introduction
In the ever-evolving landscape of web development, robust authentication mechanisms are paramount for building secure and scalable applications. Laravel Breeze, a powerful authentication scaffolding solution for both web and APIs, emerges as a beacon in this realm. Leveraging the robust Laravel Sanctum authentication system, Breeze offers a seamless and secure experience out of the box.
In this article, we will delve into the intricacies of integrating Laravel Breeze API scaffolding with React applications, combining the strengths of two powerful frameworks.
Laravel Backend Setup
Our journey begins with the establishment of the Laravel backend. We create a new Laravel application and install the Breeze API scaffolding using the following 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
With these commands, we set the foundation for our backend, incorporating the essential authentication scaffolding. Post-installation, it's imperative to update the FRONTEND_URL
in the environment file to localhost:3000. The application can be served using Laravel Sail or the php artisan serve
command.
A simple test by visiting localhost:8000
in the browser should reveal the app version as part of the response, signifying the readiness of our Laravel backend to handle requests from the React app.
React App Setup
Transitioning to the front end, we opt for Create React App to set up our React application. Execute the following commands to initialize the React app
npx create-react-app breeze-react
cd breeze-react
yarn start
This sets the stage for our React application, providing a solid foundation for further development.
Configuring Axios
To handle API requests in our React app, we leverage Axios. Add global Axios client as below:
import Axios from 'axios'
const axios = Axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL,
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
withCredentials: true
})
export default axios
Enable cross-site cookie access by setting withCredentials to true. Ensure to include REACT_APP_BACKEND_URL=localhost:8000
in the .env
file, which corresponds to the previously created Laravel backend application.
REACT_APP_BACKEND_URL=http://localhost:8000
This establishes the communication link between our React app and the Laravel backend.
CSRF Request
Given that Laravel Breeze utilizes Sanctum for authentication, the React app needs to make an initial request to the /sanctum/csrf-cookie
endpoint. This is crucial for authentication and should be performed on all non-authenticated routes such as login, register, and forgot password. To streamline this process, we create a custom hook in the hooks/auth.js
file to handle the CSRF request:
// auth.js
import axios from 'axios';
export const useAuth = () => {
const getCsrfToken = async () => {
await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sanctum/csrf-cookie`);
}
// Other authentication-related functions
return {
getCsrfToken,
// Other authentication-related functions
};
};
Integrating Login API
With the groundwork laid for CSRF handling, we proceed to integrate the login API. This involves adding a function to the useAuth hook:
// auth.js
import axios from 'axios';
export const useAuth = () => {
// Previous code
const login = async (credentials) => {
await getCsrfToken();
await axios.post(`${process.env.REACT_APP_BACKEND_URL}/login`, credentials);
// Handle login success or failure
};
// Other authentication-related functions
return {
getCsrfToken,
login,
// Other authentication-related functions
};
};
This function encapsulates the process of requesting the CSRF token before initiating the login API call, ensuring a secure and authenticated login experience.
Laravel Breeze React
For developers seeking a pre-configured React application template tailored for Laravel Breeze, Laravel Breeze React emerges as an ideal solution. This template, available on GitHub, combines the strengths of Laravel Breeze with the efficiency of Vite. Let's explore its features and a quick start guide to get you up and running seamlessly.
Features
Prebuilt UI Components: Laravel Breeze React comes equipped with prebuilt UI components for Login, Register, Forgot Password, Reset Password, and Dashboard, styled using Tailwind CSS. This accelerates development by providing a foundation for common authentication-related pages.
Built with Vite 4: Leveraging the latest features and performance improvements from Vite 4, Laravel Breeze React ensures a faster and more efficient development experience.
React Router 6: The template adopts React Router 6 for efficient and dynamic client-side routing, providing a smooth and seamless navigation experience.
SWR for Data Revalidation: SWR (Stale-While-Revalidate) is integrated to facilitate the revalidation of user data, ensuring that the application stays synchronized with the server's state.
ESLint: Maintaining code quality and adhering to best practices, Laravel Breeze React incorporates ESLint for static code analysis.
Quick Start Guide
- Clone the Repository: Begin by cloning the Laravel Breeze React repository from GitHub.
git clone https://github.com/nilanth/laravel-breeze-react
- Install Dependencies: Navigate into the cloned directory and install the project dependencies using Yarn.
cd laravel-breeze-react
yarn install
- Configure Environment: Copy the .env.example file to .env and specify the URL of your Laravel backend.
VITE_APP_BACKEND_URL=http://localhost:8000
- Run the Application: Execute the yarn start command to initiate the development server.
yarn start
Following these steps, you should witness the Laravel Breeze React template in action, presenting a clean and functional user interface.
Conclusion
In conclusion, the seamless integration of Laravel Breeze API scaffolding with React applications empowers developers to create robust, secure, and scalable web applications. By following the outlined steps, developers can establish a secure authentication layer, combining the strengths of Laravel Breeze and React. Whether opting for manual integration or leveraging templates like Laravel Breeze React, the result is a harmonious synergy between backend authentication mechanisms and frontend user experiences. This integration not only streamlines development but also ensures a resilient foundation for building modern web applications.
Thank you for reading.
You can support me by buying me a coffee ☕
More Blogs
Posted on April 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.