Middlewares
Protected
Overview
The protected.ts middleware in Nuxt is used to guard routes behind a token-based protection system. It checks for a valid token and handles access control to certain routes based on the environment configuration and preview mode.
🔐 Behavior
- Skips middleware if protection is disabled via runtime config (
isMiddlewareProtectionEnabled) or required config is missing. - Skips middleware for builder preview URLs (
builder.previewquery). - Checks for a valid token stored in the
TOKEN_EU24WEB_DEVcookie. - Revalidates the token if it hasn't been checked in the last 24 hours using a timestamp stored in the
TOKEN_VALIDATION_LAST_DATE_EU24WEB_DEVcookie. - Calls
/api/token-validateto verify the token. - Redirects to
/protectedpage if the token is missing or invalid.
📄 Code Reference
export default defineNuxtRouteMiddleware(async (to, from) => {
const config = useRuntimeConfig();
if (
!config.public.isMiddlewareProtectionEnabled ||
!config.public.translationServiceBaseUrl
) {
return;
}
const access_token = useCookie("TOKEN_EU24WEB_DEV");
const isBuilderPreview = to.query["builder.preview"] !== undefined;
if (isBuilderPreview) return;
if (!access_token.value) {
return navigateTo("/protected");
} else {
const currentDate = new Date();
const expirationDate = new Date(
currentDate.getTime() + 7 * 24 * 60 * 60 * 1000
);
const authTokenDate = useCookie("TOKEN_VALIDATION_LAST_DATE_EU24WEB_DEV", {
maxAge: (expirationDate.getTime() - currentDate.getTime()) / 1000,
});
const token_validation_date_difference =
new Date() - new Date(authTokenDate.value);
if (token_validation_date_difference > 1000 * 60 * 60 * 24) {
const body = { _token: access_token.value };
let options = {
method: "POST",
params: body,
show_notifications: false,
show_loading_indicator: false,
};
let is_token_validate = await useAjax("/api/token-validate", options);
if (is_token_validate.is_expired) {
access_token.value = "";
authTokenDate.value = "";
return navigateTo("/protected");
}
if (is_token_validate.success) {
authTokenDate.value = new Date();
} else {
return navigateTo("/protected");
}
}
}
});
📝 Notes
- Ensure the token validation API is reliable and returns proper status flags.
- Consider moving configuration such as cookie keys to a centralized constant.
- Used mainly in conjunction with content localization and builder previews.