Issue
I have many pages that I suppose to protect using the firebase admin methods:
const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
try {
const cookies = nookies.get(ctx);
const token = await firebaseAdmin.auth().verifyIdToken(cookies.token);
const { uid, email } = token;
return {
props: {
email,
uid,
},
};
} catch (err) {
return {
redirect: {
permanent: false,
destination: "/",
},
props: {} as unknown as never,
};
}
};
const ExpertPage = (
props: InferGetServerSidePropsType<typeof getServerSideProps>,
) => {
return (
<Layout type={ILayoutType.EXPERT}>
<ProtectedPage1 props={props} />
</Layout>
);
};
export default ExpertPage;
As you can see, the function getServerSideProps
should be called on all those pages, it’s something I want to avoid.
I tried to move it in a helper in order to just call it as a type here InferGetServerSidePropsType<typeof getServerSideProps>
But it’s not running. I would like to know if there is a better way of doing it.
Solution
Just re-export it from the page:
// utils/commonGetServerSideProps.ts
const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
try {
const cookies = nookies.get(ctx);
const token = await firebaseAdmin.auth().verifyIdToken(cookies.token);
const { uid, email } = token;
return {
props: {
email,
uid,
},
};
} catch (err) {
return {
redirect: {
permanent: false,
destination: "/",
},
props: {} as unknown as never,
};
}
};
export default getServerSideProps;
// pages/expert.tsx
const ExpertPage = (
props: InferGetServerSidePropsType<typeof getServerSideProps>,
) => {
return (
<Layout type={ILayoutType.EXPERT}>
<ProtectedPage1 props={props} />
</Layout>
);
};
export default ExpertPage;
export { default as getServerSideProps } from "../utils/commonGetServerSideProps"
Answered By – zomars
Answer Checked By – Marie Seifert (AngularFixing Admin)