0

I'm designing an application with Next.js and using NextAuth for authentication(using Google OAuth). In order to use other Google APIs once authenticated, I want to persist the accessToken. The accessToken gets set in the session() callback. However, it seems like the callback never runs. Could someone help me out with this? Thanks!

Here's my [...nextauth].js file

import GoogleProvider from "next-auth/providers/google"
import NextAuth from "next-auth/next"
export default NextAuth(
  {
    // Configure one or more authentication providers
    providers: [
      GoogleProvider({
        clientId: PROCESS.ENV.GOOGLE_CLIENT_ID',
        clientSecret: PROCESS.ENV.GOOGLE_CLIENT_SECRET,
        authorization: {
          params: {
            prompt: "consent",
            access_type: "offline",
            response_type: "code",
            scope: 'openid email profile https://www.googleapis.com/auth/calendar'
          },
        },
        callbacks: {
          async session({ session, token, user }) {
            session.user.id = token.id;
            session.accessToken = token.accessToken;
            // Not printed
            console.log('In here');
            return session;
          },
          async jwt({ token, user, account, profile, isNewUser }) {
            console.log(token);
            if (user) {
              token.id = user.id;
            }
            if (account) {
              token.accessToken = account?.access_token;
            }
            return token;
          },
        },
      }),
      // ...add more providers here
    ],
    sercet: PROCESS.ENV.JWT_SECRET,
    session: {
      strategy: "jwt",
    },
  }
)

Here's my login component:

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

const Login = () => {
    const x = useSession();
    const {data: session} = x
    const [calendar, setCalendar] = useState({});

    const getCalendarData = async () => {
        console.log(session.accessToken);
        console.log(x);
        const options = {  
            method: 'GET',
            headers: {
                Authorization: `Bearer ${session.accessToken}`,
            }
        };

        const url = "https://www.googleapis.com/calendar/v3/calendars/primary";
        
        const data = null
        try{
            data = await axios.get(url, options);
            setCalendar(data);
        } catch(error){
            console.log(error);
        }
        
    }

    if(session){
        return (
            <div>
                <div> Welcome, {JSON.stringify(session.user)} </div>
                <div>{JSON.stringify(calendar)}</div>
                <div><button onClick={() => signOut()}>Sign Out</button></div>
                <div><button onClick={async () => await getCalendarData()}>Get Calendar Data</button></div>
            </div>
        
        );
    }
    else{

        return(
            <div>
                <div> You are not signed in </div>
                <div><button onClick={() =>signIn()}> Sign in</button></div>
            </div>
            )
    }
}

  • `callbacks` is an option of the top level next-auth object, it should not be nested inside a provider's configuration. Move `callbacks` to the same level as `providers`, `secret` and `session`. Also, you have a typo in `sercet`. – juliomalves Oct 16 '22 at 23:07

1 Answers1

0

If the problem is still not resolved, I have a suggestion. I'm writing because I couldn't find the solution anywhere on the internet. Hopefully, it will be helpful: the error could be related to MongoDB or the database you are using. In MongoDB, go to the database you created and click on 'Add Current IP Address.' Then close and reopen your Next.js project. This should fix the problem. MongoDB saves the last added IP address as a trusted address. So, when your IP address changes, it doesn't allow access to the server, and you need to add the current IP address to the database.