Normalized Next Context
Next gives a "context" object of different types depending on whether your page uses getInitialProps, getServerSideProps, or getStaticProps.
To prevent headache juggling between those types, we provide a utility to normalize the differences in these context types into a single NextPageContext type.
The normalizeNextContext util
Example call
Refer to the implementation at packages/core/next/data-fetching/normalizeNextContext.ts.
You will normally pass whatever ctx you receive into the normalizeNextContext function, and you will get a NextPageContext object.
// Returns `NextPageContext`
const nextCtx = normalizeNextContext(ctx);
The different flavors
packages/core/next/data-fetching/normalizeNextContext.ts has variants that you can use depending on the type of your page:
staticCtxToNextCtx— for SSG pagesserverSideContextToNextContext— for SSR pagesserverSideContextToCacheableNextContext— for CSP pagesnextAPIContextToNextContext— for API routes
These function returns a NextPageContext object, that sometimes also has an extra property that is relevant to the type of page (for example, in CSP page, it will have an additional viewCacheKey property)
export const getServerSideProps: GetServerSideProps = async ctx => {
// You can now pass `nextCtx` to anything that accepts `NextPageContext`
const nextCtx = serverSideContextToNextContext(ctx);
// You can now define `getUserData` to just accept a `NextPageData`
// (no need to write `GetServerSidePropsContext | GetStaticPropsContext`)
const userData = await getUserData(nextCtx);
if (!userData.loggedIn) {
return {
redirect: {
destination: `/user/signin`,
},
};
}
return {
props: {
...sharedPageProps,
},
};
};
Usage in data-fetching helpers
If you use the data-fetching helpers/wrappers like staticProps or cacheableProps, the ctx we pass back to you has already been normalized, so you don't need to call normalizeNextContext or any of its variants.