Are you getting the CSRF token first?
419 error when attempting to request from react to laravel
Front-End part
I have a react app that has this login form that sends this request
const handleLogin = async (e) => {
e.preventDefault();
try {
await axios.post("/login", { email, password });
} catch (e) {
// console.log(e);
}
};
Note: This is my axios configure
import axios from "axios";
export default axios.create({
baseURL: import.meta.env.VITE_BACKEND_URL,
withCredentials: true,
});
Back-End part
.env:
APP_URL=http://localhost:8000
FRONTEND_URL=http://localhost:5173
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:5173
Note: I installed breeze with starter kit for API and I have these auth routes
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware('guest')
->name('register');
Route::post('/login', [AuthenticatedSessionController::class, 'store'])
->middleware('guest')
->name('login');
// and some more
I also configured kernel.php like this -
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
Main problem
I am getting 419 error and this error response -
"message": "CSRF token mismatch.",
"exception": "Symfony\Component\HttpKernel\Exception\HttpException",
"line": 492,
Can anyone tell me what am I doing wrong and how can I solve this issue ? Thanks in advance.
Since axios's version 1.6.0 you need to use withXSRFToken as described here
https://github.com/axios/axios/pull/6046:
import axios from "axios";
export default axios.create({
baseURL: import.meta.env.VITE_BACKEND_URL,
withCredentials: true,
withXSRFToken: true
});
Don't forget to change config/cors.php file:
'supports_credentials' => true,//<-- default is false
And update this file if you are using sanctum with SPA authentication: app/Http/kernel.php
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,//<-- remove comment from this line
...
];
Please or to participate in this conversation.