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

LuisAduana's avatar

Sanctum doesn't works in api.php routes

Hi, I'm trying to do a connection between my SPA (VueJS) with my api (Laravel 7). I configured my kernel.php as the official documentation says:

Importing: Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

Adding: EnsureFrontendRequestsAreStateful::class

Following the steps, I configured CORS policy, then I config my axios request.

The problem is, when I do my request to '/sanctum/csrf-cookie' I got "GET http://localhost:8000/api/sanctum/csrf-cookie 404 (Not Found)"

If I change the URL request to http://localhost:8000/sanctum/csrf-cookie then it return me the cookie

I can do request api route without the cookie, this can not be possible if I have Sanctum for SPA authentication right?

Seems like Sanctum works only with web.php and not with api.php

I hope you can help me, thanks!

0 likes
4 replies
bobbybouwmann's avatar
Level 88

You can use the API requests, but you need to send the cookie or a token along in the request.

For the initial request to get the CSRF-cookie, you need to use the regular route indeed. The idea behind it is that you authenticate to a normal Laravel application and have some API routes available for dynamic parts of your application.

5 likes
edenwebstudio's avatar

@luisaduana Did you manage to resolve? I am having a similar problem. If I move the route to web.php it works but if the route it in api.php it returns a 401.

LuisAduana's avatar

Sorry, I didn't see your question all you have to do is add 'api' prefix on config/sanctum.php

On the last line before close brackets add

....

'middleware' => [
    'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
    'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],

'prefix' => 'api'  // <-------------- HERE!

];

If you have problems you can send me a message here [email protected]

I hope it helps you! (I migrated to Laravel 8)

2 likes
MarkusGrasselt's avatar

As I had the same problem after following along the Sanctum/Fortify documentation, I just want to leave a comment here, what was the issue in my case: The login and user route was working fine, which both used the middleware groups of 'web'. But for all routes under 'api' I got unauthenticated. After I added EncryptCookies to the api block, it worked for me.

'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

I'm just starting to learn Laravel, but my guess is the cookies where encrypted for the login, but as the api route didn't decrypt them they couldn't be read.

Please or to participate in this conversation.