1

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.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
coolbeatz71
  • 928
  • 2
  • 10
  • 22
  • 1
    Does this help answer your question: [Creating a HOC (higher order component) for cookies in nextJS](https://stackoverflow.com/a/66088247/1870780)? You could create a wrapper function that you'd call on all your pages' `getServerSideProps` functions. – juliomalves May 23 '21 at 15:22
  • Hey, @juliomalves Lemme try this. – coolbeatz71 May 23 '21 at 21:45

1 Answers1

1

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"
zomars
  • 317
  • 1
  • 7