@khin zin zin thinn It seems this response code 419 has somthong to do with csrf_token. Try to append this to your request _token: "{{ csrf_token() }}"
Can not log in to Laravel API via NextJs even though it's working with Postman
I am now creating a backend with Laravel and frontend with NextJs. I am using Laravel Sanctum to authenticate users via API. I have set up required things on Laravel and tested using Postman. It's working fine on Postman (It issues the user a token with cookie) but I keep receiving this error on NextJs POST http://localhost:8000/api/login 419 (unknown status) and can not proceed.
Auth Controller
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\Response;
class AuthController extends Controller
{
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response([
'message' => 'Invalid Response',
], Response::HTTP_UNAUTHORIZED);
}
$user = Auth::user();
$token = $user->createToken('token')->plainTextToken;
$cookie = cookie('jwt', $token, 60 * 24);
return response(['message' => 'Success', 'token' => $token])->withCookie($cookie);
}
public function logout(Request $request)
{
$cookie = Cookie::forget('jwt');
return response(['message' => 'Logged out successfully!'])->withCookie($cookie);
}
}
Routes (routes/api/admin.php)
<?php
use App\Http\Controllers\API\UserController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('register', [App\Http\Controllers\API\AuthController::class, 'register']);
Route::post('login', [App\Http\Controllers\API\AuthController::class, 'login']);
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('users', UserController::class)->parameters(['users' => 'user_code']);
Route::post('logout', [App\Http\Controllers\API\AuthController::class, 'logout']);
});
Http/Middleware/authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('login');
}
}
public function handle($request, Closure $next, ...$guards)
{
if ($jwt = $request->cookie('jwt')) {
$request->headers->set('Authorization', 'Bearer ' . $jwt);
}
$this->authenticate($request, $guards);
return $next($request);
}
}
This is how I am trying to login in NextJs
await fetch('http://localhost:8000/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
// credentials: 'include',
body: JSON.stringify({
email: values.email,
password: values.password,
}),
});
This is my first time trying to authenticate via API. Please guide me if there is anything wrong. Thanks.
Please or to participate in this conversation.