首页 > 解决方案 > 会话中的 Next-Auth 用户对象为其值返回 null

问题描述

我正在尝试使用 nextjs、next-auth 和 prisma 实现身份验证。我可以成功登录,注销到我的帐户,但对于会话,它不会从 index.tsx 中的代码返回会话

Index.tsx - 我正在从这个文件记录会话对象,它返回一个未定义的值。

import React from 'react';
import { signIn, signOut, useSession } from 'next-auth/client';

export default function index() {
  const [session, loading] = useSession();

  React.useEffect(() => {
    console.log(session); // This returns an undefined value
  }, []);

  ...

}

[...nextauth].ts - 检查用户是否存在于数据库中,并在授权函数中使用 prisma 返回用户值。

export default NextAuth({
  providers: [
    providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        var user = null;
        await prisma.user
          .findMany({
            where: {
              email: credentials.email,
              password: credentials.password,
            },
          })
          .then((res) => {
            if (res) {
              user = res;
            }
          })
          .catch((err) => {
            throw err;
          });

        console.log(user);
        return user;
      },
    }),
  ],
  pages: {
    signIn: '/login',
  },
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60,
  },
  secret: process.env.JWT_SECRET,
});

应用程序.tsx

import { Provider } from 'next-auth/client';
import { AppProps } from 'next/app';

const App = ({ Component, pageProps }: AppProps) => {
  return (
    <Provider session={pageProps.session}>
      <Component {...pageProps}></Component>
    </Provider>
  );
};

export default App;

package.json - 我的环境中的依赖信息。

 {
      "name": "my-app",
      "version": "0.1.0",
      "private": true,
      "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
      },
      "dependencies": {
        "@prisma/client": "^2.30.3",
        "@tailwindcss/forms": "^0.3.3",
        "apollo-server-micro": "^3.3.0",
        "axios": "^0.21.3",
        "cookie": "^0.4.1",
        "graphql": "^15.5.2",
        "jsonwebtoken": "^8.5.1",
        "next": "11.1.2",
        "next-auth": "^3.29.0",
        "query-string": "^7.0.1",
        "react": "17.0.2",
        "react-dom": "17.0.2",
        "react-hook-form": "^7.15.0"
      },
      "devDependencies": {
        "@types/cookie": "^0.4.1",
        "@types/jsonwebtoken": "^8.5.5",
        "@types/node": "^16.7.10",
        "@types/react": "17.0.19",
        "autoprefixer": "^10.3.4",
        "eslint": "7.32.0",
        "eslint-config-next": "11.1.2",
        "postcss": "^8.3.6",
        "prisma": "^2.30.3",
        "tailwindcss": "^2.2.9",
        "ts-node": "^10.2.1",
        "typescript": "^4.4.2"
      }
    }

标签: reactjsnext.jsprismanext-auth

解决方案


您的控制台日志在会话未完全加载且仅运行一次时运行。在 index.tsx 上

将会话状态添加到 useffect 以在它更改时运行

    React.useEffect(() => {
        console.log(session);
       
  }, [session]); //Add session state to the useEffect

推荐阅读