Nuxt 3 + Laravel Sanctum Authentication: Secure Your SPA and API with Ease

Last updated on by

In modern web development, authentication is crucial for securing applications and protecting user data. The nuxt-sanctum-authentication module bridges the gap between Nuxt 3 and Laravel Sanctum, providing a streamlined and efficient way to handle both SPA (Single Page Application) and API token-based authentication. This module simplifies the integration process, managing complex tasks such as CSRF protection, Bearer token management, and seamless support for SSR (Server-Side Rendering) and CSR (Client-Side Rendering). Whether you're building a Nuxt app that requires secure login, or an API-driven project, this module offers a hassle-free solution to keep your application secure.

Before diving into the steps to set up authentication, check out these essential resources:

Setting Up Laravel Sanctum with Nuxt 3

Step 1: Install the nuxt-sanctum-authentication Module

To simplify integration between Nuxt 3 and Laravel Sanctum, you can use the nuxt-sanctum-authentication module. This module handles the complexities of both SPA and API authentication, including CSRF token management and Bearer tokens.

Start by installing the package in your Nuxt 3 app:

npm install @qirolab/nuxt-sanctum-authentication

Step 2: Configure nuxt.config.ts

Once installed, add the module to your nuxt.config.ts:

export default defineNuxtConfig({
modules: ["@qirolab/nuxt-sanctum-authentication"],
});

You also need to set the apiUrl for your Laravel app:

export default defineNuxtConfig({
modules: ["@qirolab/nuxt-sanctum-authentication"],
sanctum: {
apiUrl: "http://api.yourapp.test", // Replace with your Laravel API URL
},
});

Step 3: Set Up Login Functionality

In your Nuxt 3 app, you'll need to create a login page where users can input their credentials. You can use the useSanctum() composable to handle login requests. Here’s an example implementation:

<script setup lang="ts">
const form = ref({
email: '',
password: ''
});
 
const { login } = useSanctum();
 
const submitForm = async () => {
await login(form.value);
};
</script>
 
<template>
<form @submit.prevent="submitForm">
<input v-model="form.email" type="email" placeholder="Email" />
<input v-model="form.password" type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</template>

This simple login form sends the user’s credentials to the backend via Sanctum’s login endpoint, securing the communication using CSRF tokens.

SPA vs API Token Authentication

Depending on your app’s requirements, you can configure SPA or API token authentication. By default, the module uses cookie-based SPA authentication. To switch to API token authentication, you just need to update the authMode in nuxt.config.ts:

sanctum: {
apiUrl: "http://api.yourapp.test",
authMode: "token", // Switch to token-based authentication
}

Handling CORS Issues

A common issue when setting up cross-origin authentication between a Nuxt app and a Laravel API is CORS (Cross-Origin Resource Sharing) errors. To fix this, modify your config/cors.php in Laravel:

'paths' => ['api/*', 'sanctum/csrf-cookie', '/login'],

Ensure that the login endpoint is added to the paths array to allow CORS requests.

Testing Your Setup

After setting everything up, navigate to your login page in the browser. Open the Network tab in your browser's developer tools to inspect the login request. If everything is configured correctly, you should see a successful response without CORS errors.

Securing Your App

The combination of Nuxt 3 and Laravel Sanctum offers a powerful, flexible authentication solution that’s easy to implement. Whether you’re building a SPA that needs cookie-based authentication or an API that requires token-based authentication, this setup ensures your application remains secure and performant.

Why Use nuxt-sanctum-authentication?

Using the nuxt-sanctum-authentication module simplifies the entire authentication process between Nuxt 3 and Laravel Sanctum. It handles the complexities of managing CSRF tokens, Bearer tokens, and works seamlessly in both SSR and CSR modes.

Conclusion

Securing your Nuxt 3 app with Laravel Sanctum doesn’t have to be complicated. By using the nuxt-sanctum-authentication module, you can ensure that both SPA and API token-based authentication are implemented with ease, providing a robust security solution for your application. Follow this step-by-step guide to quickly set up a secure authentication process for your users.

Harish Kumar photo

Laravel developer skilled in PHP, JavaScript, Vue, React, TailwindCSS, and Docker. Creator of Qirolab, and a YouTube channel. Passionate about open-source contributions and developing tools to empower the developer community.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
URI Parsing and Mutation in Laravel 11.35 image

URI Parsing and Mutation in Laravel 11.35

Read article
Securing Laravel Sessions with ID Regeneration image

Securing Laravel Sessions with ID Regeneration

Read article
Paginate Multiple Eloquent Models with the Union Paginator Package image

Paginate Multiple Eloquent Models with the Union Paginator Package

Read article
Whisper.php - Automatic speech recognition and transcription image

Whisper.php - Automatic speech recognition and transcription

Read article
Multiple Column Plucking in Laravel Collections image

Multiple Column Plucking in Laravel Collections

Read article
File Manager Package for Livewire image

File Manager Package for Livewire

Read article