DBoman's avatar
Level 1

Laravel 13 + Sanctum + Fortify: API Routes Redirecting

I'm working on a web app that has a first-party SPA for the front-end and will use Laravel as an API for the backend, and I'm trying to get Sanctum set up to support authentication for the SPA. I'm using Fortify to manage authentication. For the moment, I am still using the Laravel router for web as well as API, but it seems like I've done something wrong because when I try to access a protected API route, the request gets caught by the RedirectIfAuthenticated middleware.

My application is running on localhost, and I have the following in config/sanctum.php:

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        Sanctum::currentApplicationUrlWithPort(),
        // Sanctum::currentRequestHost(),
    ))),

'guard' => ['web'],

In config/fortify.php:

'guard' => 'web',
'middleware' => ['web'],

In config/auth.php:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
        ],
    ],

I've added the statefulApi middleware to app.php as specified in the docs.

I can log in just fine using either the default configuration in the starter kit or by making an XHR request. Once I'm logged in, if I visit the dashboard, that loads correctly with the Sanctum authentication, as defined in web.php.

Route::middleware(['auth:sanctum'])->group(function() {
    Route::inertia('dashboard', 'Dashboard')->name('dashboard');

If I try to make a GET request to an API endpoint by visiting it in my browser once I've authenticated, I get redirected by the RedirectIfAuthenticated middleware. In api.php, I have:

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

I've verified that it is RedirectIfAuthenticated that is causing the issue by changing the redirect target for it, and I get redirected to the new location I specify. Similarly, if I try visiting the above when logged out, I get redirected to the login page. How can I get the API calls to return JSON instead of a redirect?

0 likes
2 replies
JussiMannisto's avatar

The guest middleware is an alias of RedirectIfAuthenticated. It's applied on routes that an authenticated user shouldn't see, e.g. login and registration pages. Are your routes inside a guest middleware block?

imrandevbd's avatar

you're testing this by visiting the endpoint directly in your browser, the browser is sending an Accept: text/html header by default instead of application/json

Please or to participate in this conversation.