I've set up Next-Auth on my NextJS project to use FaunaDB. I've managed to get it working on my production environment, however, it seems to not be working on my development environment, which is using the Fauna Dev docker container rather than the cloud-based database.
Whenever I run the dev server, I get the following error log;
https://next-auth.js.org/errors#fauna__get_session_error [NotFound: instance not found] {
description: 'Set not found.',
requestResult: RequestResult {
method: 'POST',
path: '',
query: null,
requestRaw: '{"get":{"match":{"index":"session_by_token"},"terms":"86b962d600c3f53d41d5140de6daed654a473e670a99943d7fb301a4fc86357e"}}',
requestContent: Expr { raw: [Object] },
responseRaw: '{"errors":[{"position":[],"code":"instance not found","description":"Set not found."}]}',
responseContent: { errors: [Array] },
statusCode: 404,
responseHeaders: [Object: null prototype] {
':status': 404,
'x-txn-time': '1630008523944000',
'x-compute-ops': '1',
'x-read-ops': '0',
'x-byte-read-ops': '0',
'x-byte-write-ops': '0',
'x-write-ops': '0',
'x-query-time': '703',
'x-query-bytes-in': '121',
'x-query-bytes-out': '87',
'x-storage-bytes-read': '0',
'x-storage-bytes-write': '0',
'x-txn-retries': '0',
'x-faunadb-build': '21.08.00-4d315fa',
'content-length': '87',
'content-type': 'application/json;charset=utf-8'
},
startTime: 1630008521471,
endTime: 1630008522280
}
}
I've followed the guide to set this up and continue to get the same error. I've removed and recreated the fauna docker container several times, still the same error. I also have some data that I can access in the local Fauna Dev database, so that seems to be set up fine. Also if I change my .env.local environment variables to the ones I use on production, it all works fine, but of course is then using the cloud database.
Here's a comparison of my production and local variables, with private keys removed;
# .env.local
GOOGLE_ID=<removed>
GOOGLE_SECRET=<removed>
NEXT_PUBLIC_FAUNA_ADMIN_KEY=<removed>
NEXT_PUBLIC_FAUNA_DOMAIN=localhost
NEXT_PUBLIC_FAUNA_GRAPHQL_ENDPOINT=http://localhost:8084/graphql
NEXT_PUBLIC_FAUNA_PORT=8443
NEXT_PUBLIC_FAUNA_SCHEME=http
NEXTAUTH_URL=http://localhost:3000
# production env
GOOGLE_ID=<removed, identical to local>
GOOGLE_SECRET=<removed, identical to local>
NEXT_PUBLIC_FAUNA_ADMIN_KEY=<removed, different to local>
NEXT_PUBLIC_FAUNA_DOMAIN=db.eu.fauna.com
NEXT_PUBLIC_FAUNA_GRAPHQL_ENDPOINT=https://graphql.eu.fauna.com/graphql
NEXT_PUBLIC_FAUNA_SCHEME=https
NEXTAUTH_URL=https://dnd-compendium-five.vercel.app
And for good measure, here's my [...nextauth].ts file;
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import * as Fauna from "faunadb";
import { FaunaAdapter } from "#next-auth/fauna-adapter";
const isProduction = process.env.NODE_ENV === "production";
const client = new Fauna.Client({
secret: process.env.NEXT_PUBLIC_FAUNA_ADMIN_KEY,
scheme: process.env.NEXT_PUBLIC_FAUNA_SCHEME === "https" ? "https" : "http",
domain: process.env.NEXT_PUBLIC_FAUNA_DOMAIN,
...(isProduction ? {} : { port: +process.env.NEXT_PUBLIC_FAUNA_PORT }),
});
export default NextAuth({
// Configure one or more authentication providers
providers: [
Providers.Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
// ...add more providers here
],
adapter: FaunaAdapter({ faunaClient: client }),
});
Update
Here's several documents from the production Fauna database, with personal info removed;
# accounts collection document
{
"ref": Ref(Collection("accounts"), "307944413618766018"),
"ts": 1629937528150000,
"data": {
"userId": "307944413481402562",
"providerId": "google",
"providerType": "oauth",
"providerAccountId": "110736403335097897627",
"accessToken": "ya29.a0ARrdaM_n4D6gDvzs8Mxs851r70Xs5v5HROSdcDM0HJoMP1XFhAPhFbmh46e4bfHzTbVYOhoc2W7N_0IHpV3yEW5a__Nzy8NrxWU3ns-KlxIm_oTXRVW0RyitT26uXtTq-45k6OTjakjHsinYpnof4qdXcICg",
"createdAt": Time("2021-08-26T00:25:28.101705Z"),
"updatedAt": Time("2021-08-26T00:25:28.101705Z")
}
}
# sessions collection document
{
"ref": Ref(Collection("sessions"), "308011284890124486"),
"ts": 1630001301580000,
"data": {
"userId": "307946306265940166",
"expires": Time("2021-09-25T18:08:21.521Z"),
"sessionToken": "997b45bb432cfbc05901e9a92ae9d1ac36637246277ac05ad915fb00b8fc9130",
"accessToken": "9dbec0113a46bc6a0768e1a5b7baafac65a1fb0a29568bc11562cd58ad97d5b9",
"createdAt": Time("2021-08-26T18:08:21.517447Z"),
"updatedAt": Time("2021-08-26T18:08:21.517447Z")
}
}
# users collection document
{
"ref": Ref(Collection("users"), "307946306265940166"),
"ts": 1629939333135000,
"data": {
"name": <string removed>,
"email": <string removed>,
"image": <url string removed>,
"createdAt": Time("2021-08-26T00:55:33.075553Z"),
"updatedAt": Time("2021-08-26T00:55:33.075553Z")
}
}
Which verisons of next-auth and the adapter are you using? They recently released a v4 beta and matching adapter beta's. Maybe you'll have more luck with those newer releases 👍
Related
I reviewed everything, my client ID/Secret and everything is fine in my environment variables, when I click to sign in with google in localhost it works perfectly but in vercel it throws this error
[GET] /api/auth/error?error=OAuthSignin
Here is my [...nextauth].js code
import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";
import FacebookProvider from "next-auth/providers/facebook";
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,
authorization: {
params: {
redirect_uri: "https://theracakecairo.com/api/auth/callback/google",
prompt: "consent",
scope: "email",
},
},
}),
FacebookProvider({
clientId: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
authorization: {
params: {
redirect_uri: "https://theracakecairo.com/api/auth/callback/facebook",
prompt: "consent",
// access_type: "offline",
scope: "email",
response_type: "code",
},
},
}),
],
debug: true,
secret: process.env.NEXTAUTH_SECRET,
adapter: MongoDBAdapter(clientPromise),
callbacks: {
async session({ session, token, user }) {
session.user._id = user.id;
return session;
},
},
// session: {
// strategy: "database",
// maxAge: 30 * 24 * 60 * 60
// }
});
https://next-auth.js.org/errors
Walked through the 3 possible error causes and still nothing works
Update:
This issue has been corrected by the Vercel team. Please redeploy your application.
https://github.com/nextauthjs/next-auth/issues/6688#issuecomment-1426614069
The issue is being discussed on GitHub:
https://github.com/nextauthjs/next-auth/issues/6688
https://github.com/nextauthjs/next-auth/issues/6685
Some users say that migrating to Netlify has solved their issues.
https://github.com/nextauthjs/next-auth/issues/6685#issuecomment-1426535665
I am using RTK-Query, and Redux-toolkit for this app, and I created an api-slice with createApi, as per the docs.
When I run a request to the backend, I get a "FETCH_ERROR"; however, when I run the same request using Axios, I get the data correctly from the backend, which leads me to believe I have an error in my code. I am just not sure where exactly it is.
Here is the error:
Object {
"api": Object {
"config": Object {
"focused": true,
"keepUnusedDataFor": 60,
"middlewareRegistered": true,
"online": true,
"reducerPath": "api",
"refetchOnFocus": false,
"refetchOnMountOrArgChange": false,
"refetchOnReconnect": false,
},
"mutations": Object {},
"provided": Object {},
"queries": Object {
"test(undefined)": Object {
"endpointName": "test",
"error": Object {
"error": "TypeError: Network request failed",
"status": "FETCH_ERROR",
},
"requestId": "BWOuLpOxoDKTzlUYFLW4x",
"startedTimeStamp": 1643667104869,
"status": "rejected",
},
},
"subscriptions": Object {
"test(undefined)": Object {
"QJSCV641RznGWyudGWuMb": Object {
"pollingInterval": 0,
"refetchOnFocus": undefined,
"refetchOnReconnect": undefined,
},
},
},
},
"test": Object {
"data": Array [],
},
}
Here is the test slice:
import { createSlice } from "#reduxjs/toolkit";
const testSlice = createSlice({
name: "test",
initialState: {
data: [],
},
reducers: {
getData: (state) => {
state;
},
},
});
export const { getData } = testSlice.actions;
export default testSlice.reducer;
Here is the apiSlice:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
export const apiSice = createApi({
reducerPath: "test",
baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_backend_url }),
endpoints: (builder) => ({
test: builder.query({
query: () => "/test",
}),
}),
});
export const { useTestQuery } = apiSice;
I solved it by changing the backend URL to my current ipv4 (for expo development, otherwise just your whatever your backend URL is) address in my .env file, then deleting cache, and restarting my app. In my case I was using expo so, expo r -c, and it worked.
I am having an issue running a mutation that was generated by the Amplify CLI.
I'm on node v14.18.1, amplify CLI 7.6.2.
I just recently migrated to the GraphQL Transformer v2.
Here is my model:
type User
#model
#auth(
rules: [
{ allow: groups, groups: ["admin"] }
{ allow: owner, ownerField: "id", operations: [read] }
]
) {
id: ID!
first_name: String
last_name: String
email: String!
customer: Customer #hasOne(fields: ["userCustomerId"])
userCustomerId: ID! #index(name: "usersByCreatedAt", queryField: "usersByCreatedAt" sortKeyFields: ["createdAt"])
createdAt: String!
isAdmin: Boolean
}
The mutation I'm calling from within AppSync:
mutation UpdateUser {
updateUser(input: {id: "asdfasdfasdf", isAdmin: true, last_name: "Franklin", first_name: "Tim", email: "tim#tim.com", userCustomerId: "my_customer"}) {
id
}
}
Error:
{
"data": {
"updateUser": null
},
"errors": [
{
"path": [
"updateUser"
],
"data": null,
"errorType": "MappingTemplate",
"errorInfo": null,
"locations": [
{
"line": 2,
"column": 3,
"sourceName": null
}
],
"message": "Unsupported element '$[operation]'."
}
]
}
Has anyone ran into this error, and how did you resolve it?
Thank you!
Check if there are any .vtl files in project_dir/amplify/backend/api/api_name/resolvers. If there are and you're not sure why/don't recognize them, back up and delete those files, deploy your local backend with amplify push, and see if the mutation succeeds.
I was getting the exact same error during a delete mutation and this resolved it for me. The Amplify CLI auto-generates templates for the API service, but overrides them with any it finds in that directory. Just make sure to back up all of those files before deleting them just in case..
Check what "Data Source" your resolver function is connected to. You can see this information in the AppSync web UI for the given resolver function. If the Data Source is not mapped to the correct place or if it's set to NONE_DS, then all of the operations for the given resolver function will fail.
This error happened to me when I accidentally connected the resolver to the RDS datasource instead of the DynamoDB one.
I am building an app with GatsbyJS. I am using environment variables in my gatsby-config.js. GatsbyJS app builds fine locally, by using .env.* files. However, when building from AWS Amplify it complains about an invalid value retrieved from environment variables. Indeed, it seems that when using process.env.MY_VAR inside gatsby-config.js the value retrieved is encrypted (as per AWSAmplify docs).
I tried with hardcoding the value of the env. var to confirm that encryption was the problem.
The error that I am getting is:
TypeError [ERR_INVALID_URL]: Invalid URL: 6fbaeed85a68.
Which clearly indicates that the value retrieved from process.env.HOSTNAME is 6fbaeed85a68 and not the actual value that I provided in AWS Amplify web's interface.
Below is my gatsby-js.config:
const path = require(`path`);
const queries = require('./src/utils/algolia');
const feedOptions = require('./src/utils/feed');
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
});
module.exports = {
siteMetadata: {
siteUrl: new URL(process.env.HOSTNAME).href,
title: `APP_TITLE`,
},
plugins: [
{
resolve: `gatsby-source-kentico-cloud`,
options: {
deliveryClientConfig: {
projectId: process.env.KENTICO_PROJECT_ID,
},
languageCodenames: process.env.KENTICO_LANGUAGES.split(';'),
},
},
{
resolve: `gatsby-plugin-algolia`,
options: {
appId: process.env.GATSBY_ALGOLIA_APP_ID,
apiKey: process.env.ALGOLIA_ADMIN_KEY,
queries,
chunkSize: 10000,
},
},
`gatsby-plugin-react-helmet`,
`gatsby-plugin-sitemap`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `APP_NAME`,
short_name: `APP_SHORT_NAME`,
start_url: `/`,
background_color: `#dbdcd1`,
theme_color: `#1ad2eb`,
display: `standalone`,
icon: `src/images/logo-simple-transp-square-260x260.png`,
include_favicon: true,
},
},
`gatsby-plugin-offline`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-sass`,
options: {
includePaths: ['src/styles/_variables'],
},
},
{
resolve: 'gatsby-plugin-mailchimp',
options: {
endpoint: process.env.MAILCHIMP_ENDPOINT,
},
},
{
resolve: 'gatsby-plugin-transition-link',
options: {
layout: require.resolve(`./src/layout`),
},
},
{
resolve: `gatsby-plugin-feed`,
options: feedOptions,
},
{
resolve: `gatsby-plugin-google-tagmanager`,
options: {
id: process.env.GTM_CODE,
includeInDevelopment: false,
},
},
],
};
I don't understand how I am supposed to retrieve env vars. Any help would be greatly appreciated.
When adding environment variables to AWS Amplify App under App Setting -> Environment Variables, just prefix GATSBY_ to all your environment variable names. Remember to change your code to use the new names.
Adding GATSBY_ makes env variables accessible to browser javascript.
Read more about it in the official documentation.
I am working with the gatsby-source-wordpress plugin
If I hard code my API keys/secret into my Gatsby.config, everything works fine, but I want to add these as .env variables so that I can .gitignore for deployment, and this is where things are breaking.
At the root of my directory, I have a .env file which looks like this
CLIENT_SECRET=10987654321
CLIENT_ID=123456
USER=secret#secret.com
PASS=mypassword1
I'm then try to access these in gatsby.config, like this
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`
});
module.exports = {
siteMetadata: {
title: 'Gatsby Default Starter',
},
plugins: [
{
resolve: 'gatsby-source-wordpress',
options: {
baseUrl: 'myurl.com',
protocol: 'http',
hostingWPCOM: true,
useACF: false,
auth: {
wpcom_app_clientSecret: `${process.env.CLIENT_SECRET}`,
wpcom_app_clientId: `${process.env.CLIENT_ID}`,
wpcom_user: `${process.env.USER}`,
wpcom_pass: `${process.env.PASS}`,
},
},
},
{
resolve: `gatsby-plugin-emotion`,
},
'gatsby-plugin-react-helmet',
{
resolve: `gatsby-plugin-manifest`,
options: {
name: 'gatsby-starter-default',
short_name: 'starter',
start_url: '/',
background_color: '#663399',
theme_color: '#663399',
display: 'minimal-ui',
icon: 'src/images/gatsby-icon.png', // This path is
relative to the root of the site.
},
},
'gatsby-plugin-offline',
],
}
which is returning the following errors when I run either gatsby develop or gatsby build
source and transform nodesThe server response was "400 Bad Request"
source and transform nodesThe server response was "403 Forbidden"
Inner exception message : "User cannot access this private blog."
No routes to fetch. Ending.
So, the issue is the .env variables don't seem to be pulling through properly, but I can't see a reason why they wouldn't be? Is there anything I've missed in setting this up?
Gatsby doesn't know which plugin you mean (see How to use) and your overall syntax is wrong. The plugins is an array for example.
module.exports = {
plugins: [
{
resolve: "gatsby-source-wordpress",
options: {
auth: {
wpcom_app_clientSecret: process.env.CLIENT_SECRET,
wpcom_app_clientId: process.env.CLIENT_ID,
wpcom_user: process.env.USER,
wpcom_pass: process.env.PASS,
}
}
}
]
}
This should work assuming that you also define the other necessary fields mentioned in the README.