Overview Connecting a Nuxt.js frontend to a Laravel REST API creates a powerful, SEO-friendly architecture. By using session-based authentication rather than just tokens, you gain the native security benefits of CSRF protection and reduced XSS risks. This guide explores how to synchronize these environments to share cookies and fetch data seamlessly using a first-party frontend approach. Prerequisites To follow along, you need a working knowledge of JavaScript and PHP. You should have a Laravel API already configured and Nuxt.js (version 2 is used here) installed. Basic familiarity with terminal commands and local development environments like Laravel Valet will help you manage local subdomains. 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 Laravel Valet to link your API to `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. ```javascript async fetch() { const response = await this.$axios.get('/offices'); this.offices = response.data; } ``` For authentication, configure the Nuxt Auth Module in `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 Nuxt Auth Module, 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 Laravel Sanctum stateful domains include your Nuxt URL. If you miss this, Laravel won't attach the session middleware, and your authentication will fail silently. If you get 401 errors after a session expires, use an Axios interceptor to catch the error and force a logout on the frontend to keep the UI in sync with the server.
Laravel Valet
Software
Dec 2021 • 1 videos
High activity month for Laravel Valet. Laravel among the most active voices, with 1 videos across 1 sources.
Dec 2021
- Dec 6, 2021