Outsource Laravel Development Partner - $3200/Month | Bacancy

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.

image
Curotec

Curotec helps software teams hire the best Laravel developers in Latin America. Click for rates and to learn more about how it works.

Visit Curotec
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
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
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

The latest

View all →
Laravel Boost Update Adds Support for the New MCP Protocol image

Laravel Boost Update Adds Support for the New MCP Protocol

Read article
Pest Adds withHost for Browser Testing Subdomains in Laravel image

Pest Adds withHost for Browser Testing Subdomains in Laravel

Read article
Run Artisan Make Commands in Laravel VS Code Extension image

Run Artisan Make Commands in Laravel VS Code Extension

Read article
Livewire 4 Is Dropping Next Week, and wire:transition Makes Animations Effortless image

Livewire 4 Is Dropping Next Week, and wire:transition Makes Animations Effortless

Read article
Laravel 12.45.1, 12.45.2, and 12.46.0 Released image

Laravel 12.45.1, 12.45.2, and 12.46.0 Released

Read article
"Don't Remember" Form Helper Added in Inertia.js 2.3.7 image

"Don't Remember" Form Helper Added in Inertia.js 2.3.7

Read article