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.
- Create Middleware:
- In your Laravel project, create a middleware using the artisan command:
bash php artisan make:middleware AuthCheck
- Define Middleware Logic:
- 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);
}
}
- Register Middleware:
- Add your middleware to the kernel (
app/Http/Kernel.php):
php
protected $routeMiddleware = [
'auth.check' => AppHttpMiddlewareAuthCheck::class,
// other middlewares
];
- Apply Middleware to Routes:
- 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.
- Install Pinia:
- Install Pinia in your Vue project:
bash npm install pinia
- Set Up Pinia:
- 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();
},
},
});
- Use Pinia in Vue:
- Initialize Pinia in your
main.jsormain.tsfile:
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.
- Set Up Vue Router:
- Install Vue Router if not already done:
bash npm install vue-router@4
- Configure Router:
- Set up your routes in
router/index.jsorrouter/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.