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

NextAuth中User|AdapterUser类型不存在role属性的TypeScript错误

解决NextAuth自定义字段的TypeScript类型错误

问题根源

NextAuth的默认User、Session、JWT类型未包含你自定义的role和id字段,导致TypeScript无法识别这些属性。

解决方案

1. 扩展NextAuth类型定义

在项目根目录创建types/next-auth.d.ts文件,添加以下代码扩展默认接口:

import NextAuth from "next-auth";

declare module "next-auth" {
  // 扩展User类型,添加自定义字段
  interface User {
    id: string;
    role: number;
  }

  // 扩展Session类型,添加自定义字段
  interface Session {
    id: string;
    role: number;
  }
}

declare module "next-auth/jwt" {
  // 扩展JWT类型,添加自定义字段
  interface JWT {
    id: string;
    role: number;
  }
}

2. 确保TypeScript识别类型文件

修改tsconfig.json的include配置,确保包含上述类型文件:

{
  "compilerOptions": {
    // 保留原有配置...
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "types/**/*.d.ts"]
}

3. 验证回调代码

你的原回调代码逻辑无需修改,扩展类型后TypeScript会自动识别user.role、session.id等字段,类型错误将消失。

说明

通过声明模块扩展NextAuth的默认接口,TypeScript就能识别你在authorize中返回的自定义用户字段,同时解决JWT和Session回调中的类型不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:10:37