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

  1. Locale Stripping: Removes locale prefix from path (e.g., /en-US/events/.../events/...).
  2. Model Detection:
    • Defaults to page
    • Switches to events if path starts with /events
  3. Content Lookup:
    • Calls builderStore.getItem() using the model and urlPath
    • Only requests the id field to minimize payload
  4. 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"],
});

📚 Learn More


Copyright © 2026