我正在尝试使用 next-auth 在 nextjs 中添加“使用 google 登录”选项,这是我的 [...nextauth].js 文件,位于 api/auth 文件夹中:
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
secret: process.env.JWT_SECRET,
});
这是我的应用程序文件,我也在其中使用 i18n 进行翻译:
import i18next from "i18next";
import { I18nextProvider } from "react-i18next";
import Backend from "i18next-xhr-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
import { SessionProvider } from "next-auth/react";
export default function App({ Component, pageProps, session }) {
return (
<SessionProvider session={session}>
<I18nextProvider i18n={i18next}>
<Component {...pageProps} />
</I18nextProvider>
</SessionProvider>
);
}
但是我在登录时不断收到此错误:
message: 'client_id is required'
这是完整的错误:
[next-auth][error][SIGNIN_OAUTH_ERROR]
https://next-auth.js.org/errors#signin_oauth_error client_id is required {
error: {
message: 'client_id is required',
stack: 'TypeError: client_id is required\n' +
' at new BaseClient (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/openid-client/lib/client.js:185:13)\n' +
' at new Client (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/openid-client/lib/client.js:1841:7)\n' +
' at openidClient (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/next-auth/core/lib/oauth/client.js:29:18)\n' +
' at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n' +
' at async getAuthorizationUrl (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/next-auth/core/lib/oauth/authorization-url.js:70:18)\n' +
' at async Object.signin (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/next-auth/core/routes/signin.js:38:24)\n' +
' at async AuthHandler (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/next-auth/core/index.js:260:26)\n' +
' at async NextAuthApiHandler (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/next-auth/next/index.js:22:19)\n' +
' at async NextAuth._args$ (/Users/moeezramay/Desktop/job/moeezMatch/mosquematch/node_modules/next-auth/next/index.js:108:14)',
name: 'TypeError'
},
providerId: 'google',
message: 'client_id is required'
}
在 Next.js 9.4 及更高版本中,您可以在 .env 文件中使用 NEXT_PUBLIC_ 前缀使环境变量可供浏览器使用。这些变量将在构建时替换为其实际值,因此可以从客户端代码访问它们,就像它们是硬编码一样。例如,您可以使用
process.env.NEXT_PUBLIC_API_KEY
访问您设置的名为 API_KEY
的环境变量。
请记住,使用此方法会将您的环境变量公开给客户端,因此您应该小心选择以这种方式提供哪些变量。您应该仅对可从客户端安全访问的变量(例如公开可用的 API 密钥)使用此方法。
非 NEXT_PUBLIC_ 环境变量仅在 Node.js 环境中可用,这意味着浏览器无法访问它们(客户端在不同的环境中运行)。