Securing Your Vue.js 3 App with Laravel 11 Middleware, Pinia, and Vue Router

When building a modern web application, ensuring its security is crucial. Combining Vue.js 3 with Laravel 11, Pinia, and Vue Router provides a strong foundation for building secure applications. This guide will walk you through the steps to integrate Laravel middleware with a Vue.js frontend, using Pinia for state management and Vue Router for routing.

Prerequisites

  • Basic knowledge of Vue.js, Laravel, and state management.
  • Installed Vue.js 3, Laravel 11, Pinia, and Vue Router in your project.

1. Setting Up Laravel Middleware

Laravel Middleware is used to filter HTTP requests entering your application. It can handle authentication, logging, and security checks.

  1. Create Middleware:
  2. In your Laravel project, create a middleware using the artisan command:
bash

php artisan make:middleware AuthCheck
  1. Define Middleware Logic:
  2. Edit the newly created middleware (app/Http/Middleware/AuthCheck.php):
php

<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

class AuthCheck
{
    public function handle(Request $request, Closure $next)
    {
        if (!Auth::check()) {
            return redirect('/login');
        }

        return $next($request);
    }
}
  1. Register Middleware:
  2. Add your middleware to the kernel (app/Http/Kernel.php):
php

protected $routeMiddleware = [
    'auth.check' => AppHttpMiddlewareAuthCheck::class,
    // other middlewares
];
  1. Apply Middleware to Routes:
  2. Apply it to your routes in routes/web.php:
php

Route::middleware(['auth.check'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

2. Configuring Pinia for State Management

Pinia is the state management library for Vue 3. It simplifies the state management in Vue apps.

  1. Install Pinia:
  2. Install Pinia in your Vue project:
bash

npm install pinia
  1. Set Up Pinia:
  2. Create a Pinia store. For example, stores/userStore.js:
javascript

import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
    state: () => ({
        user: null,
    }),
    actions: {
        async fetchUser() {
            const response = await fetch('/api/user');
            this.user = await response.json();
        },
    },
});
  1. Use Pinia in Vue:
  2. Initialize Pinia in your main.js or main.ts file:
javascript

import { createPinia } from ‘pinia’;

import { createApp } from ‘vue’;

import App from ‘./App.vue’;

import router from ‘./router’;

const app = createApp(App);

app.use(createPinia());

app.use(router);

app.mount(‘#app’);

3. Integrating Vue Router

Vue Router handles client-side routing in Vue applications.

  1. Set Up Vue Router:
  2. Install Vue Router if not already done:
bash

npm install vue-router@4
  1. Configure Router:
  2. Set up your routes in router/index.js or router/index.ts:
javascript

import { createRouter, createWebHistory } from ‘vue-router’;

import Home from ‘../views/Home.vue’;

import Login from ‘../views/Login.vue’;

import Dashboard from ‘../views/Dashboard.vue’;

const routes = [

{ path: ‘/’, component: Home },

{ path: ‘/login’, component: Login },

{ path: ‘/dashboard’, component: Dashboard, meta: { requiresAuth: true } },

];

const router = createRouter({

history: createWebHistory(),

routes,

});

router.beforeEach((to, from, next) => {

const isAuthenticated = /* logic to check authentication, e.g., from Pinia store */;

if (to.meta.requiresAuth && !isAuthenticated) {

next(‘/login’);

} else {

next();

}

});

export default router;

4. Combining Everything

  • Ensure that your Laravel backend validates user authentication properly.
  • Your Vue.js frontend should use Pinia to manage user state and Vue Router to handle navigation based on authentication status.
  • Use Vue Router’s navigation guards to prevent unauthorized access to protected routes.

Conclusion

Integrating Laravel 11 middleware with Vue.js 3, Pinia, and Vue Router provides a secure and scalable way to manage authentication and state in your application. By following these steps, you can build a robust security system that ensures only authorized users can access certain parts of your application.

Leave a comment

Your email address will not be published. Required fields are marked *