Courses

How to Build Laravel 11 API From Scratch

Authentication with Laravel Sanctum and SPA

Summary of this lesson:
- Setting up Sanctum for Single Page Applications
- Configuring CORS and cookies
- Protecting API routes with Sanctum middleware

In this lesson, we will see an example of how to authenticate users using Laravel Sanctum for a SPA application.

This lesson isn't about how to create an SPA application. The Vue.js part will only be shown partly.

We will change the home page to show categories and products for authenticated users.


Laravel Sanctum Setup

Laravel Sanctum comes with the default new Laravel installation. First, you must set the stateful domain. Your application must be on the same domain, but API can be on a subdomain.

Laravel has set some default stateful domains. You can check the domain in the config/sanctum.php. But, the correct way, in my opinion, would be to set the correct APP_URL in the .env, and Laravel will set the stateful domain automatically. Another option is to set SANCTUM_STATEFUL_DOMAINS in the .env without the http part.

Next, we must add the Sanctum EnsureFrontendRequestsAreStateful Middleware. Laravel has a method called statefulApi which can be added to enable this Middleware.

bootstrap/app.php:

return Application::configure(basePath: dirname(__DIR__))
->withProviders()
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->statefulApi();
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->renderable(function (NotFoundHttpException $e) {
return response()->json(['message' => 'Object not found'], 404);
});
})->create();

And for the CORS and cookies, we need to set...

The full lesson is only for Premium Members.
Want to access all 23 lessons of this course? (58 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord