The below code is code from [...nextauth].js . The Goal is to achieve is to send POST request to save data and to set a session token with the returned result when using google-authentication.
To explain the code written: I am using next-auth's credential and google providers. In the Credential provider I am making a POST request to check for the user in the database hosted on localhost:8080. The credentials passed as parameters include email and password.
For Google Provider, I have kept the code default from the doc.
callbacks are there to save tokens.
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
export default NextAuth({
// Configure one or more authentication providers
providers: [
CredentialsProvider({
async authorize(credentials){
//check if crenditials.email is present in database
const res =await fetch('http://localhost:8080/user/login?deviceToken=eEiLMMkzR1ypiCwp068z97:APA91bEiBpfwCmpZ5-ijVU4FKcl-4d0QkuWrBtXgcZRJF06MUw8GJvcBn_4ci-v1IFOD8wMF0bNqEheFq0LR0Vz5hXIktT-7sMwOfR52ULhy14NgjiUUW_0nNs5gBXAZHwhtifJluS7v', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
})
const x=await res.json();
// console.log(x);
const user={email:x.user.email,name:`${x.user.firstName} ${x.user.lastName}`};
if(res.ok && user){
console.log("logged In");
return user;
}
console.log("error1");
return null;
}}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code"
}
}
}),
],
jwt: {
encryption:true,
},
callbacks:{
async jwt(token,account)
{
console.log(account);
if(account){
token.accessToken = account.accessToken;
}
return token;
},
}
})