Middlewares
Buynow Protect
๐งญ Overview
The buynow-protect.ts middleware ensures that a user is authenticated and has a valid "Buy Now" trolley session before proceeding to a checkout-related route. It handles both direct visits and refreshes gracefully.
๐ Code Example
// middleware/buynow-protect.ts
export default defineNuxtRouteMiddleware(async (to, from) => {
const authStore = useAuthStore();
const checkoutStore = useCheckoutStore();
const localePath = useLocalePath();
// 1. Redirect unauthenticated users to login
if (!authStore.is_authenticated){
const rootStore = useRootStore();
rootStore.after_auth_intended_route = to.fullPath;
return await navigateTo(localePath("/login"));
}
// 2. If buy now trolley is missing
if (!checkoutStore.buy_now_trolley.id) {
if (to.fullPath.includes("buy-now") && !from.fullPath.includes("buy-now")) {
const rootStore = useRootStore();
// Track origin for analytics
if (!from.fullPath.includes("auth"))
rootStore.buy_now_source_route = from.fullPath;
return await navigateTo(localePath(from.fullPath || '/'));
} else {
// Handle direct visits or refreshes
const router = useRouter();
return await navigateTo(localePath((router.options.history.state.back || '/') as string));
}
}
});
โ๏ธ How It Works
1. Authentication Check
- If the user is not authenticated, it stores the intended route (
to.fullPath) and redirects them to/login.
2. "Buy Now" Trolley Validation
- If the trolley is missing:
- If the user came from another route and not from "buy-now", it redirects them back and logs the source route.
- If it's a refresh or direct visit (where
fromis not useful), it tries to go back using the routerโs history state.
๐ง Use Case
Youโd apply this middleware to routes like:
pages/
buy-now/
checkout.vue
confirm.vue
Inside those pages:
definePageMeta({
middleware: ['buynow-protect']
});
๐ Notes
- Protects against unauthorized access and expired/missing cart sessions.
- Useful for analytics by tracking
buy_now_source_route. - Handles edge cases like page refresh or server-side navigation.