0
votes

I'm trying to create SPA. I use Laravel API for backend and Nuxt.js for frontend. I want to authenticate users via Laravel Sanctum. I run backend on localhost:8000 and frontend on localhost:3000. SANCTUM_STATEFUL_DOMAINS is set to localhost:3000, SESSION_DOMAIN is set to localhost and SESSION_DRIVER is set to cookie.

I created login and logout in my app and everything works great until I make first request after logging in. I just wanted my app to return all users:

Route::middleware('auth:sanctum')->get('/users', function() { return User::all(); });

but it returns 401 unauthenticated. I don't know why is that happening. The route used for returning logged in user uses the same middleware:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

and works perfectly (Nuxt returns logged in user with every page change). I called users route with axios:

axios.get('http://localhost:8000/api/users')

What can cause this problem? This is very frustrating because I struggled a lot just to get the login and logout working.

I also thought about running API on api.domain.test and frontend on domain.test but is it possible to hook up a domain like that to Nuxt locally?

1

1 Answers

0
votes

It returns unauthorized because the call to the endpoint doesn't have access token of the user.

The idea is that when you login auth:sanctum returns access token to the client so that it can use it to access the data in all of it's next calls.

To do that you need to use authentication module in nuxt check this

The problem you are going to face next is that SPA doesn't have middleware so you need to set your app as universal instead of spa to be able to use the middleware in the client side