TLDR
You need to make sure the requests include the Accept: application/json header.
Details
If a user does not authenticate, Laravel will throw an AuthenticationException.
This exception is handled by the render method in Illuminate/Foundation/Exceptions/Handler.php, and will in turn call the the unauthenticated() method which is defined in your app/Exceptions/Handler.php:
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('login'));
}
As you can see, by default, if the request expects a JSON response, you’ll get a 401 with a JSON error body. If the request does not expect JSON, the request is redirected to the login page.
The expectsJson() method will return true if your request has either the Accept: application/json header, or the X-Requested-With: XMLHttpRequest. The Accept: application/json header is more appropriate for api calls, whereas the X-Requested-With: XMLHttpRequest header is used for ajax calls.
So, without changing any of your application code, just make sure the requests include the Accept: application/json header.
However, if you need to have a different action happen when a user is not authenticated, you can modify this unauthenticated() method in app/Exceptions/Handler.php:
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
// return a plain 401 response even when not a json call
return response('Unauthenticated.', 401);
}
Tutorial last revisioned on August 10, 2022 with Laravel 9
API-based projects are more and more popular, and they are pretty easy to create in Laravel. But one topic is less talked about — it’s error handling for various exceptions. API consumers often complain that they get «Server error» but no valuable messages. So, how to handle API errors gracefully? How to return them in «readable» form?
Main Goal: Status Code + Readable Message
For APIs, correct errors are even more important than for web-only browser projects. As people, we can understand the error from browser message and then decide what to do, but for APIs — they are usually consumed by other software and not by people, so returned result should be «readable by machines». And that means HTTP status codes.
Every request to the API returns some status code, for successful requests it’s usually 200, or 2xx with XX as other number.
If you return an error response, it should not contain 2xx code, here are most popular ones for errors:
| Status Code | Meaning |
| 404 | Not Found (page or other resource doesn’t exist) |
| 401 | Not authorized (not logged in) |
| 403 | Logged in but access to requested area is forbidden |
| 400 | Bad request (something wrong with URL or parameters) |
| 422 | Unprocessable Entity (validation failed) |
| 500 | General server error |
Notice that if we don’t specify the status code for return, Laravel will do it automatically for us, and that may be incorrect. So it is advisable to specify codes whenever possible.
In addition to that, we need to take care of human-readable messages. So typical good response should contain HTTP error code and JSON result with something like this:
{
"error": "Resource not found"
}
Ideally, it should contain even more details, to help API consumer to deal with the error. Here’s an example of how Facebook API returns error:
{
"error": {
"message": "Error validating access token: Session has expired on Wednesday, 14-Feb-18 18:00:00 PST. The current time is Thursday, 15-Feb-18 13:46:35 PST.",
"type": "OAuthException",
"code": 190,
"error_subcode": 463,
"fbtrace_id": "H2il2t5bn4e"
}
}
Usually, «error» contents is what is shown back to the browser or mobile app. So that’s what will be read by humans, therefore we need to take care of that to be clear, and with as many details as needed.
Now, let’s get to real tips how to make API errors better.
Tip 1. Switch APP_DEBUG=false Even Locally
There’s one important setting in .env file of Laravel — it’s APP_DEBUG which can be false or true.
If you turn it on as true, then all your errors will be shown with all the details, including names of the classes, DB tables etc.
It is a huge security issue, so in production environment it’s strictly advised to set this to false.
But I would advise to turn it off for API projects even locally, here’s why.
By turning off actual errors, you will be forced to think like API consumer who would receive just «Server error» and no more information. In other words, you will be forced to think how to handle errors and provide useful messages from the API.
Tip 2. Unhandled Routes — Fallback Method
First situation — what if someone calls API route that doesn’t exist, it can be really possible if someone even made a typo in URL. By default, you get this response from API:
Request URL: http://q1.test/api/v1/offices
Request Method: GET
Status Code: 404 Not Found
{
"message": ""
}
And it is OK-ish message, at least 404 code is passed correctly. But you can do a better job and explain the error with some message.
To do that, you can specify Route::fallback() method at the end of routes/api.php, handling all the routes that weren’t matched.
Route::fallback(function(){
return response()->json([
'message' => 'Page Not Found. If error persists, contact info@website.com'], 404);
});
The result will be the same 404 response, but now with error message that give some more information about what to do with this error.
Tip 3. Override 404 ModelNotFoundException
One of the most often exceptions is that some model object is not found, usually thrown by Model::findOrFail($id). If we leave it at that, here’s the typical message your API will show:
{
"message": "No query results for model [AppOffice] 2",
"exception": "SymfonyComponentHttpKernelExceptionNotFoundHttpException",
...
}
It is correct, but not a very pretty message to show to the end user, right? Therefore my advice is to override the handling for that particular exception.
We can do that in app/Exceptions/Handler.php (remember that file, we will come back to it multiple times later), in render() method:
// Don't forget this in the beginning of file
use IlluminateDatabaseEloquentModelNotFoundException;
// ...
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Entry for '.str_replace('App', '', $exception->getModel()).' not found'], 404);
}
return parent::render($request, $exception);
}
We can catch any number of exceptions in this method. In this case, we’re returning the same 404 code but with a more readable message like this:
{
"error": "Entry for Office not found"
}
Notice: have you noticed an interesting method $exception->getModel()? There’s a lot of very useful information we can get from the $exception object, here’s a screenshot from PhpStorm auto-complete:
Tip 4. Catch As Much As Possible in Validation
In typical projects, developers don’t overthink validation rules, stick mostly with simple ones like «required», «date», «email» etc. But for APIs it’s actually the most typical cause of errors — that consumer posts invalid data, and then stuff breaks.
If we don’t put extra effort in catching bad data, then API will pass the back-end validation and throw just simple «Server error» without any details (which actually would mean DB query error).
Let’s look at this example — we have a store() method in Controller:
public function store(StoreOfficesRequest $request)
{
$office = Office::create($request->all());
return (new OfficeResource($office))
->response()
->setStatusCode(201);
}
Our FormRequest file app/Http/Requests/StoreOfficesRequest.php contains two rules:
public function rules()
{
return [
'city_id' => 'required|integer|exists:cities,id',
'address' => 'required'
];
}
If we miss both of those parameters and pass empty values there, API will return a pretty readable error with 422 status code (this code is produced by default by Laravel validation failure):
{
"message": "The given data was invalid.",
"errors": {
"city_id": ["The city id must be an integer.", "The city id field is required."],
"address": ["The address field is required."]
}
}
As you can see, it lists all fields errors, also mentioning all errors for each field, not just the first that was caught.
Now, if we don’t specify those validation rules and allow validation to pass, here’s the API return:
{
"message": "Server Error"
}
That’s it. Server error. No other useful information about what went wrong, what field is missing or incorrect. So API consumer will get lost and won’t know what to do.
So I will repeat my point here — please, try to catch as many possible situations as possible within validation rules. Check for field existence, its type, min-max values, duplication etc.
Tip 5. Generally Avoid Empty 500 Server Error with Try-Catch
Continuing on the example above, just empty errors are the worst thing when using API. But harsh reality is that anything can go wrong, especially in big projects, so we can’t fix or predict random bugs.
On the other hand, we can catch them! With try-catch PHP block, obviously.
Imagine this Controller code:
public function store(StoreOfficesRequest $request)
{
$admin = User::find($request->email);
$office = Office::create($request->all() + ['admin_id' => $admin->id]);
(new UserService())->assignAdminToOffice($office);
return (new OfficeResource($office))
->response()
->setStatusCode(201);
}
It’s a fictional example, but pretty realistic. Searching for a user with email, then creating a record, then doing something with that record. And on any step, something wrong may happen. Email may be empty, admin may be not found (or wrong admin found), service method may throw any other error or exception etc.
There are many way to handle it and to use try-catch, but one of the most popular is to just have one big try-catch, with catching various exceptions:
try {
$admin = User::find($request->email);
$office = Office::create($request->all() + ['admin_id' => $admin->id]);
(new UserService())->assignAdminToOffice($office);
} catch (ModelNotFoundException $ex) { // User not found
abort(422, 'Invalid email: administrator not found');
} catch (Exception $ex) { // Anything that went wrong
abort(500, 'Could not create office or assign it to administrator');
}
As you can see, we can call abort() at any time, and add an error message we want. If we do that in every controller (or majority of them), then our API will return same 500 as «Server error», but with much more actionable error messages.
Tip 6. Handle 3rd Party API Errors by Catching Their Exceptions
These days, web-project use a lot of external APIs, and they may also fail. If their API is good, then they will provide a proper exception and error mechanism (ironically, that’s kinda the point of this whole article), so let’s use it in our applications.
As an example, let’s try to make a Guzzle curl request to some URL and catch the exception.
Code is simple:
$client = new GuzzleHttpClient();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle123456');
// ... Do something with that response
As you may have noticed, the Github URL is invalid and this repository doesn’t exist. And if we leave the code as it is, our API will throw.. guess what.. Yup, «500 Server error» with no other details. But we can catch the exception and provide more details to the consumer:
// at the top
use GuzzleHttpExceptionRequestException;
// ...
try {
$client = new GuzzleHttpClient();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle123456');
} catch (RequestException $ex) {
abort(404, 'Github Repository not found');
}
Tip 6.1. Create Your Own Exceptions
We can even go one step further, and create our own exception, related specifically to some 3rd party API errors.
php artisan make:exception GithubAPIException
Then, our newly generated file app/Exceptions/GithubAPIException.php will look like this:
namespace AppExceptions;
use Exception;
class GithubAPIException extends Exception
{
public function render()
{
// ...
}
}
We can even leave it empty, but still throw it as exception. Even the exception name may help API user to avoid the errors in the future. So we do this:
try {
$client = new GuzzleHttpClient();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle123456');
} catch (RequestException $ex) {
throw new GithubAPIException('Github API failed in Offices Controller');
}
Not only that — we can move that error handling into app/Exceptions/Handler.php file (remember above?), like this:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json(['error' => 'Entry for '.str_replace('App', '', $exception->getModel()).' not found'], 404);
} else if ($exception instanceof GithubAPIException) {
return response()->json(['error' => $exception->getMessage()], 500);
} else if ($exception instanceof RequestException) {
return response()->json(['error' => 'External API call failed.'], 500);
}
return parent::render($request, $exception);
}
Final Notes
So, here were my tips to handle API errors, but they are not strict rules. People work with errors in quite different ways, so you may find other suggestions or opinions, feel free to comment below and let’s discuss.
Finally, I want to encourage you to do two things, in addition to error handling:
- Provide detailed API documentation for your users, use packages like API Generator for it;
- While returning API errors, handle them in the background with some 3rd party service like Bugsnag / Sentry / Rollbar. They are not free, but they save massive amount of time while debugging. Our team uses Bugsnag, here’s a video example.
Answer by Matteo Hickman
I think that first you need to set up your hosts different, your react app should have the main domain laravel-api.test without the port and your backend should be: api.laravel-api.test,
In this movie a woman fears that something terrible has happened in the past but it turns out to be a premonition
,
About the company
in your .env you should have this:
SESSION_DOMAIN=.laravel-api.test
SANCTUM_STATEFUL_DOMAINS=laravel-api.test
also in your backend: /config/cors.php , change the support_credentials to true :
'supports_credentials' => true,
Answer by Jasiah Hendrix
In React I made a function to easily send Axios requests:,In my routes (routes/api.php) I added two routes:,In my config/cors.php I added:
In my routes (routes/api.php) I added two routes:
Route::post('login', [AppHttpControllersLoginController::class, 'login']);
Route::middleware('auth:sanctum')->get('books', [AppHttpControllersBookController::class, 'list']);
In my config/cors.php I added:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
In my .env I added the following:
SESSION_DOMAIN=.laravel-api.test
SANCTUM_STATEFUL_DOMAINS=app.laravel-api.test:3000
In React I made a function to easily send Axios requests:
import axios from "axios";
const apiClient = axios.create({
baseURL: "http://laravel-api.test",
withCredentials: true,
});
export default apiClient;
Then I made a submit function for my login form:
const handleSubmit: FormEventHandler = (e) => {
e.preventDefault();
apiClient.get("sanctum/csrf-cookie").then((response) => {
apiClient
.post("api/login", {
email: email,
password: password,
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});
});
};
Is it the cookie? Is it the hostname?
import React from "react";
import apiClient from "../services/api";
interface Book {
id: string;
title: string;
}
const Books = () => {
const [books, setBooks] = React.useState<Book[]>([]);
React.useEffect(() => {
apiClient
.get("/api/books")
.then((response) => {
setBooks(response.data);
})
.catch((error) => console.error(error));
}, []);
const bookList = books.map((book) => <li key={book.id}>{book.title}</li>);
return <ul>{bookList}</ul>;
};
export default Books;
Answer by Rebekah Arroyo
Answer by Alyssa Novak
How do i fix 401 unauthorized error in react and laravel sanctum
,
How do i fix 401 unauthorized error in react and laravel sanctum
Answer by Alaina Robles
Domainlaravel-api.testpointing to my Homestead environment,React (npx create-react-app) running locally with a custom HOSTapp.laravel-api.test:3000,In React I made a function to easily send Axios requests:
Answer by Katherine Joseph
Then I made a submit perform for my login type:,Now my request for sanctum/csrf-cookie goes properly and I am going to obtain Cookies.,The request for login can also be going nice and it’ll return the Person.
Answer by Morgan Farrell
You may be working locally with the Laravel project; scaffolded a front-end app with React/Vue/Angular and when making requests to routes wrapped within auth:sanctum middleware, you may get an unauthenticated error. It is because of misconfigurations. Let’s fix this.,It is necessary for the front-end app(s) and the laravel app to serve from the same domain — localhost in our case.,And finally, you should make requests from the front-end app to the localhost/api/other-route but not to 127.0.0.1/api/other-route using axios.
SANCTUM_STATEFUL_DOMAINS=localhost:8080,127.0.0.1:8080,localhost:3000,127.0.0.1:3000
SESSION_DOMAIN=localhost
'paths' => ['api/*', 'login', 'register', 'otp/*', 'sanctum/csrf-cookie'],'supports_credentials' => true,
Answer by Richard Gilmore
hello I have a problem in react and laravel sanctum, it’s running fine when I test on postman, but it showing an error 401 Unauthorized when I implementing it in react,6 Laravel sanctum unauthenticated,4 Laravel Sanctum auth:sanctum middleware with Angular SPA unauthenticated response
this my stateful domain
'stateful' => explode(',', env(
'SANCTUM_STATEFUL_DOMAINS',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,' . parse_url(env('APP_URL'), PHP_URL_HOST),
)),
here’s my react front end
export const postLogout = (token) => (dispatch) => {
const config = {
headers: { Authorization: "Bearer " + token },
};
console.log(config);
axios.defaults.withCredentials = true;
axios.get("http://localhost:8000/sanctum/csrf-cookie").then((response) => {
axios
.post(`${Api}/logout`, config)
.then((res) => {
console.log(res);
dispatch({
type: POST_LOGOUT,
payload: res,
});
})
.catch((err) => {
console.log(err);
});
});
};
#laravel #vue.js #axios #laravel-sanctum
Вопрос:
Итак, у меня есть этот Laravel 8 проект VueJS 3 во внешнем интерфейсе, и я запускаю его на своем локальном
хосте И использую Sanctum для аутентификации.
Процесс входа и регистрации работает нормально, но когда я захожу на панель мониторинга и пытаюсь что-то добавить в свою базу данных, это выдает 401 Unauthorized ошибку.
Ларавель:
ИЗМЕНИТЬ: Пользовательский контроллер
public function login(Request $request)
{
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
$success = true;
$user = User::where('email', $credentials['email'])->first();
$token = $user->createToken("authToken")->plainTextToken;
} else {
$success = false;
}
$response = [
'success' => $success,
'access_token' => $token,
];
return response()->json($response);
}
web.php
Route::get('/{any}', function () {
return view('welcome');
})->where('any', '.*');
api.php
// Auth
Route::post('login', [UserController::class, 'login']);
Route::post('register', [UserController::class, 'register']);
Route::post('logout', [UserController::class, 'logout'])->middleware('auth:sanctum');
// Niveau
Route::group(['prefix' => 'niveaux', 'middleware' => 'auth:sanctum'], function () {
Route::get('/', [NiveauScolaireController::class, 'index']);
Route::post('add', [NiveauScolaireController::class, 'add']);
Route::get('edit/{id}', [NiveauScolaireController::class, 'edit']);
Route::post('update/{id}', [NiveauScolaireController::class, 'update']);
Route::delete('delete/{id}', [NiveauScolaireController::class, 'delete']);
});
cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'SANCTUM_STATEFUL_DOMAINS',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
session.php
'domain' => env('SESSION_DOMAIN', null),
So that’s what I set up for the Laravel side.
VueJS
app.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./Router/index";
import axios from "axios";
const app = createApp(App);
app.config.globalProperties.$axios = axios;
app.use(router);
app.mount("#app");
bootsrap.js
window.axios = require("axios");
window.axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
windoow.axios.defaults.withCredentials = true;
Компонент входа в систему
this.$axios.get("/sanctum/csrf-cookie").then((res) => {
this.$axios
.post("api/login", {
email: this.email,
password: this.password,
})
.then((res) => {
if (res.data.success) {
this.$router.push({ name: "Dashboard" });
} else {
console.log("Error: " res.data.message);
}
})
.catch(function (error) {
console.log("error :>> ", error);
});
});
Здесь мой запрос sanctum/csrf-cookie идет хорошо, и я получу файлы cookie, логин работает нормально, он получает пользователя из базы данных, а затем перенаправляет меня на панель мониторинга.
Проблема
Теперь вот, когда я пытаюсь отправить запрос (api/niveaux/add) , запрос отправляется, но я получаю 401 Unauthorized ошибку с {"message":"Unauthenticated."} ответом.
Компонент панели мониторинга
this.$axios
.post("api/niveaux/add", {
nom: this.niveau,
})
.then((res) => {
if (res.data.success) {
alert(res.data.message);
} else {
alert(res.data.message);
}
})
.catch(function (error) {
console.log("error :>> ", error);
});
Комментарии:
1. спасибо за вопрос. У меня та же проблема
Ответ №1:
вам нужно отправить вам access_token каждый запрос, который есть middleware('auth:sanctum') в laravel. вы можете найти access_token внутри файла cookie, который вы получаете после входа в систему. (может иметь другое имя, например token )
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
или
axios.defaults.headers.common['Authorization'] = `${access_token}`
должен сделать этот трюк
Комментарии:
1. Я пробовал, но это не работает, я отредактировал свой вопрос и добавил пользовательский контроллер, и в свой
boostarp.jsфайл я внес изменения, о которых вы мне сказали, но все равно не повезло
Ответ №2:
Я думаю, что вы получаете доступ через порт localhost 8000, но в вашем параметре с отслеживанием состояния в конфигурации sanctum его нет localhost:8000 . Конфигурация использует $_SERVER[‘ИМЯ_СЕРВЕРА’], поэтому она фактически ищет точное содержимое при доступе к нему.
sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'SANCTUM_STATEFUL_DOMAINS',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
'localhost:8000',
env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
Комментарии:
1. Я попробовал, все та же ошибка «401», у вас есть какие-либо другие идеи, которые могут вызвать эту проблему
Ответ №3:
заметил здесь опечатку:
window.axios = require("axios");
window.axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
windoow.axios.defaults.withCredentials = true;
последнее «виндоу» было написано неправильно.
Ответ №4:
Когда я столкнулся с этим, я отследил и сравнил изменения с существующим рабочим проектом
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'SANCTUM_STATEFUL_DOMAINS',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
в config/sanctum.php был изменен, я просто заменил его старым кодом
'stateful' => explode(',', env(
'SANCTUM_STATEFUL_DOMAINS',
'localhost,127.0.0.1,127.0.0.1:8000,::1,' . parse_url(env('APP_URL'), PHP_URL_HOST)
)),
I was able to resolve this error that dozens or hundreds of people report online, but none of the existing solutions worked for me, except for the following.
using Laravel 5.8, following docs to set up Passport.
In my case, although I was including the csrf token in a meta tag, it was not being picked up as the Passport documentation states that laravel will by default. from the docs (https://laravel.com/docs/5.8/passport#consuming-your-api-with-javascript):
» the default Laravel JavaScript scaffolding instructs Axios to always send the X-CSRF-TOKEN and X-Requested-With headers. «
and then the example is provided:
// In your application layout...
<meta name="csrf-token" content="{{ csrf_token() }}">
// Laravel's JavaScript scaffolding...
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
};
Well that would be great if it worked that way by default as the docs state, but in my case I had to explicitly set the axios default to include the contents of said csrf-token meta tag before making the axios request. like this:
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')
};
In my case, this was the only thing that allowed me to get past the 401 unauthorized error, which seems to indicate either:
A) something in my project’s configuration has altered the default behavior of axios requests by not setting them automatically include the csrf-token based on the meta tag if present or
B) the docs are inaccurate on this one point, and in the present version of Laravel and Passport that is not the default behavior as stated.


