Bridging the Gap: Integrating Nuxt.js with Laravel Sanctum
Overview
Connecting a
Prerequisites
To follow along, you need a working knowledge of
Key Libraries & Tools
- Axios: A promise-based HTTP client for the browser and Node.js.
- Nuxt Auth Module: A dedicated library to handle authentication strategies.
- Laravel Sanctum: Provides a featherweight authentication system for SPAs and simple APIs.
- Tailwind CSS: A utility-first CSS framework for rapid UI development.
Environment Synchronization
For session-based auth to work, both apps must share a top-level domain. Use api.ergodnc.test and proxy your Nuxt app to app.ergodnc.test. In your Laravel .env, set SESSION_DOMAIN to .ergodnc.test. This dot prefix is non-negotiable; it tells the browser the cookie belongs to all subdomains. Additionally, update cors.php by setting supports_credentials to true to allow the browser to pass cookies back and forth.
Code Walkthrough: Data Fetching and Auth
In your Nuxt pages, the fetch hook is your best friend. It allows you to populate data on the server side or during client-side navigation.
async fetch() {
const response = await this.$axios.get('/offices');
this.offices = response.data;
}
For authentication, configure the nuxt.config.js using the cookie strategy. You must define four critical endpoints: login, logout, user, and the Sanctum client-side-csrf cookie. This ensures Nuxt initializes the CSRF token before attempting a login.
Syntax Notes
Nuxt’s fetchState is an elegant way to handle UI states. Use $fetchState.pending to show loaders and $fetchState.error to catch failures. When using the $auth helper becomes globally available, allowing you to check $auth.loggedIn or access user data via $auth.user directly in your templates.
Tips & Gotchas
Always verify that your
