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>
)
}
}