Skip to content

Commit

Permalink
ref(nextjs): Don't assert existance of pageProps in _app (#5945)
Browse files Browse the repository at this point in the history
Co-authored-by: Lukas Stracke <lukas.stracke@sentry.io>
  • Loading branch information
lforst and Lms24 committed Oct 13, 2022
1 parent 07990ac commit 960f9a5
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
Expand Up @@ -45,6 +45,15 @@ export function withSentryServerSideAppGetInitialProps(origAppGetInitialProps: A
});

const requestTransaction = getTransactionFromRequest(req);

// Per definition, `pageProps` is not optional, however an increased amount of users doesn't seem to call
// `App.getInitialProps(appContext)` in their custom `_app` pages which is required as per
// https://nextjs.org/docs/advanced-features/custom-app - resulting in missing `pageProps`.
// For this reason, we just handle the case where `pageProps` doesn't exist explicitly.
if (!appGetInitialProps.pageProps) {
appGetInitialProps.pageProps = {};
}

if (requestTransaction) {
appGetInitialProps.pageProps._sentryTraceData = requestTransaction.toTraceparent();

Expand Down
18 changes: 18 additions & 0 deletions packages/nextjs/test/integration/pages/_app.tsx
@@ -0,0 +1,18 @@
import App, { AppContext, AppProps } from 'next/app';

const MyApp = ({ Component, pageProps }: AppProps) => {
return <Component {...pageProps} />;
};

MyApp.getInitialProps = async (appContext: AppContext) => {
// This simulates user misconfiguration. Users should always call `App.getInitialProps(appContext)`, but they don't,
// so we have a test for this so we don't break their apps.
if (appContext.ctx.pathname === '/faultyAppGetInitialProps') {
return {};
}

const appProps = await App.getInitialProps(appContext);
return { ...appProps };
};

export default MyApp;
@@ -0,0 +1,4 @@
// See _app.tsx for more information why this file exists.
const Page = (): JSX.Element => <h1>Hello World!</h1>;

export default Page;
@@ -0,0 +1,11 @@
const expect = require('expect');

// This test verifies that a faulty configuration of `getInitialProps` in `_app` will not cause our
// auto - wrapping / instrumentation to throw an error.
// See `_app.tsx` for more information.

module.exports = async ({ page, url }) => {
await page.goto(`${url}/faultyAppGetInitialProps`);
const serverErrorText = await page.$x('//*[contains(text(), "Internal Server Error")]');
expect(serverErrorText).toHaveLength(0);
};

0 comments on commit 960f9a5

Please sign in to comment.