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

Firebase Auth自定义API路由问题:currentUser获取始终为null

问题解决:Firebase Auth跨API路由无法获取currentUser

问题原因

Next.js的API路由是无状态的独立请求上下文,每次API调用都会创建新的服务器实例。Firebase Auth的auth.currentUser仅在当前请求的上下文内有效,无法跨请求共享状态——这就是登录后调用get-user路由时auth.currentUser返回null的核心原因。

你已经在登录逻辑中生成了JWT并存储到httpOnly cookie里,正确的做法是在get-user路由中解析并验证这个JWT,通过JWT中的用户ID去获取用户信息,而不是依赖auth.currentUser。

修改方案

修改/api/auth/get-user路由,从请求cookie中取出JWT,验证其有效性后,使用JWT中的用户ID调用getUserFromFS获取用户信息:

修改后的/api/auth/get-user代码

import { getUserFromFS } from '@/app/libs/user';
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';

// 与登录路由一致的JWT密钥编码
const JWT_TOKEN = new TextEncoder().encode(process.env.JWT_SECRET!);

export const GET = async (req: NextRequest) => {
  if (req.method !== 'GET') return NextResponse.json({ message: '无效请求方法' }, { status: 401 });

  try {
    // 从cookie中获取authToken
    const authToken = req.cookies.get('authToken')?.value;
    if (!authToken) {
      return NextResponse.json({ message: '未登录' }, { status: 401 });
    }

    // 验证JWT的有效性
    const { payload } = await jwtVerify(authToken, JWT_TOKEN, {
      algorithms: ['HS256'],
    });

    // 从payload中取出用户ID,调用getUserFromFS获取用户信息
    const fetchedUser = await getUserFromFS(payload.id as string);
    if (!fetchedUser) {
      return NextResponse.json({ message: '用户不存在' }, { status: 404 });
    }

    return NextResponse.json({ fetchedUser }, { status: 200 });
  } catch (error) {
    // JWT验证失败(过期、篡改等)
    return NextResponse.json({ message: '登录状态无效' }, { status: 401 });
  }
};

额外说明

  • 确保process.env.JWT_SECRET在环境变量中正确配置,且登录和验证路由使用完全相同的密钥。
  • httpOnly cookie无法被前端JS读取,避免了XSS攻击风险,是安全的做法。
  • JWT验证会自动检查过期时间,无需额外处理过期逻辑。

内容的提问来源于stack exchange,提问作者Serdest PALAOĞLU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:11:11