Next.js Discord

Discord Forum

Automatically getting session token

Answered
Rex posted this in #help-forum
Open in Discord
Avatar
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 / 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 in
Answered by Rex
Fixed thsi issue. I was supoed to check th session.token
View full answer

13 Replies

Avatar
RexOP
middleware.js
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
RexOP
still struggling with this and haven't be able to make any progress
Avatar
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
enable 'preserve log'
Avatar
RexOP
tried in firefox and still facing the issue
Avatar
check http headers form network tab
Avatar
RexOP
Image
I have enabled the xhr request in firefox hence this request in the console
Image
response header set-cookie is not empty
Avatar
RexOP
Fixed thsi issue. I was supoed to check th session.token
Answer