terlebach's avatar

Getting 401 when using axios in Jetstream Inertia project

Hello Friends!

There is an Issue in my current project when fetching Data from my API Endpoints using axios. I am always getting a 401 I was assuming that Inertia is taking care of the authentification. I am Using Laravel 9 Jetstream with Inertia which is running locally in Valet.

What I want to achieve are dashboard widgets that are independent. For example a "Online User"-Widget that is refreshing every 2s.

I know that I can (or should) use Inertia's partial reloads. My problem with that is, that the page is always refreshing. The process bar for example is always running every x seconds same goes for the browser info at the bottom. That simply doesn't feel right. If there would be a ways to use the partial loading asynchronously in the background that would be awesome.

This is what I have so far:

resources/js/bootstrap.js

window._ = require('lodash');

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

 import Echo from 'laravel-echo';

 window.Pusher = require('pusher-js');

 window.Echo = new Echo({
     broadcaster: 'pusher',
     key: process.env.MIX_PUSHER_APP_KEY,
     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
     forceTLS: true
 });

routes/api.php

Route::group(['middleware' => ['auth:sanctum', 'verified'], 'prefix' => 'v1', 'as' => 'api.v1.'], function(){
    Route::group(['prefix' => 'user', 'as' => 'user.'], function(){
        Route::get('online', [\App\Http\Controllers\Api\UserOnlineController::class, 'index'])->name('online.index');
    });
});

The actual Code in my Vue Widget:

function updateData()
{
    window.axios.get(route('api.v1.user.online.index')).then((response) => {
        console.log(response.data);
    })
}

I am really thankful for every suggestions. Maybe someone has a totally different approach or a Link to a best practice?

Thanks a lot!

0 likes
1 reply
terlebach's avatar
terlebach
OP
Best Answer
Level 7

I found the solution!

I had to uncomment in app\Http\Kernel.php following line: \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

:)

6 likes

Please or to participate in this conversation.