I am making a Next.js app with Next-auth.js authentication. The app is deployed on vercel. When I tried to open my app, it shows error in console. Here is the list of errors:
Failed to load resource: the server responded with a status of 500 ()
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error There is a problem with the server configuration. Check the server logs for more information.
/api/auth/_log:1 Failed to load resource: the server responded with a status of 500 ()
it could be that you forgot 'secret' option in your [...nextauth].js. It seems to be mandatory since v4 in Prod.
https://next-auth.js.org/getting-started/upgrade-v4#missing-secret
I recently migrated some projects to NextAuth v4.14
import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
import GoogleProvider from "next-auth/providers/google";
export const authOptions = {
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
})
// ...add more providers here
],
secret: process.env.SECRET
}
export default NextAuth(authOptions)
Related
I want add signin features using 'GoogleProvider' in next-auth.
I finished google cloud and firebase settings
OAuth 2.0 client ID in Credentials
App domain, Authorized domains in OAuth consent screen
create web app in firebase project settings
and [...nextauth].ts code is below:
import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import KakaoProvider from "next-auth/providers/kakao"
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { db } from "../../../firebase.config";
const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID_DEV as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET_DEV as string
})
],
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: "jwt",
maxAge: 3 * 60 * 60
},
adapter: FirestoreAdapter(db.app.options),
pages: {
signIn: '/login'
},
callbacks: {
async session({ session, user, token }) {
return session;
}
},
debug: true
}
export default NextAuth(authOptions);
This project is deploying with Github Actions, Cloud Run, Firebase Hosting.
It works very well in local but not works in production.
Interestingly, It works well in Cloud Run project service URL.
Only not works in domain web page that used Firebase Hosting.
so, I tried these
change Authorized redirect URIs in OAuth 2.0 client ID
Edit app registration in OAuth consent screen
callbackUrl property in signIn function
Is this problem caused by Firebase Hosting?
How can I solve this problem?
Thanks.
+add
When I was looking log in Cloud Run, I found these logs:
https://next-auth.js.org/errors#oauth_callback_error checks.state argument is missing.
error: TypeError: checks.state argument is missing.
name: 'OAuthCallbackError'
I have set up next-auth with the GoogleProvider.
Everything works fine locally, however in production, I am having aOAuthCreateAccount error: api/auth/signin?error=OAuthCreateAccount
stating "Try signing in with a different account."
I have provided the ID & Secret of the Provider, I have dropped my DB, tried to log with multiples accounts... I do not understand. Is there something that my production environment is not accessing?
Here's my nextauth.js:
`
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import { MongoDBAdapter } from "#next-auth/mongodb-adapter";
import clientPromise from "../../../lib/mongodb";
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
// ...add more providers here
],
secret: process.env.NEXTAUTH_SECRET,
// Can custom page & path
pages: {
signOut: "/auth/signout",
error: "/auth/error", // Error code passed in query string as ?error=
verifyRequest: "/auth/verify-request", // (used for check email message)
// newUser: "/auth/new-user", // New users will be directed here on first sign in (leave the property out if not of interest)
newUser: "/recruiter/2", // New users will be directed here on first sign in (leave the property out if not of interest)
},
adapter: MongoDBAdapter(clientPromise),
});
`
And my mongodb.js:
`
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
};
let client;
let clientPromise;
if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local");
}
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;
`
Thank you!
Read the documentations.
Look on Stackoverflow and github thread, tried all the offered solutions, in vain.
I have managed to fix it reading this thorough article: https://medium.com/geekculture/why-and-how-to-get-started-with-next-auth-61740558b45b
I was missing the database variable in my deployment system (vercel) :)
I am working on a React Native / Meteor combo, Where Meteor is my server. I need to set up a Firebase admin instance to send an API request for triggering push notifications for my React Native app.
I have installed the Firebase NPM SDK, when I go to import and/or require the firebase.admin object instance is empty or incomplete. Works fine if I load it into a normal node app setup.
I am assuming there is a latency with the import/require. I looked at some wrapper packages but they are outdated and unmaintained.
import * as admin from 'firebase-admin'
console.log(admin)
Should print
FirebaseNamespace {
__esModule: true,
credential:
{ cert: [Function: cert],
refreshToken: [Function: refreshToken],
applicationDefault: [Function: applicationDefault] },
SDK_VERSION: '6.2.0',
Promise: [Function: Promise],
INTERNAL:
FirebaseNamespaceInternals {
firebase_: [Circular],
serviceFactories: {},
apps_: {},
appHooks_: {} },
default: [Circular] }
But instead prints
{ default: {}, [Symbol(__esModule)]: true }
I was studying how to use Apollo GraphQL server with Firebase functions and I found this link, which uses Apollo Server 1. I'm trying to use Apollo Server 2, but it doesn't have
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
that the author used in the article.
I've tried to implement in this way:
import { https } from "firebase-functions"
import { ApolloServer, gql } from 'apollo-server-express';
import * as express from 'express';
const app = express();
const graphQLServer = new ApolloServer({ typeDefs, resolvers });
graphQLServer.applyMiddleware({ app });
export const api = https.onRequest(app);
with "apollo-server-express": "^2.0.0" but without success, because I always get Cannot GET / every time I follow function link.
So, is there a way to implement Apollo Server 2 with Firebase/Google Functions?
It works when I add path: '/' to applyMiddleware
graphQLServer.applyMiddleware({ app, path: '/' });
I consume this function when deployed with endpoint // https://us-central1-<project-name>.cloudfunctions.net/api. Playground works fine here.
At localhost, by http://localhost:5000/<project-name>/us-central1/api. Playground doesn't work here until I change URL beside History button to http://localhost:5000/<project-name>/us-central1/api/
I'm using meteor and trying to make Apollo Subscriptions to work, but I'm getting
WebSocket connection to 'ws://127.0.0.1:3000/sockjs/401/m892wugm/websocket' failed: Connection closed before receiving a handshake response in the client.
I followed apollographql.com guide for Server Configuration and Client Configuration but I'm not quite sure how to connection the client to the server yet.
In the client, I'm using ApolloClient and ApolloLink to pass the Meteor auth to GraphQL.
Here's the code:
Client
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
const httpLink = new createHttpLink()
const authLink = new ApolloLink((operation, forward) => {
operation.setContext(() => ({
headers: { 'meteor-login-token': Accounts._storedLoginToken() },
}))
return forward(operation)
})
export default ApolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
})
Server
createApolloServer({
schema,
tracing: true,
cacheControl: true,
})
new SubscriptionServer({
schema,
execute,
subscribe,
}, {
server: WebApp.httpServer,
path: '/subscriptions',
})
Package.json (not everything, of course)
Meteor 1.6.1.1
...
"apollo-client": "^2.2.5",
"apollo-link": "^1.2.1",
"apollo-link-context": "^1.0.7",
"apollo-link-http": "^1.5.3",
"apollo-link-ws": "^1.0.8",
"subscriptions-transport-ws": "^0.9.9",
...
I read somewhere that passing noServer: true to the SubscriptionServer() resolve the conflict. The error indeed goes away, but the subscription doesnt seem to work either.
And yes, I have followed the Meteor Integration guide from apollographql, but the info there is outdated and does not work.