SPA Cookie Authentication
The nuxt-sanctum-authentication
module is specifically designed to seamlessly integrate with Laravel Sanctum's SPA (Single Page Application) cookie-based authentication. This setup provides a secure and efficient way to manage user authentication in your Nuxt 3 application.
Configuration
To enable SPA cookie-based authentication, you need to set the laravelSanctum.authMode
property to cookie
in your nuxt.config.ts
file:
export default defineNuxtConfig({
laravelSanctum: {
apiUrl: 'http://laravel-api.test', // Your Laravel API URL
authMode: 'cookie',
},
});
Domain Configuration
For this authentication mode to work correctly, your Nuxt and Laravel applications must share the same top-level domain. Here's an example setup:
Nuxt Application:
domain.com
Laravel Application:
api.domain.com
This ensures that cookies can be shared across both applications, which is crucial for maintaining the user's authentication state.
How It Works
Once the module is configured, you can authenticate users by sending their credentials to the designated login endpoint. Here's how you can do it:
const { login } = useSanctum();
const credentials = {
email: "john@doe.com",
password: "password",
remember: true,
};
await login(credentials);
When the login
method is called with the user's credentials, the module will handle the authentication process, including obtaining a CSRF token and setting the necessary cookies.
Post-Login Behavior
After a successful login, the user will be automatically redirected to the route specified in laravelSanctum.redirect.redirectToAfterLogin
. From this point on, the module will manage the authentication state, including requesting a CSRF cookie from the API and ensuring that it is included as an XSRF
header in all subsequent requests.
Laravel Configuration
To ensure that your Laravel backend properly supports SPA cookie authentication with Nuxt, you need to configure Laravel as follows:
Stateful Domains: Register your Nuxt application's domain in the
SANCTUM_STATEFUL_DOMAINS
environment variable.CORS Configuration:
Add your Nuxt domain to the
allowed_origins
list inconfig/cors.php
.Set
support_credentials
totrue
inconfig/cors.php
.
Sanctum Middleware: Enable Sanctum's
statefulApi
middleware to handle stateful API requests.Session Domain: Use the top-level domain for the session by setting
SESSION_DOMAIN=.domain.com
in your environment file. During development, you can uselocalhost
.
By following these steps, your Laravel application will be fully configured to support SPA cookie authentication with your Nuxt 3 frontend.
For more detailed instructions, refer to the official Laravel documentation on SPA Authentication.