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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
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
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
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
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
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 →
Install Laravel Package Guidelines and Skills in Boost image

Install Laravel Package Guidelines and Skills in Boost

Read article
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article