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

咨询Auth.js(Next-Auth)登录成功后触发的回调函数

在Auth.js(Next-Auth)中记录登录活动的通用回调方案

有的,Auth.js(原Next-Auth)提供了**signIn回调函数**,它会在OAuth、魔法链接、凭证登录等所有方式完成成功登录后触发,完全适合用来记录登录活动历史这类场景。

核心用法示例

在你的Auth配置文件(通常是app/api/auth/[...nextauth]/route.js或pages/api/auth/[...nextauth].js)中,只需在callbacks字段下配置signIn回调即可:

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import EmailProvider from "next-auth/providers/email";

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    CredentialsProvider({
      credentials: {
        email: { label: "邮箱", type: "email" },
        password: { label: "密码", type: "password" },
      },
      async authorize(credentials) {
        // 这里写你的凭证验证逻辑,返回用户或null
        const user = await getUserByEmail(credentials.email);
        if (user && await validatePassword(credentials.password, user.passwordHash)) {
          return { id: user.id, email: user.email };
        }
        return null;
      },
    }),
    EmailProvider({
      // 魔法链接配置
      server: process.env.EMAIL_SERVER,
      from: process.env.EMAIL_FROM,
    }),
  ],
  callbacks: {
    async signIn({ user, account, isNewUser }) {
      // 登录成功后执行记录逻辑,比如写入数据库
      await saveLoginHistory({
        userId: user.id,
        loginMethod: account.provider, // 区分登录方式:google/email/credentials
        loginTimestamp: new Date(),
        isFirstLogin: isNewUser || false,
      });

      // 返回true允许登录,返回false会阻止用户进入系统
      return true;
    },
  },
};

export default NextAuth(authOptions);

关键细节说明

  • 触发时机:signIn回调会在用户通过任何登录方式完成授权并成功验证身份后立即执行,覆盖第三方OAuth登录、邮箱魔法链接、账号密码登录等所有场景。
  • 参数获取:通过account.provider可以准确识别用户使用的登录渠道;isNewUser参数可判断是否为用户首次登录,方便做新用户专属操作记录。
  • 错误处理:如果登录记录逻辑可能抛出异常,建议用try/catch包裹,避免因记录失败导致用户登录被阻断。
  • 扩展场景:若需在登录后修改会话数据,可结合session回调,但signIn是专门针对登录成功事件的回调,更适配登录审计、活动记录这类需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:15:04