You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express中tRPC createContext无法访问user对象问题求助

解决tRPC中无法访问Express req.user的问题

可能的原因及对应解决方案

1. 未实现Passport序列化/反序列化函数

Passport依赖这两个函数完成用户信息与Session的互转,缺失会导致后续请求无法恢复req.user。添加以下代码:

passport.serializeUser((user, done) => {
  // 存入Session的用户唯一标识,示例为user.id,可根据实际调整
  done(null, user.id);
});

passport.deserializeUser(async (userId, done) => {
  // 从数据库或存储中查询用户信息,替换为你的业务逻辑
  try {
    const user = await User.findById(userId);
    done(null, user);
  } catch (err) {
    done(err, null);
  }
});

2. Session中间件配置不完整

默认express-session配置可能导致Session无法正确保存或传递,完善配置:

app.use(
  session({
    secret: process.env.SESSION_SECRET, // 建议用环境变量存储密钥
    resave: false, // 无变化时不重新保存Session
    saveUninitialized: false, // 不保存未初始化的Session(如未登录请求)
    cookie: {
      secure: process.env.NODE_ENV === 'production', // 生产环境开启HTTPS Cookie
      sameSite: 'lax', // 防CSRF,可按需调整为'strict'或'none'
      maxAge: 24 * 60 * 60 * 1000, // Session有效期设为1天
    },
  }),
);

前端调用tRPC接口时若未携带Cookie,后端无法识别Session,导致req.user为undefined。确保客户端开启凭证携带:

  • 使用@trpc/client的httpLink:
import { createTRPCProxyClient, httpLink } from '@trpc/client';

const client = createTRPCProxyClient<AppRouter>({
  links: [
    httpLink({
      url: '/trpc',
      fetch(url, options) {
        return fetch(url, {
          ...options,
          credentials: 'include', // 关键:携带Cookie
        });
      },
    }),
  ],
});
  • 直接使用fetch:
fetch('/trpc/addTodo', {
  method: 'POST',
  credentials: 'include',
  body: JSON.stringify({ input: 'New Todo' }),
});

4. 扩展Express Request类型(TypeScript用户)

TypeScript默认Request类型不含user属性,需扩展类型避免报错:
在项目中创建types/express.d.ts文件:

declare global {
  namespace Express {
    interface Request {
      user?: {
        // 替换为你的用户实际结构
        id: string;
        name: string;
        email: string;
      };
    }
  }
}

export {};

验证步骤

  1. 登录后检查浏览器Cookie是否存在Session ID
  2. 查看tRPC请求的请求头是否包含Cookie字段
  3. 在tRPC createContext中打印ctx.req.session,确认Session是否正常存在

内容的提问来源于stack exchange,提问作者Simon Kinn Bjørnøy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:31:11