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

rafa-acioly's avatar

Using API route in inertia with laravel always returns unauthenticated

On my HTTP Kernel I've added the class EnsureFrontendRequestsAreStateful so it can take care of the sessions

'api' => [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

On my vue component I've also tried to use axios and router from inertia, but both solutions ended up giving me the error:

"Attempt to read property "storeCredential" on null"

Using router from inertia

router.get(`/api/store/${storeSku.value}`, {
    preserveState: true,
    onStart: () => set(isLoadingAddProduct, true),
    onSuccess: (page) => {
      console.log('Sucesso!', page)
    },
    onError: e => {
      console.log('Erro!', e)
    },
    onFinish: () => set(isLoadingAddProduct, false),
  })

Using axios

axios.get(`/api/store/${storeSku.value}`)
    .then(res => {
      set(errors, { storeSku: '' })
      set(selectedProductFromStore, res.data)
    })
    .catch(error => {
      if (error.response.status === 404) {
        set(selectedProductFromStore, {})
        set(errors, { storeSku: error.response.data.message })
      }
    })
    .finally(() => set(isLoadingAddProduct, false))

My route

Route::prefix('store')->group(function () {
    Route::get('/{sku}', [StoreProductController::class, 'show'])->name('store.index');
})->middleware(['auth:sanctum']);

The controller method

public function show(string $sku, Request $request): JsonResponse
    {
        $product = FindProductOnUserStore::run($request->user()->storeCredential, $sku);

        abort_unless($product, 404, 'Não foi possível encontrar o produto');

        return response()->json($product);
    }

What else can I do to call the "api" route from my components?

0 likes
4 replies
jlrdw's avatar

Maybe try curl just to see if you are getting to the end point correctly. Is your cors correctly setup.

Always just do small steps at a time while troubleshooting.

Also if not from here, there are some decent youtube videos on sanctum.

rafa-acioly's avatar

@jlrdw I can reach the endpoint correctly, that's how I can see the error "Attempt to read property "storeCredential" on null" on my controller

puklipo's avatar

If you use Inertia, just use regular web routes. Forget about api routes.

The original meaning of "API" is for external use, not for internal use.

puklipo's avatar

You misunderstand what Inertia is. Forget everything and learn the basics of how to use Inertia.

Please or to participate in this conversation.