如何在使用nex-auth登录nextjs时保存用户数据?

Nas*_*sem 5 javascript next.js next-auth

我是 next-auth 的新手。当我点击登录按钮时,它会将我带到谷歌登录页面。它显示帐户列表。单击其中一个帐户后,它会显示图像和电子邮件。

这个signIn()函数来自模块next-auth/react。如果我想将用户的电子邮件和图像保存在数据库中,我该怎么做?我希望用户的电子邮件和图像保存过程在用户单击其任何帐户时发生。

我在哪里编写用于将用户数据保存在数据库中的代码,其中涉及典型的数据库步骤,例如使用数据模型、数据库连接等?

//页面/index.js:

import { useSession, signIn, signOut } from "next-auth/react";

export default function Home() {
  const { data: session } = useSession();

  if (session) {
    return (
      <>
        <p>Signed in as {session.user.email}</p>
        <img src={session.user.image} />
        <button onClick={() => signOut()}>Sign out</button>
      </>
    );
  }
  return (
    <div>
      <p>Not signed in</p>
      <button onClick={() => signIn()}>Sign in</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

//pages/api/auth/[...nextauth].js

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

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET
    })
  ],
});
Run Code Online (Sandbox Code Playgroud)

小智 1

基本上你需要使用一个适配器

NextAuth.js 中的适配器将您的应用程序连接到您想要用来存储用户及其帐户、会话等数据的任何数据库或后端系统。

因此,您可以转到 NextAuth 文档并在适配器部分阅读您正在使用的数据库。

适配器的类型将根据您使用的后端/数据库类型而有所不同,在我的例子中,我将 prisma 与 mongoDB 一起使用,因此我的下一个身份验证端点[...nextauth].ts如下:

import NextAuth from 'next-auth/next';
import GitHubProvider from 'next-auth/providers/github';
import GoogleProvider from 'next-auth/providers/google';
import {PrismaAdapter} from '@next-auth/prisma-adapter';
import { PrismaClient } from '@prisma/client';

const client = new PrismaClient(); 

export default NextAuth({
  adapter: PrismaAdapter(client), 
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    GitHubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,   
});
Run Code Online (Sandbox Code Playgroud)