Overview
Laravel Breeze Next.js uses Axios for HTTP requests and SWR for data fetching with caching and revalidation.Axios Configuration
The Axios instance is configured with Laravel Sanctum support:src/lib/axios.ts
Configuration Options
baseURL- The Laravel backend URL from environment variablesX-Requested-With: XMLHttpRequest- Identifies the request as an AJAX callwithCredentials: true- Sends cookies with cross-origin requestswithXSRFToken: true- Automatically includes CSRF token from cookies
Environment Variables
Set your backend URL in.env.local:
.env.local
SWR Data Fetching
Basic Usage
SWR provides automatic caching, revalidation, and error handling:SWR with useAuth
TheuseAuth hook uses SWR to fetch the current user:
src/hooks/auth.ts
- Automatic revalidation on focus/reconnect
- Caching for better performance
mutate()to manually revalidate- Error handling with
catch()
Making API Calls
GET Requests
POST Requests
PUT/PATCH Requests
DELETE Requests
Error Handling
Try-Catch Pattern
Validation Errors (422)
Laravel returns validation errors in this format:SWR Error Handling
Authentication Endpoints
TheuseAuth hook provides methods for all auth endpoints:
Register
POST /register
Login
POST /login
Forgot Password
POST /forgot-password
Reset Password
POST /reset-password
Email Verification
POST /email/verification-notification
Logout
POST /logout
Get Current User
GET /api/user
CSRF Protection
All mutation requests (POST, PUT, PATCH, DELETE) to Laravel require CSRF protection.Automatic CSRF Token
The Axios config includeswithXSRFToken: true, which automatically reads the CSRF token from the XSRF-TOKEN cookie and sends it in the X-XSRF-TOKEN header.
Fetch CSRF Cookie
Before making authenticated requests, fetch the CSRF cookie:useAuth hook does this automatically:
src/hooks/auth.ts
SWR Patterns
Revalidation
Manually revalidate cached data:Conditional Fetching
Only fetch when certain conditions are met:Optimistic Updates
Update UI immediately, then revalidate:Dependent Queries
Fetch data that depends on other data:TypeScript Types
Typing API Responses
Typing Error Responses
Best Practices
- Use SWR for GET requests - Automatic caching and revalidation
- Use axios directly for mutations - POST, PUT, PATCH, DELETE
- Always handle errors - Especially 422 validation errors
- Fetch CSRF token - Before authenticated mutations
- Call mutate() - After mutations to refresh data
- Type your responses - Use TypeScript interfaces
- Conditional fetching - Only fetch when data is needed
- Optimistic updates - For better UX
Common Patterns
Create Resource
Update Resource
Delete Resource
Pagination
Next Steps
- Authentication - Learn about the useAuth hook
- Components - Build UI components