Level 29
Seems you are mixing up cookie based and token based auth. Since you are talking for a SPA you can follow the documentation https://laravel.com/docs/9.x/sanctum#logging-in
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I am getting started with SPA authentication with Laravel and React with a sample app, but I can't get what I'm missing
Code and logs bellow
Console log: https://imgur.com/1SlwhCg
import React, { useEffect } from "react"
import axios from "axios"
export default function App() {
const http = axios.create({
baseURL: 'http://localhost:8000',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json'
},
withCredentials: true,
})
useEffect(() => {
getUser()
}, [])
async function getUser() {
const csrf = await http.get('/sanctum/csrf-cookie')
console.log('csrf = ', csrf)
const login = await http.post('/api/login', {
email: '[email protected]',
password: 'password',
})
console.log('login = ', login)
const user = await http.post('/api/user')
console.log('user = ', user)
}
return (
<div>...</div>
)
}
public function login(Request $request) {
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
// Check email
$user = User::where('email', $fields['email'])->first();
// Check password
if(!$user || !Hash::check($fields['password'], $user->password)) {
return response([
'message' => 'Bad creds'
], 401);
}
$token = $user->createToken('myapptoken')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
Please or to participate in this conversation.