在使用 iron-session 和 next.js 时,我在刷新和选项卡之间丢失了用户信息(会话)

分享于2022年07月17日 javascript next.js 问答
【问题标题】:在使用 iron-session 和 next.js 时,我在刷新和选项卡之间丢失了用户信息(会话)(I am losing user information (session) on refreshing and between tabs while using iron-session and next.js)
【发布时间】:2022-07-11 19:35:17
【问题描述】:

我目前正在使用 Iron-session 和 next.js 进行一个项目。点击 Link 标签不会失去我的用户。但是,如果我刷新用户变得未定义。 Cookie 已设置并且不会在刷新时被删除。不知道怎么回事。

这是我的 login.ts 代码:

export default withIronSessionApiRoute(loginRoute, sessionOptions);

async function loginRoute(req: NextApiRequest, res: NextApiResponse) {

    try {
        const {
            data: {tcId, admin, userName},
        } = await axios('http://localhost:8080/user/login', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            data: JSON.stringify(req.body),
        });
        const user = {tcId: tcId, userName: userName, admin: admin} as User;
        req.session.user = user;
        await req.session.save();
        
        res.json(user);
    } catch (error) {
        res.status(500).json({message: (error as Error).message})
    }}

这是我的 session.ts 代码:

// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import type { IronSessionOptions } from 'iron-session'
import type { User } from '../pages/api/user'

export const sessionOptions: IronSessionOptions = {
  password: process.env.SECRET_COOKIE_PASSWORD as string,
  cookieName: 'eys-cookie',
  // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
  cookieOptions: {
    secure: process.env.NODE_ENV === 'production',
  },
};

// This is where we specify the typings of req.session.*
declare module 'iron-session' {
  interface IronSessionData {
    user?: User
  }
}

正如我之前所说。我不会失去我的用户。在使用下一个 Link 标记进行路由时。 刷新导致失去我的用户。其他标签也无法访问我的用户。

如果需要,我可以显示更多代码。但我认为问题就在这里。

  • 你如何检查用户是否通过身份验证?

【解决方案1】:

我假设您正在遵循以下示例: https://github.com/vercel/next.js/tree/canary/examples/with-iron-session

您是否对 pages/_app.tsx 文件使用了相同的模板?我遇到了同样的问题,这解决了它。