Next auth cookie loading issue.
Unanswered
Rohit | Lucifer posted this in #help-forum
I have a backend on which I receive the
Below is the auth api route
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { getCookie, setCookie } from "@/util/cookie-helper";
import { AuthService } from "@/service";
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.AUTH_GOOGLE_ID as string,
clientSecret: process.env.AUTH_GOOGLE_SECRET as string,
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async signIn({ account }) {
if (account?.access_token) {
try {
const { data } = await AuthService.loginWithGoogle(
account.access_token
);
if (data){
await setCookie("token", data.access_token, "/", 432000);
return true;
} else {
return false;
}
} catch (error) {
console.error(error);
return false;
}
}
return true;
},
async session({ session }) {
session.token = await getCookie("token")
return session;
},
},
pages: {
signIn: "/auth/signin",
error: "/auth/error",
},
});
export { handler as GET, handler as POST };
google_access_token
from the frontend in order to store the user info and I return a new token generated by the backend to the user and I store it in the cookies. But the issue is that as soon as the callbackURL is hit, I get navigated to the home page and there is a middleware which checks if the user has a valid token or not? And everytime I get back to the auth screen instead of home because the middleware is not able to find the token, but if I refresh the page and then visit the home page, I can stay there as the middleware can now access the token. What can I do, please help? Below is the auth api route
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { getCookie, setCookie } from "@/util/cookie-helper";
import { AuthService } from "@/service";
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.AUTH_GOOGLE_ID as string,
clientSecret: process.env.AUTH_GOOGLE_SECRET as string,
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async signIn({ account }) {
if (account?.access_token) {
try {
const { data } = await AuthService.loginWithGoogle(
account.access_token
);
if (data){
await setCookie("token", data.access_token, "/", 432000);
return true;
} else {
return false;
}
} catch (error) {
console.error(error);
return false;
}
}
return true;
},
async session({ session }) {
session.token = await getCookie("token")
return session;
},
},
pages: {
signIn: "/auth/signin",
error: "/auth/error",
},
});
export { handler as GET, handler as POST };
1 Reply
Anyone guys?