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

arkanrosyid's avatar

How to Handle Unauthenticated JSON Responses for JWT Guard in Laravel 11?

Hi everyone,

I’m working on a Laravel 11 application with two authentication guards:

  1. web for session-based authentication.
  2. jwt for API token-based authentication using JWT.

The issue I’m facing is that when I use the auth:jwt middleware and the user isn’t authenticated, instead of returning a JSON response, the application redirects to the login page. This behavior is fine for web routes but not for API endpoints.

In previous versions of Laravel, I would override the unauthenticated method in app/Exceptions/Handler.php to handle this. However, in Laravel 11, the app/Exceptions/Handler.php file is no longer used, and configuration is done in bootstrap/app.php.

Here’s my current setup :

Guards in config/auth.php

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

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\RoleMiddleware;


return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->validateCsrfTokens(except: [
            'http://127.0.0.1:8000/api/*',
        ]);
        $middleware->alias([
           'role' => RoleMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Problem

When an unauthenticated request hits an API route protected by auth:jwt, it redirects to the login page instead of returning a JSON response like:

{
    "error": "Unauthenticated",
    "message": "Token is invalid or missing."
}

What I’ve Tried

I know that in Laravel 11, exception handling is configured in bootstrap/app.php using the withExceptions callback. I need to customize the behavior for unauthenticated requests based on the guard being used.

Question How can I modify the bootstrap/app.php file to ensure that:

  1. Requests using the jwt guard return a JSON response when unauthenticated.
  2. Requests using the web guard continue to redirect to the login page.

Thanks in advance for your help!

0 likes
2 replies
JussiMannisto's avatar
Level 50

AuthenticationException has a guards() method that you can use to check whether it originates from the jwt guard:

// bootstrap/app.php
use Illuminate\Auth\AuthenticationException;

return Application::configure(...)
	...
	->withExceptions(function (Exceptions $exceptions) {
	    $exceptions->render(function (AuthenticationException $e, Request $request): ?JsonResponse {
		    if(in_array('jwt', $e->guards()))
			    return response()->json([
				    'error' => 'Unauthenticated',
				    'message' => 'Token is invalid or missing.',
			    ]);
			
			return null;
	    });
    })->create();

That handles authentication exceptions from the jwt guard while letting Laravel handle others. If you only want this behavior for JSON requests, you can additionally check if $request->expectsJson() is true.

1 like

Please or to participate in this conversation.