My solution: rewrite withPageAuthRequiredFactory to allow customizing redirect destination.
export function withPageAuthRequiredFactory(redirectDestination: string): WithPageAuthRequired {
return ({ getServerSideProps, returnTo } = {}) =>
async (ctx) => {
// original `assertCtx` is changed to the following
if (!ctx.req) {
throw new Error('Request is not available');
}
if (!ctx.res) {
throw new Error('Response is not available');
}
// original `getSessionCache` is changed to the following
const session = await getSession(ctx.req, ctx.res);
if (!session?.user) {
return {
redirect: {
destination: redirectDestination,
permanent: true,
}
};
}
let ret: any = { props: {} };
if (getServerSideProps) {
ret = await getServerSideProps(ctx);
}
if (ret.props instanceof Promise) {
return { ...ret, props: ret.props.then((props: any) => ({ user: session.user, ...props })) };
}
return { ...ret, props: { user: session.user, ...ret.props } };
};
}
Usage:
export const getServerSideProps = withPageAuthRequiredFactory('/intro')()
this will make the protected page redirect to /intro if the user is unauthorized