DCodeMania
Home
Posts
React
Full Stack Laravel 10 & React JS | SPA Authentication | Part 2
Full Stack Laravel 10 & React JS | SPA Authentication | Part 2
Sahil Kumar
5 months ago
Full Stack Laravel 10 & React JS | SPA Authentication | Part 2
Share Via:
Introduction
Full Stack Laravel 10 & React JS is a robust technology stack used for building modern web applications. When combined, they provide a seamless and intuitive user experience that is both responsive and secure. One critical aspect of building such applications is implementing authentication, which ensures that only authorized users can access sensitive data and perform specific actions.
To implement SPA authentication in Full Stack Laravel 10 & React JS, Laravel Sanctum is a lightweight and token-based authentication package that can be used to secure API endpoints. Laravel Sanctum allows developers to generate and manage API tokens, which can be used to authenticate users' requests and provide access to protected resources.
When using Laravel Sanctum for SPA authentication, developers can choose to implement either stateless or stateful requests. Stateful requests involve persisting a user's authentication state on the server-side, while stateless requests do not. In stateful requests, the user's authentication state is stored on the server, and the user is identified using a session cookie. In contrast, stateless requests involve sending the API token with each request, and the server verifies the token's validity before responding.
Implementing stateful requests in Laravel Sanctum involves configuring session driver and stateful domain, while implementing stateless requests involves setting up middleware that checks for the token in the request headers.
Overall, Full Stack Laravel 10 & React JS with Laravel Sanctum provides developers with a robust and secure way to implement SPA authentication. Whether using stateful or stateless requests, Laravel Sanctum makes it easy to manage user authentication and authorization, providing developers with a secure and flexible way to build modern web applications.
This is the 2nd Part of the Full Stack Laravel 10 & React.js 18 series. In this part We'll see how to create React app and consume API that we have already seen in Part 1.
We'll see all the process in step by step:
Step 1: Install React Using Vite
Make sure you have Node.js and npm installed on your computer. You can check by running node -v and npm -v in your terminal.
npm 6.x
npm create vite@latest frontend --template react
npm 7+, extra double-dash is needed:
npm create vite@latest frontend -- --template react
Plaintext
Once you run above command then a directory named frontend will be created, now open this directory in VS Code.
Step 2: Installing Other Dependencies
We'll also use some other dependencies, in this React app, so to install all dependencies just follow the below command:
npm install react-router-dom axios flowbite flowbite-react
Plaintext
We'll also use some dev dependencies, so to install all dev dependencies just follow the following command:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Plaintext
Install tailwindcss and its peer dependencies via npm, and then run the init command to generate both tailwind.config.cjs and postcss.config.cjs.
Now here We are using react-router-dom for routing, axios for sending HTTP request, consuming backend, flowbite is a user interface (UI) kit and design system for building web applications. It is designed to help developers and designers create beautiful and responsive web interfaces quickly and easily. Flowbite provides a comprehensive set of UI components and templates that are designed to work together seamlessly, making it easy to create consistent and visually appealing web applications.
Step 3: Configuring Some Files
First, we'll open package.json file and add port in dev script like below, this will open our dev server in localhost with port = 3000.
"scripts": {
"dev": "vite --port=3000",
"build": "vite build",
"preview": "vite preview"
},
JavaScript
Next, we'll open tailwind.config.cjs file and update with below codes:
/** @type {import('tailwindcss').Config} /
module.exports = {
content: [
"./index.html",
"./src/**/.{js,ts,jsx,tsx}",
],
darkMode: 'media',
theme: {
container: {
padding: {
DEFAULT: '1rem',
sm: '2rem',
lg: '4rem',
xl: '5rem',
'2xl': '6rem',
},
},
extend: {
colors: {
primary: { "50": "#eff6ff", "100": "#dbeafe", "200": "#bfdbfe", "300": "#93c5fd", "400": "#60a5fa", "500": "#3b82f6", "600": "#2563eb", "700": "#1d4ed8", "800": "#1e40af", "900": "#1e3a8a" }
}
},
fontFamily: {
'body': [
'Inter',
'ui-sans-serif',
'system-ui',
'-apple-system',
'system-ui',
'Segoe UI',
'Roboto',
'Helvetica Neue',
'Arial',
'Noto Sans',
'sans-serif',
'Apple Color Emoji',
'Segoe UI Emoji',
'Segoe UI Symbol',
'Noto Color Emoji'
],
'sans': [
'Inter',
'ui-sans-serif',
'system-ui',
'-apple-system',
'system-ui',
'Segoe UI',
'Roboto',
'Helvetica Neue',
'Arial',
'Noto Sans',
'sans-serif',
'Apple Color Emoji',
'Segoe UI Emoji',
'Segoe UI Symbol',
'Noto Color Emoji'
]
}
},
plugins: [
require('flowbite/plugin')
],
}
JavaScript
Next, we'll open src/index.css file and just use the below codes:
@tailwind base;
@tailwind components;
@tailwind utilities;
CSS
Step 4: Working on Project Structure
In this step we'll create some directory and files inside src directory.
So, let's first create a components directory inside src directory. Now inside components directory we'll create two components:
GuestLayout.jsx
ProtectedLayout.jsx
These two components are the layouts components.
Next, we'll create pages directory inside src directory, and inside pages we'll create pages like:
Login.jsx
Register.jsx
Profile.jsx
About.jsx
Next, we'll create a contexts directory inside src directory, and inside this directory we'll a single file:
AuthContext.jsx
Step 5: Working on Router file
In this step we'll create a file inside src directory named router.js, inside this file just use below codes:
import { createBrowserRouter } from 'react-router-dom';
import Login from './pages/Login';
import About from './pages/About';
import Profile from './pages/Profile';
import Register from './pages/Register';
import ProtectedLayout from './components/ProtectedLayout';
import GuestLayout from './components/GuestLayout';
const router = createBrowserRouter([
{
path: '/',
element: ,
children: [
{
path: '/',
element: ,
},
{
path: '/register',
element: ,
},
],
},
{
path: '/',
element: ,
children: [
{
path: '/about',
element: ,
},
{
path: '/profile',
element: ,
},
],
},
]);
export default router;
JavaScript
The code above is setting up a router using createBrowserRouter from the react-router-dom library. This router is defining the routes for a web application with different layouts for guest and authenticated users.
The router is defined as an array of route objects. Each route object contains a path property which represents the URL path for that route, and an element property which specifies the component to be rendered when the path is matched.
The first route object is defining routes for guest users. The element property is set to a GuestLayout component, which will be used as the layout for these routes. The children property is an array of nested route objects, which define the specific pages that should be displayed within this layout. In this case, there are two routes defined - one for the login page (path: '/') and one for the registration page (path: '/register').
The second route object is defining routes for authenticated users. The element property is set to a ProtectedLayout component, which will be used as the layout for these routes. Similarly to the previous route object, the children property is an array of nested route objects, which define the specific pages that should be displayed within this layout. In this case, there are two routes defined - one for the about page (path: '/about') and one for the user profile page (path: '/profile').
Step 6: Working AuthContext.jsx file
This file is already created now, open this src/contexts/AuthContext.jsx file and just below codes:
import { createContext, useContext, useState } from 'react';
import axios from '../axios';
const AuthContent = createContext({
user: null,
setUser: () => {},
csrfToken: () => {},
});
export const AuthProvider = ({ children }) => {
const [user, _setUser] = useState(
JSON.parse(localStorage.getItem('user')) || null
);
// set user to local storage
const setUser = (user) => {
if (user) {
localStorage.setItem('user', JSON.stringify(user));
} else {
localStorage.removeItem('user');
}
_setUser(user);
};