【问题标题】:How to use next-iron-session with custom api route middleware in NextJS?如何在 NextJS 中使用 next-iron-session 和自定义 api 路由中间件?
【发布时间】:2021-05-18 22:54:12
【问题描述】:

我使用 next-iron-session 进行会话存储,使用 firebase 进行身份验证,每个 api 路由都应该有身份验证中间件和 next-iron-session,这是我第一次使用 NextJS。 尝试了几种不同的方法,但它们都不起作用,这是我所做的:

//auth-middleware.ts

import { NextApiRequest, NextApiResponse } from "next";
import { auth } from "utils/firebase-admin";
import { sessionObject } from "utils/session";
import { withIronSession } from "next-iron-session";

const withAuth = (handler: any) => {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    const { accessToken } = (<any>req).session.get("user");

    await auth.verifyIdToken(accessToken);

    return handler(req, res);
  };
};

export default withIronSession(withAuth, sessionObject);

//hello.ts (just a simple route)
import { NextApiRequest, NextApiResponse } from "next";
import authMiddleware from "utils/auth-middleware";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  res.status(200).json({ name: "John Doe" });
};

export default authMiddleware(handler);

我不确定它是否正确。

有什么帮助吗?

【问题讨论】:

    标签: javascript reactjs firebase next.js


    【解决方案1】:

    您需要在 withIronSession 函数调用周围附加一个闭包,以将 handler 函数传递给 withAuth。

    // auth-middleware.ts
    
    export default function authMiddleware(handler: any) {
        return withIronSession(withAuth(handler), sessionObject);
    };
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2019-12-03
      • 1970-01-01
      • 2023-02-13
      • 2019-11-14
      • 2020-03-09
      • 2013-09-04
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多