Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jonaspauleta's avatar

Sanctum SPA Auth

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);
    }
0 likes
1 reply

Please or to participate in this conversation.