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

NextAuth自定义登录页无法正常登录跳转至首页问题如何修复?

问题根源

当前异常由两个配置缺失导致:

  1. NextAuth核心配置未声明自定义登录页路径,框架默认会跳转自带的内置登录页面
  2. 调用登录方法/提交表单时未指定登录成功后的回调地址,框架默认将当前登录页地址作为回调地址

修复步骤

1. 调整api/[...nextauth].js配置

新增pages字段指定自定义登录页的路径,完整配置参考:

export default NextAuth({
providers: [
    Providers.Credentials({
    name: 'Credentials',
    credentials: {
        email: { label: 'E-mail', type: 'text', placeholder: 'me@gmail.com' },
        password: { label: 'Password', type: 'password', placeholder: 'my password' },
    },
    async authorize(credentials, req) {
        // 实际业务场景请在此处添加账号密码校验逻辑,不要返回敏感字段如密码
        return { email: 'x' }
    },
    }),
],
// 新增配置:指定自定义登录页地址
pages: {
  signIn: '/auth/signin'
}
});

2. 调整自定义登录页登录逻辑

调用signIn方法时新增callbackUrl参数指定跳转至根路径,修改后代码参考:

export default function SignIn() {
const [password, setPassword] = useState('')
const [email, setEmail] = useState('')

const onSubmit = () => {
    signIn("Credentials", { 
      email, 
      password,
      // 指定登录成功后跳转的地址
      callbackUrl: '/'
    })
}

return (
    <div>
    <label>
        Email
        <input name="email" type="text" onChange={e => setEmail(e.target.value)} />
    </label>
    <label>
        Password
        <input name="password" type="password"  onChange={e => setPassword(e.target.value)} />
    </label>
    <button type="submit" onClick={onSubmit}>Sign in!</button>
    </div>
)
}

如果你使用原生form标签提交表单,需要额外添加隐藏字段指定回调地址,参考写法:

<form method="post" action="/api/auth/callback/credentials">
  <input name="email" type="text" />
  <input name="password" type="password" />
  <input type="hidden" name="callbackUrl" value="/" />
  <button type="submit">登录</button>
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:45:02