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

Next.js 13中NextAuth登录功能失效问题求助

问题:NextAuth登录按钮点击后仅页面刷新,无跳转

环境

  • Next.js 13.4.19
  • next-auth 4.23.1
  • 已完成GitHub、Google OAuth提供商配置

现象

点击登录按钮后页面正常跳转到api/auth/signin路由,但点击页面内的GitHub/Google登录按钮时,仅触发页面刷新,不会跳转到对应平台的登录页,控制台无任何错误提示。

相关代码

app/api/auth/[...nextauth]/route.ts

import NextAuth from 'next-auth/next';
import { options } from '@/app/utils/options';

const handler = NextAuth(options);

export { handler as GET, handler as POST };

app/utils/options.ts

import type { NextAuthOptions } from 'next-auth';
import { validateCredentials } from './helpers/getCredentials';

import GoogleProvider from 'next-auth/providers/google';
import GithubProvider from 'next-auth/providers/github';
import DiscordProvider from 'next-auth/providers/discord';

const googleCredentials = validateCredentials(
  process.env.GOOGLE_CLIENT_ID!,
  process.env.GOOGLE_CLIENT_SECRET!
);

const githubCredentials = validateCredentials(
  process.env.GITHUB_CLIENT_ID!,
  process.env.GITHUB_CLIENT_SECRET!
);

export const options: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: googleCredentials.clientId,
      clientSecret: googleCredentials.clientSecret,
    }),
    GithubProvider({
      clientId: githubCredentials.clientId,
      clientSecret: githubCredentials.clientSecret,
    }),
  ],
};

已排查事项

  • GitHub OAuth应用回调URL设置为http://localhost:3000/api/auth/callback/github
  • 已查阅YouTube、GitHub相关解决方案,未解决问题

解决排查方向

  1. 验证环境变量有效性

    • 在options.ts中添加日志输出,确认环境变量是否正确加载:
      console.log('GitHub Client ID:', githubCredentials.clientId);
      
    • 确保.env.local文件放置在项目根目录,且重启开发服务器加载最新变量。
  2. 检查validateCredentials函数逻辑

    • 临时注释该函数,直接使用环境变量初始化Provider,排查是否是凭据验证函数导致的问题:
      GithubProvider({
        clientId: process.env.GITHUB_CLIENT_ID!,
        clientSecret: process.env.GITHUB_CLIENT_SECRET!
      })
      
  3. 确认NextAuth路由与提供商注册状态

    • 访问http://localhost:3000/api/auth/providers,查看返回的JSON是否包含GitHub、Google提供商,若为空数组则说明Provider未正确注册。
  4. 检查登录按钮的实现逻辑

    • 确保使用NextAuth提供的signIn函数触发登录,而非普通表单提交:
      import { signIn } from 'next-auth/react';
      
      const handleLogin = () => {
        signIn('github'); // 指定对应提供商
      };
      
    • 若使用表单,需阻止默认提交行为,避免页面刷新。
  5. 核对回调URL一致性

    • 确认GitHub/Google平台设置的回调URL与本地开发环境完全匹配(包括HTTP/HTTPS、端口号),无拼写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:52:28