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

Next.js + Facebook OAuth:NextAuth JWT回调TypeScript类型错误

解决NextAuth + TypeScript中JWT回调的类型错误

我在Next.js TypeScript项目里用NextAuth做Facebook认证,要获取access token调用API。代码基本遵循NextAuth文档实现,也按要求扩展了类型模块,但JWT回调一直报类型错误,不想把所有参数都设为any,求合理的解决办法。

现有代码

pages/api/auth/[...nextAuth].ts

...
export const authOptions = {
  callbacks: {
    async jwt({ token, user, account, profile }) {
      if (account) {
        token.accessToken = account.access_token
        token.id = profile.id
      }
      return token;
    },
    async session({ session, token, user }) {
      session.user.id = token.id;
      session.accessToken = token.accessToken;
      return session;
    }
  },
...

next-auth.d.ts

...
declare module "next-auth/jwt" {
  interface JWT {
    id: string;
    accessToken: string;
  }
}

declare module "next-auth" {
  interface Session {
    user: {
      id: string;
    }
  }
}

类型错误说明

当前报错主要集中在:

  • account.access_token 无类型定义
  • profile.id 可能为undefined,未做非空处理
  • session.accessToken 未在扩展的Session接口中声明
  • 回调参数未明确类型,导致token的自定义字段无法被TypeScript识别

解决步骤

1. 完善Session接口扩展

在next-auth.d.ts中,将自定义Session字段与NextAuth默认的DefaultSession合并,避免覆盖默认user字段(如name、email),同时添加accessToken:

import { DefaultSession } from "next-auth";

declare module "next-auth" {
  interface Session extends DefaultSession {
    accessToken: string;
    user: {
      id: string;
    } & DefaultSession["user"];
  }
}

declare module "next-auth/jwt" {
  interface JWT {
    id: string;
    accessToken: string;
  }
}

2. 给JWT回调参数指定明确类型

引入Facebook提供商对应的Account和Profile类型,同时添加非空判断避免undefined报错:

import type { JWT, Session, User } from "next-auth";
import type { OAuthAccount, Profile } from "next-auth/providers/facebook";

// 在authOptions内:
callbacks: {
  async jwt({ token, user, account, profile }: {
    token: JWT;
    user?: User;
    account?: OAuthAccount;
    profile?: Profile;
  }) {
    // 同时判断account和profile存在,避免访问undefined属性
    if (account && profile) {
      token.accessToken = account.access_token;
      token.id = profile.id;
    }
    return token;
  },
  // ...
}

3. 给Session回调参数指定类型

明确session和token的类型,让TypeScript识别自定义字段:

async session({ session, token }: {
  session: Session;
  token: JWT;
}) {
  session.user.id = token.id;
  session.accessToken = token.accessToken;
  return session;
}

4. 检查类型声明文件配置

确保next-auth.d.ts在TypeScript的扫描范围内:

  • 将文件放在项目根目录或src目录下
  • 检查tsconfig.json的include配置,确保包含该文件:
{
  "include": ["next-auth.d.ts", "**/*.ts", "**/*.tsx"]
}

内容的提问来源于stack exchange,提问作者Ishaan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:01:17