Middlewares
Builder Error Page
🧭 Overview
This builder-error-page.ts middleware dynamically determines which Builder.io model to use (either page or events) based on the incoming URL path and checks if corresponding content exists. If not found, it throws a 404 error.
This is useful for routing content-managed pages in a CMS-driven site.
📄 Code Example
export default defineNuxtRouteMiddleware(async (to, from) => {
const urlPath = to.path.replace(/^\/[a-z]{2}-[A-Z]{2}/, "");
const builderStore = useBuilderStore();
let model = "page";
const isEventPage = urlPath.startsWith("/events");
if (isEventPage) model = "events";
const pageData = await builderStore.getItem(
model,
{ urlPath },
{},
{ fields: "id" }
);
if (!pageData) {
throw createError({
statusCode: 404,
statusMessage: "404 - Page Not Found",
});
}
});
⚙️ How It Works
- Locale Stripping: Removes locale prefix from path (e.g.,
/en-US/events/...→/events/...). - Model Detection:
- Defaults to
page - Switches to
eventsif path starts with/events
- Defaults to
- Content Lookup:
- Calls
builderStore.getItem()using the model andurlPath - Only requests the
idfield to minimize payload
- Calls
- Error Handling:
- Throws a 404 if no content is found
🔧 Use Case
You'd typically apply this middleware to dynamic routes like:
pages/
[slug].vue
events/
[eventSlug].vue
Apply it using route rules or directly inside the page component:
definePageMeta({
middleware: ["builder-error-page"],
});