My current setup includes:
type Session = {
bearer: string,
firstName: string,
lastName: string,
etc...
};
interface ServerContext extends GetServerSidePropsContext {
session: Session,
};
export type ServerProps<P extends { [key: string]: any } = { [key: string]: any }> = (
context: ServerContext
) => Promise<GetServerSidePropsResult<P>>;
export const requireAuth = (gssp: GetServerSideProps) => {
return async (ctx: GetServerSidePropsContext) => {
const { req } = ctx;
const session = req?.headers?.cookie ? await getSession(req?.headers?.cookie) : null;
if (!session) {
return {
redirect: { permanent: false, destination: '/login' }
};
};
const serverSession = { ...ctx, session };
return await gssp(serverSession);
};
};
When using it, I follow this pattern:
export const getServerSideProps: ServerProps = requireAuth(async _ctx => {
const { session } = _ctx;
let account = session;
let stats = {};
try {
stats = fetchSomeData
} catch (error) {
console.log('Pages/Index Fetching Error: ', error);
}
return {
props: {
account: account,
stats: stats,
navbar: true,
footer: true,
},
};
});
The problem arises when accessing 'session' in '_ctx', triggering the error message: "Property session does not exist on type 'GetServerSidePropsContext<ParsedUrlQuery, PreviewData>'"
To bypass this issue, modifying 'index.d.tsx' within 'next/types' by adding 'session: Session' to GetServerSidePropsContext works, but extending the interface as shown above fails to resolve the problem.