Automatically getting session token
Answered
Rex posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
RexOP
I am using Next Auth with Next Js to add authentication in my app. In order to protect routes I am using middleware to check if the user is authenticated or not and depending on that I redirect user to diffrent page.
For now I am using credential and google provider for registering
I am also storing users in the mongodb and using mongoose as ORM
Here I the issue I am facing
I manually clear the cookies by going in the developer tools> appliaction then I go the
To double check I refresh the
For now I am using credential and google provider for registering
I am also storing users in the mongodb and using mongoose as ORM
Here I the issue I am facing
I manually clear the cookies by going in the developer tools> appliaction then I go the
/
and I am redirected to the /signin
page as expetecd but now if I check my cookie now it show cookie even tho I haven't signedin. To double check I refresh the
/register
page and redirected to the /
as expected since I have cookies but the issue is I (user) never signed in13 Replies
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
RexOP
middleware.js
please guide me what is the issue
export function middleware(req) {
let token;
if (req.cookies.get("next-auth.csrf-token")) {
token = req.cookies.get("next-auth.csrf-token").value;
}
if (
(req.nextUrl.pathname.startsWith("/signin") ||
req.nextUrl.pathname.startsWith("/register")) &&
token
) {
return NextResponse.redirect(new URL("/", req.nextUrl));
}
const path = req.nextUrl.pathname;
const isPublicPath = path === "/signin" || path === "/register";
if (!isPublicPath && !token) {
return NextResponse.redirect(new URL("/signin", req.nextUrl));
}
}
export const config = {
matcher: ["/register", "/signin", "/", "/events", "/register/:path*"],
};
please guide me what is the issue
api/auth/[...nextauth]/route.js
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
CredentialsProvider({
name: "Credentials",
credentials: {},
async authorize(credentials) {
const { email, password } = credentials;
if (!email || !password)
NextResponse.json(
{ error: "both email and password required" },
{ status: 400 }
);
await startDb();
const existingUser = await User.findOne({ email });
console.log("user present");
if (existingUser == null) {
throw new Error("email not present");
}
const isPasswordCorrect = await bcrypt.compare(
credentials.password,
existingUser?.password
);
if (!isPasswordCorrect)
// NextResponse.json({ error: "wrong password" }, { status: 400 });
throw new Error("wrong password");
if (existingUser) {
console.log("returning user,", existingUser);
return existingUser;
} else {
return null;
}
},
}),
],
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/signin",
},
// callback goes here
});
export { handler as GET, handler as POST };
callbacks: {
async signIn({ user, account }) {
console.log("PROVIDER: ", account.provider);
if (account.provider == "google") {
try {
const { email } = user;
await startDb();
const checkUser = await User.findOne({ email });
const newUser = new User({
email,
});
const res = await newUser.save();
return user;
} catch (error) {
console.log("ERROR: ", error);
}
} else if (account.provider == "Credentials") {
return user;
}
},
async redirect({ url, baseUrl }) {
console.log(" url, baseUrl: ", url, baseUrl);
return baseUrl;
},
async session({ session, token }) {
session.user = token.user;
return session;
},
async jwt({ token, user }) {
if (user) {
token.user = user;
}
return token;
},
},
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
RexOP
still struggling with this and haven't be able to make any progress
![Avatar](https://cdn.discordapp.com/avatars/809942393637306400/1e4e5a29a08b96de9a1e3d3520b5e771.webp?size=256)
tafutada777
make sure that you do not have multiple Google accounts log in Chrome browser itself. plus try other browser(non chromium) like Safari
plus, check the network tab > http response header > set-cookie does not exist
plus, check the network tab > http response header > set-cookie does not exist
enable 'preserve log'
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
RexOP
tried in firefox and still facing the issue
![Avatar](https://cdn.discordapp.com/avatars/809942393637306400/1e4e5a29a08b96de9a1e3d3520b5e771.webp?size=256)
tafutada777
check http headers form network tab
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
RexOP
![Image](https://cdn.discordapp.com/attachments/1150965012232425503/1151046940046397501/Screenshot_from_2023-09-12_11-48-45.png)
I have enabled the xhr request in firefox hence this request in the console
![Image](https://cdn.discordapp.com/attachments/1150965012232425503/1151047408218800158/Screenshot_from_2023-09-12_11-50-35.png)
response header set-cookie is not empty
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
RexOP
Fixed thsi issue. I was supoed to check th session.token
Answer