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

Harish Kumar · · 1772 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:

15 Must-Know TypeScript Features to Level Up Your Development Skills

TypeScript has become the go-to tool for developers building scalable, maintainable JavaScript applications. Its advanced features go far beyond basic typing, giving developers (...)
Harish Kumar

JavaScript Best Practices: Tips for Writing Clean and Maintainable Code

JavaScript is one of the most versatile and widely used programming languages today, powering everything from simple scripts to complex web applications. As the language continues (...)
Harish Kumar

Shallow Copy vs Deep Copy in JavaScript: Key Differences Explained

When working with objects and arrays in JavaScript, it's crucial to understand the difference between shallow copy and deep copy. These concepts dictate how data is duplicated (...)
Harish Kumar

A Beginner’s Guide to Efficient Memory Use in JavaScript

Managing memory efficiently in JavaScript applications is essential for smooth performance, especially for large-scale or complex applications. Poor memory handling can lead to (...)
Harish Kumar

Understanding the `.reduce()` Method in JavaScript

The .reduce() method in JavaScript is one of the most powerful array methods used for iterating over array elements and accumulating a single value from them. Whether you're summing (...)
Harish Kumar

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar