Replies: 2 comments 2 replies
-
|
Hi @InJaEE Are you able to fix that? I am also getting the same issue #85166 |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Hello! This is a common issue with static generation in Next.js. Here are the recommended solutions: Solution 1: Use Optional Chaining and Error Boundaries // app/[slug]/page.tsx
export default function Home() {
return (
<div>
<h1>{testData?.test?.test2?.name2 || 'Data not available'}</h1>
</div>
);
}Solution 2: Implement Error Handling with error.tsx 'use client';
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}Solution 3: Use React Error Boundary // app/[slug]/page.tsx
import { ErrorBoundary } from 'react-error-boundary';
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
export default function Home() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<div>
<h1>{testData.test.test2.name2}</h1>
</div>
</ErrorBoundary>
);
}Solution 4: Proper Data Fetching with Static Generation // app/[slug]/page.tsx
async function getData() {
try {
const res = await fetch('your-api-endpoint');
if (!res.ok) throw new Error('Failed to fetch data');
return res.json();
} catch (error) {
return null;
}
}
export default async function Home() {
const testData = await getData();
if (!testData) {
return <div>Data unavailable</div>;
}
return (
<div>
<h1>{testData.test.test2.name2}</h1>
</div>
);
}The key is combining proper error boundaries with safe data access patterns to prevent runtime errors during static generation. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Here is a simple example
This code causes the server to throw an error and render NextJS's default 500 error page because
testData.test.test2.name2is inaccessible when the page is visited after a build.The problem can be caused by the fact that the testData is not returned as the type you specified when you thought it was getting data from the server.
I would keep an empty generateStaticParams and use
1doesn't work, I want to render a page other than the default 500 error page when an error occurs (error.tsx doesn't work for me).Is this possible with the current functionality of NextJS?
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions