typescript - 在 Next.js 中的高阶身份验证组件中返回附加数据

标签 typescript authentication next.js

我有以下代码:

export const requireAuth = (gssp: GetServerSideProps) => {
  return async (ctx: GetServerSidePropsContext) => {
    const { req } = ctx;
    let session = null;

    if (req?.headers?.cookie) {
      session = await getSession(req?.headers?.cookie);
    };

    if (!session) {
      return {
        redirect: {
          permanent: false,
          destination: '/login',
        },
      };
    };
    return await gssp(ctx);
  };
};

我还尝试在 await gssp(ctx) 中返回 session ,我对 NextJS 还很陌生,我无法找到任何相关信息。

当前方法允许我按以下方式使用该组件:

export const getServerSideProps: GetServerSideProps = requireAuth(async _ctx => {
  let account;
  let stats = {};

  if (_ctx?.req?.headers?.cookie) {
    account = await getSession(_ctx?.req?.headers?.cookie);
  }

  try {
    const X = fetchSomeData...;
  } catch (error) {
    console.log('Pages/Index Fetching Error: ', error);
  }

  return {
    props: {
      account: account,
      data: X,
      navbar: true,
      footer: true,
    },
  };
});

与其他 HOR 方法相比,它允许在使用它的页面上添加额外的逻辑。

有什么方法可以在主 requireAuth 组件中返回 session ,而不是在每个页面上获取它?

最佳答案

您可以控制高阶函数传递给实际 gssp 函数的内容,因此您只需在 ctx 对象中传递 session 即可。

export const requireAuth = (gssp: GetServerSidePropsWithSession) => {
    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 ctxWithSession = { ...ctx, session };

        return await gssp(ctxWithSession);
    };
};

然后,您可以在 getServerSideProps 代码中访问session

interface GetServerSidePropsContextWithSession extends GetServerSidePropsContext {
    session?: Session;
}

type GetServerSidePropsWithSession<P extends { [key: string]: any } = { [key: string]: any }> = (
    context: GetServerSidePropsContextWithContext
) => Promise<GetServerSidePropsResult<P>>;

export const getServerSideProps: GetServerSidePropsWithSession = requireAuth(async _ctx => {
    const account = _ctx.session;
        
    // Remaining code...
});

请注意,您需要扩展 GetServerSideProps 类型以获取 session 字段。

关于typescript - 在 Next.js 中的高阶身份验证组件中返回附加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72010291/

相关文章:

javascript - Canvas 绘图 : Await for images to load in a recursive method

javascript - 将 "this"绑定(bind)到 TypeScript Lambda

java - 登录和注销 session android

java - 如何通过 session 跟踪用户是否登录?

reactjs - 如果用户访问 Next.js 中的特定 URL,如何重定向到另一个页面?

reactjs - 如何在 Antd Input 上使用 React-Hook-Form?

javascript - Angular 2 : Promise rejection: alertify is not defined

java - 将 Oracle 身份验证迁移到表

browser - 频繁从 socket.io 接收数据时 React 崩溃

javascript - 在 JavaScript/Typescript 中将字符串数组转换为对象,最里面的子元素为空数组