Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mcadio's avatar

How to integrate Laravel Fortify with my Vue 3 frontend?

I was upgrading my app from laravel 9 to 10, and I wanted to change from using a single vue component to using vue-router and SPA for the frontend. So far, I've upgraded to Laravel 10, and created the single page app with vue-router.

The problem is that I was doing my authentication using Fortify, and now adding ->middleware('auth') to my vue catchall route isn't working.

I've seen a variety of articles on how to make this work, only to break my app somehow. What is the simplest way to integrate what I've already got going on with Vue SPA? I'm using pinia store, and I don't know anything about nuxt.js so I'd like to avoid using it if possible. I also don't know inertia.js yet either.

Can someone dumb it down for me, or point me in the right direction? I don't want to publish my app without proper authentication and authorization, and I've been stuck for days.

0 likes
1 reply
LaryAI's avatar
Level 58

Integrating Laravel Fortify with a Vue 3 SPA (Single Page Application) involves setting up an API-based authentication system since your Vue app will be running separately from your Laravel backend. Here's a step-by-step guide to help you integrate Fortify with your Vue 3 frontend:

  1. Install Laravel Fortify: If you haven't already installed Laravel Fortify, you can do so by running the following command:

    composer require laravel/fortify
    
  2. Publish Fortify's Resources: Publish Fortify's configuration and views using the following command:

    php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
    
  3. Configure Fortify: In your config/fortify.php, make sure you have the features you want enabled, such as login, registration, etc.

  4. Set Up Fortify for SPA: Since you're using an SPA, you'll want to make sure Fortify is set up to work with JSON responses. In your App\Providers\FortifyServiceProvider, within the boot method, you can define the views to return JSON responses when the request expects JSON:

    use Laravel\Fortify\Fortify;
    use Illuminate\Http\Request;
    
    Fortify::loginView(function (Request $request) {
        if ($request->wantsJson()) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
        // return the login view if you have one
    });
    
    Fortify::registerView(function (Request $request) {
        if ($request->wantsJson()) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
        // return the registration view if you have one
    });
    
  5. Set Up Middleware: Since you're using a Vue SPA, you won't be able to use the auth middleware directly on your routes in the same way as a traditional Laravel app. Instead, you'll need to protect your API routes using the auth:sanctum middleware if you're using Laravel Sanctum for API token authentication.

    Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
        return $request->user();
    });
    
  6. Configure CORS: Make sure your config/cors.php is set up to allow requests from your Vue SPA's domain.

  7. Set Up Vue Router: In your Vue application, you'll need to set up navigation guards to protect your routes. Use the beforeEach hook in Vue Router to check if the user is authenticated before allowing access to certain routes.

    import { createRouter, createWebHistory } from 'vue-router';
    
    const router = createRouter({
      history: createWebHistory(),
      routes: [
        // ... your routes here
      ],
    });
    
    router.beforeEach((to, from, next) => {
      // Check if the route requires authentication and if the user is authenticated
      if (to.matched.some(record => record.meta.requiresAuth) && !store.isAuthenticated) {
        next('/login'); // redirect to login page
      } else {
        next(); // proceed to route
      }
    });
    
    export default router;
    
  8. Set Up Pinia Store: Use Pinia to manage your authentication state. You can create an auth store that keeps track of whether the user is logged in or not.

    import { defineStore } from 'pinia';
    
    export const useAuthStore = defineStore('auth', {
      state: () => ({
        isAuthenticated: false,
        // ... other auth-related states
      }),
      actions: {
        // ... actions for logging in, logging out, etc.
      },
    });
    
  9. Handle Authentication in Your Vue Components: In your Vue components, you'll use the auth store to handle login, registration, and user state.

    import { useAuthStore } from './stores/auth';
    
    const authStore = useAuthStore();
    
    // Example of a login method
    function login() {
      // Call your API to log in, then update the store
      authStore.isAuthenticated = true;
    }
    
  10. API Calls: When making API calls from your Vue app to your Laravel backend, ensure you're sending the necessary credentials (like API tokens) with your requests. If you're using Axios, you can set up defaults for headers, such as the Authorization header with the token.

Remember to run php artisan migrate after setting up Fortify to ensure that any necessary database tables are created.

This is a high-level overview, and you may need to adjust the code to fit your specific application's needs. Make sure to test your authentication flow thoroughly to ensure security.

Please or to participate in this conversation.