Next.js中NextAuth signIn函数重定向至错误页面问题
NextAuth 登录跳转至
/api/auth/error 的问题解决 问题描述
刚接触Next.js,尝试在本地用NextAuth为React应用添加Google/GitHub登录功能,但点击登录按钮时,页面重定向至http://localhost:3000/api/auth/error,而非预期的Google账号选择页。
项目代码与配置
LoginPage.tsx
"use client"; import { signIn, useSession } from "next-auth/react"; import Image from "next/image"; import Link from "next/link"; import { useRouter } from "next/navigation"; import React from "react"; const LoginPage = () => { const { status } = useSession(); const router = useRouter(); if (status === "loading") { return <p>Loading...</p>; } if (status === "authenticated") { router.push("/") } return ( <div className="p-4 h-[calc(100vh-9rem)] md:h-[calc(100vh-9rem)] flex items-center justify-center"> {/* BOX */} <div className=" h-full shadow-2xl rounded-md flex flex-col md:flex-row md:h-[70%] md:w-full lg:w-[60%] 2xl:w-1/2"> {/* FORM CONTAINER */} <div className="p-10 items-center flex flex-col gap-8 md:w-[100%]"> <h1 className="font-bold text-xl xl:text-3xl">Welcome</h1> <p>Log into your account or create a new one using social buttons</p> // ISSUE IS HERE <button className="flex gap-4 p-4 ring-1 ring-[#213b5e] rounded-md" onClick={() => { signIn('google')}} > <Image src="/google.png" alt="" width={20} height={20} className="object-contain" /> <span>Sign in with Google</span> </button> <button className="flex gap-4 p-4 ring-1 ring-[#213b5e] rounded-md" onClick={() => signIn("github")}> <Image src="/facebook.png" alt="" width={20} height={20} className="object-contain" /> <span>Sign in with GitHub</span> </button> <p className="text-sm"> Have a problem? <Link className="underline" href="/") {" "} Contact us </Link> </p> </div> </div> </div> ); }; export default LoginPage;
options.ts
import { NextAuthOptions, User, getServerSession } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import GithubProvider from "next-auth/providers/github"; import { prisma } from "./connect"; declare module "next-auth" { interface Session { user: User & { isAdmin: Boolean; }; } } declare module "next-auth/jwt" { interface JWT { isAdmin: Boolean; } } export const options: NextAuthOptions = { debug: true, session: { strategy: "jwt", }, providers: [ GoogleProvider({ // clientId: process.env.GOOGLE_ID as string, // clientSecret: process.env.GOOGLE_SECRET as string, clientId: process.env.GOOGLE_ID!, clientSecret: process.env.GOOGLE_SECRET!, }), GithubProvider({ // clientId: process.env.GOOGLE_ID as string, // clientSecret: process.env.GOOGLE_SECRET as string, clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET!, }), ], secret: "PLACE-HERE-ANY-STRING", }; export const getAuthSession = () => getServerSession(options);
router.ts
import { options } from "./options"; import NextAuth from "next-auth"; const handler = NextAuth(options); export {handler as GET, handler as POST}
.env
# Environment variables declared in this file are automatically made available to Prisma. # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB. # See the documentation for all the connection string options: https://pris.ly/d/connection-strings DATABASE_URL="postgresql://myuser:mypassword@localhost:5432/mydb?schema=public" NEXTAUTH_SECRET=This is text NEXTAUTH_URL=https://localhost:3000 GOOGLE_ID= 977467927902-trcb4gg3reqj34b6drhjs5novnftou12.apps.googleusercontent.com GOOGLE_SECRET= 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 GITHUB_ID=f83f7e3e91fef7d3af71 GITHUB_SECRET=81432edd1610b06fe0aec444ce8c679e26f48f07
已尝试的方法
- 删除api文件夹并重建
- 在.env中配置NEXTAUTH_URL
- 确认Google和GitHub的OAuth客户端已正确设置授权重定向URI
- 使用最新版next-auth和Next.js
排查与修复方案
1. 修复环境变量格式错误
.env中GOOGLE_ID和GOOGLE_SECRET的值前面存在空格,这会导致OAuth客户端ID/密钥被识别为无效值。修改为:
GOOGLE_ID=977467927902-trcb4gg3reqj34b6drhjs5novnftou12.apps.googleusercontent.com GOOGLE_SECRET=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
环境变量值前后不能有空格,否则会被当作值的一部分传入NextAuth。
2. 修正NEXTAUTH_URL配置
本地开发默认使用HTTP协议,将.env中的NEXTAUTH_URL改为:
NEXTAUTH_URL=http://localhost:3000
该URL必须与OAuth控制台中配置的重定向URI完全一致(控制台用HTTP就不能写HTTPS)。
3. 统一NextAuth Secret配置
options.ts中硬编码的secret与.env中的NEXTAUTH_SECRET冲突,建议删除硬编码值,改用环境变量:
export const options: NextAuthOptions = { debug: true, session: { strategy: "jwt", }, providers: [/* ... */], secret: process.env.NEXTAUTH_SECRET, // 改用环境变量 };
同时确保NEXTAUTH_SECRET是无空格的随机字符串,可通过openssl rand -hex 32生成。
4. 修复LoginPage中的语法错误
LoginPage里的Link组件存在语法错误,会影响页面渲染:
// 错误写法 <Link className="underline" href="/") {" "} Contact us </Link> // 正确写法 <Link className="underline" href="/"> Contact us </Link>
5. 查看Debug日志
已开启debug: true,启动项目后查看终端输出,日志会详细标注OAuth流程中的错误(如客户端ID无效、重定向不匹配等),这是最直接的排查依据。
内容的提问来源于stack exchange,提问作者brownstic
相关产品推荐
相关产品推荐

