404 page showing up when not needed

I am using builder.io with Next.js 14. I am using the app router so my page structure looks like src > app > [[…page]] > page.tsx. I am able to create pages in builder.io and everything works fine.

Now I created a 404 page. Because the above route is a catch-all and matches every page, the 404 page is caught inside the above page.tsx like so:

const content = await builder
// Get the page content from Builder with the specified options
.get(builderModelName, {
userAttributes: {
// Use the page path specified in the URL to fetch the content
urlPath: ‘/’ + (props?.params?.page?.join(‘/’) || ‘’),
},
})
// Convert the result to a promise
.toPromise();

// Check if the content exists
// if it doesn’t exist, redirect to the custom 404 page that we have built
if (!content) {
notFound();
return null; // This line won’t be reached because notFound() will redirect to the 404 page
}

This also works nicely.

Now the problem is: when I try to create a new page on builder.io, I do a “+ page” and the visual editor opens up. But at that point that page doesn’t quite exist (yet) so the above code gets triggered for 404 and it shows the 404 page (inside the visual editor). I need to wait for a few minutes before that goes away and I get the real blank page that I am supposed to get when crafting a new page.

The question is:

  • is there any way to update the above code so it gets triggered only in the deployed system but not when I am creating pages in the visual editor?

Hey, @naren , welcome to the Builder forum! You can add a condition to apply your if statement only when it is not in preview mode. For example:

if (!isPreviewing) {
    if (!content) {
        notFound();
        return null; // This line won’t be reached because notFound() will redirect to the 404 page
    }
}

Thank you @sheema. Works nicely.

If anybody finds it useful below is the full code:

'use client';
import { ComponentProps } from 'react';
import { BuilderComponent, useIsPreviewing } from '@builder.io/react';
import { builder } from '@builder.io/sdk';
import '../builder-registry';
import { notFound } from 'next/navigation';

type BuilderPageProps = ComponentProps<typeof BuilderComponent>;

// Builder Public API Key set in .env file
builder.init(process.env.NEXT_PUBLIC_BUILDER_API_KEY!);

export function RenderBuilderContent({ content, model }: BuilderPageProps) {
  const isPreviewing = useIsPreviewing();
  const isEditing = builder.editingMode;
  
  if (content || isPreviewing || isEditing) {
    return <BuilderComponent content={content} model={model} />;
  }

  notFound();
  return null; // This line won't be reached because notFound() will redirect to the 404 page
}
1 Like