Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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
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 more

Visit CodeRabbit
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 $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
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
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
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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

The latest

View all →
Streamline Conditional Logic with Laravel's Fluent Conditionable Trait image

Streamline Conditional Logic with Laravel's Fluent Conditionable Trait

Read article
Sublime Text Releases Update With Support for Right Sidebar image

Sublime Text Releases Update With Support for Right Sidebar

Read article
Enhance Email Validation with Laravel's Fluent Email Rule Object image

Enhance Email Validation with Laravel's Fluent Email Rule Object

Read article
Locale-aware Number Parsing in Laravel 12.15 image

Locale-aware Number Parsing in Laravel 12.15

Read article
Handle Fluent Values as Arrays with Laravel's array() Method image

Handle Fluent Values as Arrays with Laravel's array() Method

Read article
Chargebee Starter Kit for Billing in Laravel image

Chargebee Starter Kit for Billing in Laravel

Read article