Skip to content

Commit 9ab0772

Browse files
committed
fix(nextjs): Fix runtime error for static pages
1 parent 3269a06 commit 9ab0772

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

packages/nextjs/src/config/templates/serverComponentWrapperTemplate.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,20 @@ import * as wrapee from '__SENTRY_WRAPPING_TARGET_FILE__';
1313
import * as Sentry from '@sentry/nextjs';
1414
// @ts-ignore This template is only used with the app directory so we know that this dependency exists.
1515
// eslint-disable-next-line import/no-unresolved
16+
import { staticGenerationAsyncStorage } from 'next/dist/client/components/static-generation-async-storage';
17+
// @ts-ignore This template is only used with the app directory so we know that this dependency exists.
18+
// eslint-disable-next-line import/no-unresolved
1619
import { headers } from 'next/headers';
1720

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

23+
declare const staticGenerationAsyncStorage: {
24+
getStore: () => {
25+
isStaticGeneration: boolean;
26+
dynamicShouldError: boolean;
27+
};
28+
};
29+
2030
type ServerComponentModule = {
2131
default: unknown;
2232
};
@@ -38,9 +48,15 @@ if (typeof serverComponent === 'function') {
3848
// If we call the headers function inside the build phase, Next.js will automatically mark the server component as
3949
// dynamic(SSR) which we do not want in case the users have a static component.
4050
if (process.env.NEXT_PHASE !== 'phase-production-build') {
41-
const headersList = headers();
42-
sentryTraceHeader = headersList.get('sentry-trace');
43-
baggageHeader = headersList.get('baggage');
51+
// The headers function can also not be used for revalidaton of previously statically generated pages as that
52+
// results in a Runtime error because the page switches from static to dynamic
53+
const staticGenerationStore = staticGenerationAsyncStorage.getStore();
54+
const dynamicAllowed = !staticGenerationStore?.isStaticGeneration && !staticGenerationStore?.dynamicShouldError;
55+
if (dynamicAllowed) {
56+
const headersList = headers();
57+
sentryTraceHeader = headersList.get('sentry-trace');
58+
baggageHeader = headersList.get('baggage');
59+
}
4460
}
4561

4662
return Sentry.wrapServerComponentWithSentry(originalFunction, {

0 commit comments

Comments
 (0)