Laravel 12 & Next.js Authentication with Sanctum – Guide
This tutorial will show you how to connect Laravel 12 (as the backend API) with Next.js 14+ (as the frontend) using Laravel Sanctum for authentication. We’ll build a basic full-stack authentication flow from register to logout.
Prerequisites
Tool | Requirement |
---|---|
PHP | 8.1 or higher |
Composer | Installed |
Node.js | 18.x or higher |
npm | Installed |
MySQL | Any version |
Git (optional) | Version control |
Project Structure
Step 1: Create the Laravel 12 Backend
1.1 Create Laravel Project
1.2 Configure Database
Edit the .env
file
1.3 Run Migrations
Step 2: Install Sanctum
Step 3: Enable API Tokens
In app/Models/User.php
, add
Step 4: Configure CORS
Update config/cors.php
Step 5: (Optional) Generate API Boilerplate
Step 6: Add Auth Routes
Edit routes/api.php
Step 7: Create the Next.js Frontend
7.1 Create App
7.2 Install Axios
Step 8: Axios Configuration
Create lib/axios.js
Step 9: Register Page
Create pages/register.js
Step 10: Login Page
Create pages/login.js
Step 11: Profile Page
Create pages/profile.js
Step 12: Run Both Servers
Laravel (Backend)
Next.js (Frontend)
Test It
-
Visit
/register
and create an account. -
Go to
/login
and log in. -
View your profile at
/profile
. -
Click Logout to clear the token and return to the login screen.
What's Next?
-
Protect frontend routes using
localStorage.getItem('token')
. -
Add middleware in Next.js for guarding pages.
-
Display a dynamic navbar (login/register/logout) based on authentication state.