Skip to content

Commit

Permalink
fix(nextjs): Fix runtime error for static pages
Browse files Browse the repository at this point in the history
  • Loading branch information
baked-dev committed Mar 16, 2023
1 parent 3269a06 commit 9ab0772
Showing 1 changed file with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,20 @@ import * as wrapee from '__SENTRY_WRAPPING_TARGET_FILE__';
import * as Sentry from '@sentry/nextjs';
// @ts-ignore This template is only used with the app directory so we know that this dependency exists.
// eslint-disable-next-line import/no-unresolved
import { staticGenerationAsyncStorage } from 'next/dist/client/components/static-generation-async-storage';
// @ts-ignore This template is only used with the app directory so we know that this dependency exists.
// eslint-disable-next-line import/no-unresolved
import { headers } from 'next/headers';

declare function headers(): { get: (header: string) => string | undefined };

declare const staticGenerationAsyncStorage: {
getStore: () => {
isStaticGeneration: boolean;
dynamicShouldError: boolean;
};
};

type ServerComponentModule = {
default: unknown;
};
Expand All @@ -38,9 +48,15 @@ if (typeof serverComponent === 'function') {
// If we call the headers function inside the build phase, Next.js will automatically mark the server component as
// dynamic(SSR) which we do not want in case the users have a static component.
if (process.env.NEXT_PHASE !== 'phase-production-build') {
const headersList = headers();
sentryTraceHeader = headersList.get('sentry-trace');
baggageHeader = headersList.get('baggage');
// The headers function can also not be used for revalidaton of previously statically generated pages as that
// results in a Runtime error because the page switches from static to dynamic
const staticGenerationStore = staticGenerationAsyncStorage.getStore();
const dynamicAllowed = !staticGenerationStore?.isStaticGeneration && !staticGenerationStore?.dynamicShouldError;
if (dynamicAllowed) {
const headersList = headers();
sentryTraceHeader = headersList.get('sentry-trace');
baggageHeader = headersList.get('baggage');
}
}

return Sentry.wrapServerComponentWithSentry(originalFunction, {
Expand Down

0 comments on commit 9ab0772

Please sign in to comment.