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

如何让NextAuth集成Google登录时每次显示账号选择页面?

解决NextAuth Google登录后登出再登录自动跳过账号选择的问题

要实现完全退出会话且每次登录都显示Google账号选择页,需要从登出清除Google端会话和登录强制触发账号选择两个方面处理:


1. 登录时强制显示账号选择界面

Google OAuth2提供了prompt: "select_account"参数,无论浏览器是否存在已登录的Google会话,都会强制弹出账号选择页面。直接在signIn调用中添加该参数即可:

修改登录按钮的点击逻辑:

<button onClick={() => signIn("google", { prompt: "select_account" })}>Sign In</button>

2. 登出时同步清除Google端会话

默认的signOut()只会清除NextAuth的本地会话,Google浏览器端的登录状态仍会保留。需要在登出时指定Google提供商,让NextAuth触发Google的登出流程:

修改登出按钮的点击逻辑:

<button onClick={async () => {
    await signOut({
        provider: "google",
        callbackUrl: window.location.origin
    });
}}>Sign out</button>

修改后的完整组件代码

import type { NextPage, NextPageContext } from "next";
import { getSession, signIn, signOut, useSession } from "next-auth/react";

const Home: NextPage = () => {
    const { data, status } = useSession();

    return (
        <>
            {data?.user ? (
                <button onClick={async () => {
                    await signOut({
                        provider: "google",
                        callbackUrl: window.location.origin
                    });
                }}>Sign out</button>
            ) : (
                <button onClick={() => signIn("google", { prompt: "select_account" })}>Sign In</button>
            )}
            {data?.user?.name}
        </>
    );
};

export async function getServerSideProps(context: NextPageContext) {
    const session = await getSession(context);
    return {
        props: { session }
    };
}

export default Home;

可选:全局配置默认强制账号选择

如果希望所有Google登录请求都自动触发账号选择,可以在[...nextauth].js的Google提供商配置中全局设置参数:

import GoogleProvider from "next-auth/providers/google";
import NextAuth from "next-auth";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorization: {
        params: {
          prompt: "select_account",
          access_type: "offline",
          response_type: "code"
        }
      }
    })
  ]
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:45:46