How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

Harish Kumar · · 176 Views

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:

  1. Cookie-based SPA Authentication, which uses Laravel's built-in session authentication.

  2. 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:

  1. Cookie-based (SPA): This is ideal for traditional SPA applications that use session cookies.

  2. 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.

  1. Open the auth/login.vue file.

  2. Use the useSanctum() composable to call the login() 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>
  1. 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

  1. Logout: The module also provides a logout() method for logging users out.

  2. Middleware: You can easily set up authentication middleware to protect routes in your Nuxt application.

Troubleshooting Common Issues

  1. CSRF Token Errors: Ensure that the /sanctum/csrf-cookie endpoint is hit before making login requests.

  2. CORS Issues: Double-check the Laravel CORS configuration if you're seeing cross-origin errors in your browser console.

  3. 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:

  1. Nuxt Sanctum Authentication Documentation

  2. Nuxt Sanctum Authentication Demo Repository

Feel free to explore the module, try out different authentication modes, and let us know how it helps streamline your authentication flow!

0

Please login or create new account to add your comment.

0 comments
You may also like:

Understanding `.slice()` and `.splice()`: JavaScript Array Methods

In JavaScript, arrays come with numerous built-in methods for manipulation. Two commonly used methods are .slice() and .splice(). While they sound similar, their purposes and behaviors (...)
Harish Kumar

Vue 3.5 Release: What's New and Improved?

Vue.js has released version 3.5, bringing a host of exciting new features and optimizations designed to boost developer productivity and improve application performance. This update (...)
Harish Kumar

Laracon US 2024: Laravel 11 Minor Features That Enhance Performance

At Laracon US 2024, Taylor Otwell and the Laravel team introduced a series of "minor" features for Laravel 11 that are anything but minor. These enhancements, while not headline-grabbing (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

JavaScript Array .filter(): A Comprehensive Tutorial

JavaScript offers several powerful methods to manipulate arrays, and .filter() is one of the most versatile and commonly used. This tutorial will guide you through the basics of (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar