Middlewares
Checkout Protect
🧭 Overview
The checkout-protect.ts middleware ensures that only authenticated users—or guests using guest checkout—can access the checkout pages. It also checks if a valid trolley (cart) session exists.
📄 Code Example
// middleware/checkout-protect.ts
export default defineNuxtRouteMiddleware(async (to, from) => {
const authStore = useAuthStore();
const trolleyStore = useTrolleyStore();
const localePath = useLocalePath();
// 1. Block users who are neither authenticated nor on guest checkout
if (!authStore.is_authenticated && !authStore.is_guest_checkout) {
const rootStore = useRootStore();
rootStore.after_auth_intended_route = to.fullPath;
return await navigateTo(localePath("/login?type=guest"));
}
// 2. Redirect if trolley is missing
if (!trolleyStore.trolley_id) {
return await navigateTo(localePath("/trolley"));
}
});
⚙️ How It Works
1. Auth and Guest Checkout Check
- If the user is neither logged in nor checking out as a guest:
- Save their intended destination.
- Redirect to
/login?type=guestto offer both login and guest checkout options.
2. Trolley (Cart) Check
- If the trolley is empty or the session is lost, redirect to the
/trolleypage so they can start fresh.
🔧 Use Case
Ideal for checkout-related routes such as:
pages/
checkout/
address.vue
payment.vue
review.vue
Apply it inside the pages:
definePageMeta({
middleware: ["checkout-protect"],
});
📝 Notes
- Prevents unauthorized and cart-less access to the checkout.
- Supports guest checkout by checking
is_guest_checkout. - Seamlessly redirects with the intended route preserved for later navigation.