From abbd92ef85da2c6aaa4514abe59a64f64df247cc Mon Sep 17 00:00:00 2001 From: Tim Stollberg Date: Sat, 18 Jul 2026 16:09:04 +0700 Subject: [PATCH] fix(auth): return JSON 401 for unauthenticated requests unconditionally The previous Authenticate::redirectTo() -> null fix was incomplete: Laravel's default Handler::unauthenticated() still falls back to route('login') via '$exception->redirectTo() ?? route('login')' whenever the request isn't detected as expectsJson() (no Accept: application/json or X-Requested-With header), which throws RouteNotFoundException since this app has no named login route. Override unauthenticated() directly so this pure-API backend always returns a JSON 401, regardless of request headers. --- backend/app/Exceptions/Handler.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/backend/app/Exceptions/Handler.php b/backend/app/Exceptions/Handler.php index 56af264..68c889d 100644 --- a/backend/app/Exceptions/Handler.php +++ b/backend/app/Exceptions/Handler.php @@ -2,7 +2,9 @@ namespace App\Exceptions; +use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; +use Illuminate\Http\JsonResponse; use Throwable; class Handler extends ExceptionHandler @@ -27,4 +29,14 @@ public function register(): void // }); } + + /** + * This app is a pure JSON API (SPA frontend, no server-rendered login route), + * so unauthenticated requests always get a 401 JSON response instead of + * Laravel's default redirect-to-login fallback. + */ + protected function unauthenticated($request, AuthenticationException $exception): JsonResponse + { + return response()->json(['message' => $exception->getMessage()], 401); + } }