如何检查用户是否是第一次使用Next-Auth登录?
我尝试按照官方文档实现 newUser 页面,但似乎并没有真正起作用。这是我在 [...nextauth].js 文件中的页面配置:
pages: {
signIn: "/auth/login",
newUser: "/auth/new-user",
},
我还尝试检查 jwt 回调上的 isNewUser 参数,但我只是获取了登录用户的数据,但没有用处:
callbacks: {
jwt: async (token, user, account, isNewUser) => {
console.log(isNewUser)
\\There is no relevant info using this
}
}
当用户创建帐户时,我的应用程序需要更多信息(家庭住址、出生日期等),而使用 SSO 并不总是可以提供这些信息。我需要检查用户是否是第一次登录,以便我可以将他们重定向到表单以填写缺少的信息。
实现此目的的一个简单方法是使用 cookies-next 库,您可以在here找到该库。查看链接,因为它们有非常简单且有用的解释。
无论如何,出于您的目的,您可以通过设置/检索存储有此信息的 cookie 来检查用户是否是首次登录。您可以在您想要的任何页面/组件中设置和检索 cookie,但听起来在您的情况下,您可能希望在仪表板页面或组件中执行此操作。
假设用户使用 next/auth 登录,登录后将被路由到仪表板页面。您可以使用 cookies-next 库来检查用户是否第一次访问该仪表板页面。
import { setCookies } from "cookies-next";
export default function Dashboard({ pageVisited }) {
// This is how the cookie would be set when the user accesses the dashboard page for the first time
useEffect(() => {
if (!pageVisited) {
setCookies("pageVisited", true);
}
}, []);
// You can do some conditional logic if it's the user's first time signing in
if (!pageVisited) {
// return something
}
}
export const getServerSideProps = async (ctx) => {
const { pageVisited } = ctx.req.cookies;
return { props: { pageVisited: pageVisited ?? null } };
};
如果您需要从另一个组件检索 cookie 以根据用户是否是首次访问者执行某些逻辑,您可以遵循与上述相同的模式:
export default function AnotherComponent({ pageVisited }){
if (pageVisited) {
// return something
}
}
export const getServerSideProps = async (ctx) => {
const { pageVisited } = ctx.req.cookies;
return { props: { pageVisited: pageVisited ?? null } };
};
注意:用户可以手动删除 cookie,在这种情况下,即使他们之前登录过,您的应用程序也会将其作为第一次读取。
我遇到了同样的问题,事实证明,将新用户重定向到专用页面以填写缺失的信息然后再继续操作要容易得多
pages
配置对我来说按预期工作,具有:
页面配置的 AuthJs Docs 并不是非常有用,但从
PagesOptions
界面来看,它说:
(property) newUser?: string | undefined
If set, new users will be directed here on first sign in
这是我的设置:
// (root)/auth.config.ts
pages: {
signIn: "/login",
newUser: "/onboarding", // Users land on this page when they first sign up/log in
},
// (root)/auth.ts
import { authConfig } from './auth.config';
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
...authConfig,
// Providers
// Callbacks
});
// app/api/auth/[...nextauth]/route.ts
export { GET, POST } from '@/auth';