How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)
In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (SSR) applications with Nuxt 3, integrating with Laravel Sanctum is one of the most efficient ways to ensure secure authentication for both SPA and API requests.
In this guide, we'll walk through how to set up Nuxt Sanctum Authentication, a module that simplifies the integration of Laravel Sanctum into your Nuxt 3 app.
Why Laravel Sanctum?
Laravel Sanctum provides a lightweight authentication system for SPAs and APIs. It offers:
Cookie-based SPA Authentication, which uses Laravel's built-in session authentication.
Token-based API Authentication for mobile apps and other APIs that need to authenticate without sessions.
The Nuxt Sanctum Authentication module allows you to easily switch between these two modes, making it a flexible solution for different types of applications.
Setting Up Nuxt Sanctum Authentication
Step 1: Installing the Nuxt Sanctum Authentication Module
To start, we need to install the Nuxt Sanctum Authentication module into our Nuxt 3 application. This module helps manage Laravel Sanctum's authentication process, from CSRF token management to login and logout functionality.
Open your terminal and run the following command within your Nuxt app directory:
npm install @qirolab/nuxt-sanctum-authentication
Once installed, Nuxt will automatically configure the module in your nuxt.config.ts
file, adding the module entry for nuxt-sanctum-authentication
.
export default defineNuxtConfig({
modules: ["@qirolab/nuxt-sanctum-authentication"],
});
Step 2: Configuring the API URL
In the nuxt.config.ts file, you'll need to specify the apiUrl
, which should point to your Laravel backend.
For example, if your Laravel app is running on http://api.myapp.test
, your configuration will look like this:
export default defineNuxtConfig({
modules: ["@qirolab/nuxt-sanctum-authentication"],
sanctum: {
apiUrl: 'http://api.myapp.test',
}
});
Step 3: Choosing the Authentication Mode
The nuxt-sanctum-authentication
module supports two modes of authentication:
Cookie-based (SPA): This is ideal for traditional SPA applications that use session cookies.
Token-based: Suitable for APIs where you want to authenticate using Bearer tokens.
By default, the module uses cookie-based authentication. However, you can switch to token-based authentication by configuring the authMode
option.
sanctum: {
apiUrl: 'http://api.myapp.test',
authMode: 'token', // Change to 'cookie' if using cookie-based SPA authentication
}
Step 4: Using the Authentication Composables
The module provides helpful composables for managing authentication in your Nuxt 3 application. One of the most useful composables is useSanctum()
, which provides methods like login()
and logout()
.
Here’s how to implement a basic login form in your Nuxt app.
Open the
auth/login.vue
file.Use the
useSanctum()
composable to call thelogin()
method and pass the user’s credentials.
<script setup lang="ts">
const form = ref({
email: "",
password: ""
});
const { login } = useSanctum();
const submitForm = async () => {
await login(form.value);
};
</script>
Bind the form submission to the
submitForm
method.
<form @submit.prevent="submitForm">
<!-- form inputs -->
</form>
Step 5: Handling CORS Errors
If you encounter CORS (Cross-Origin Resource Sharing) errors during your authentication requests, you may need to adjust the CORS configuration in your Laravel app.
Open the cors.php
file in Laravel (config/cors.php
) and ensure that paths like sanctum/csrf-cookie
and /login
are properly listed:
'paths' => ['api/*', 'sanctum/csrf-cookie', '/login'],
This allows Laravel to handle the necessary CORS headers for authentication requests.
Step 6: Testing the Login Request
Now that the login functionality is in place, it's time to test the setup. Open your Nuxt app in the browser, navigate to the login page, and submit the form. Use the browser's developer tools (Network tab) to check if the login request hits the correct API endpoint and whether it succeeds.
If you’ve followed the steps correctly, the API should respond with a 200 status code, and the user should be logged in successfully!
Additional Features
Logout: The module also provides a
logout()
method for logging users out.Middleware: You can easily set up authentication middleware to protect routes in your Nuxt application.
Troubleshooting Common Issues
CSRF Token Errors: Ensure that the
/sanctum/csrf-cookie
endpoint is hit before making login requests.CORS Issues: Double-check the Laravel CORS configuration if you're seeing cross-origin errors in your browser console.
Session Expiry: For cookie-based authentication, be sure to configure Laravel's session handling properly.
Conclusion
The Nuxt Sanctum Authentication module simplifies the integration of Laravel Sanctum into your Nuxt 3 application, providing a flexible and secure way to manage user authentication. Whether you're building an SPA or an API-driven app, this module ensures your authentication process is efficient, secure, and easy to implement.
To dive deeper into the setup process, watch the full video tutorial here:
Watch the Video Tutorial.
Useful Links:
Feel free to explore the module, try out different authentication modes, and let us know how it helps streamline your authentication flow!
Please login or create new account to add your comment.