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

NextAuth Credentials授权函数类型不兼容错误求助

解决NextAuth Credentials授权的TypeScript类型错误

问题代码

import bcrypt from "bcrypt";
import type { NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { LoginSchema } from "@/schemas";
import { getUserByEmail } from "@/data/user";

export default {
    providers: [
        Credentials({
            async authorize(credentials) {
                const validatedFields = LoginSchema.safeParse(credentials);
                if (validatedFields.success) {
                    const {email, password} = validatedFields.data;

                    const user  = await getUserByEmail(email);
                    if (!user || !user.password) return;

                    const passwordMatch = await bcrypt.compare(password, user.password);
                    if (passwordMatch)  return user;
                }
                return;
            },
        }),
    ],
}satisfies NextAuthConfig

错误核心原因

  • NextAuth要求authorize函数必须返回User | null,但当前代码中return;会返回undefined,违反类型约束。
  • 自定义user对象包含password字段,而NextAuth内置的User类型没有该字段,导致类型不兼容。

修复方案

1. 替换无值返回为return null;

将代码中所有空返回的地方改为返回null,匹配NextAuth的类型要求:

if (!user || !user.password) return null;
// ...
return null;

2. 对齐自定义user与NextAuth的User类型

有两种方式处理类型不兼容问题:

方式一:扩展NextAuth的User类型

在项目中创建types/next-auth.d.ts文件,添加类型扩展:

import NextAuth from "next-auth";

declare module "next-auth" {
  interface User {
    password?: string | null;
  }
}
方式二:返回时剔除password字段

修改authorize函数中返回user的逻辑,移除password字段以匹配内置User类型:

if (passwordMatch) {
  const { password, ...userWithoutPassword } = user;
  return userWithoutPassword as User;
}

修复后的完整代码

import bcrypt from "bcrypt";
import type { NextAuthConfig, User } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { LoginSchema } from "@/schemas";
import { getUserByEmail } from "@/data/user";

export default {
    providers: [
        Credentials({
            async authorize(credentials) {
                const validatedFields = LoginSchema.safeParse(credentials);
                if (validatedFields.success) {
                    const { email, password } = validatedFields.data;

                    const user = await getUserByEmail(email);
                    if (!user || !user.password) return null;

                    const passwordMatch = await bcrypt.compare(password, user.password);
                    if (passwordMatch) {
                        const { password: _, ...userWithoutPassword } = user;
                        return userWithoutPassword as User;
                    }
                }
                return null;
            },
        }),
    ],
} satisfies NextAuthConfig

内容的提问来源于stack exchange,提问作者Ahmed Seddik Bouchiba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:31:40