如何修复使用 Next-Auth 进行身份验证时出现的内部服务器错误?

Tho*_*len 9 javascript authentication reactjs next.js next-auth

我正在尝试使用 Next-Auth 将身份验证添加到我的 Next.js 项目。500 internal server error但是,提交凭据后我陷入了困境( http://localhost:3000/api/auth/error?error=Configuration)。

我认为这可能与在http://localhost:3000上运行有关,但我不确定。我做错了什么?

页面/api/auth/[...nextauth].js

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

const options = {
  site: 'http://localhost:3000',

  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        username: { label: 'Username', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      authorize: async (credentials) => {
        consol.log('credentials', credentials);
        const user = { id: 1, name: 'J Smith', email: 'jsmith@example.com' };
        if (user) {
          return Promise.resolve(user);
        } else {
          return Promise.resolve(null);
        }
      },
    }),
  ],
  database: process.env.MONGO_URI,
};

export default (req, res) => NextAuth(req, res, options);
Run Code Online (Sandbox Code Playgroud)

页面/index.js

import { useSession } from 'next-auth/client';

export default function Home() {
  const [session, loading] = useSession();
  console.log('session', session);

  return (
    <div className="container">
      <main>
          {session && <p>Signed in as {session.user.email}</p>}
          {!session && (
            <p>
              <a href="/api/auth/signin">Sign in</a>
            </p>
          )}
      </main>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

页面/_app.js

import { Provider } from 'next-auth/client';
import '../styles.css';

export default ({ Component, pageProps }) => {
  const { session } = pageProps;
  return (
    <Provider options={{ site: process.env.SITE }} session={session}>
      <Component {...pageProps} />
    </Provider>
  );
};
Run Code Online (Sandbox Code Playgroud)

next.config.js

module.exports = {
  env: {
    MONGO_URI: '...',
    SITE: 'http://localhost:3000',
  },
};
Run Code Online (Sandbox Code Playgroud)

小智 4

在您的pages/api/auth/[...nextauth].js文件中,添加:

\n
secret:process.env.SECRET\n
Run Code Online (Sandbox Code Playgroud)\n

SECRET必须是任何字符串值,如下所示:

\n
SECRET:LlKq6ZtYbr+hTC073mAmAh9/h2HwMfsFo4hrfCx6gts=\n
Run Code Online (Sandbox Code Playgroud)\n

另外,将其添加到您的 Vercel 环境中。\nthat\xe2\x80\x99s 它;你的问题将会得到解决。

\n