Vedant Mule
Vedant Mule

Reputation: 1

In MERN Chatting app, My backend running well, browser getting jwt. But while calling AllUsers, not getting token from JWT

while calling allUsers from database, in backend I am getting it. But, in frontEnd I am not getting hte token through JWT even though it is showing in JWT, localStorage in applications and Network response in browser.

Also I already checked the cors.Because, backend running on 5002, frontend on 3001, I implemented cors in it, used socketIO, added the => httpOnly: true, // xss attacks se bachayega // secure: process.env.NODE_ENV === "production", secure: true, // path: "/", sameSite: "Strict",

in the josnwebtoken file. The error coming while fetching all users to show in UI. Please check the image, and suggest your answers. I am stuck in it. Help me out.

Thank you, Vedant Mule

  1. code in secureRoute ->
import jwt from "jsonwebtoken";
   import User from "../models/user.models.js";

   const secureRoute = async (req, res, next) => {
   try {
    const token = req.cookies.jwt;
    console.log("token in secureRoute: ", token);
    if (!token) {
      return res.status(401).json({ error: "No token, authorization denied" });
    }
    const decoded = jwt.verify(token, process.env.JWT_TOKEN);
    if (!decoded) {
      return res.status(401).json({ error: "Invalid Token" });
    }
    const user = await User.findById(decoded.userId).select("-password"); // current loggedIn user
    if (!user) {
      return res.status(401).json({ error: "No user found" });
    }
    req.user = user;
    next();
    } catch (error) {
    console.log("Error in secureRoute: ", error);
    res.status(500).json({ error: "Internal server error" });
    }
   };
   export default secureRoute;
  1. code in useGetAllUsers ->
import React, { useEffect, useState } from "react";
   import Cookies from "js-cookie";
   import axios from "axios";

   axios.defaults.withCredentials = true;

   function useGetAllUsers() {
    const [allUsers, setAllUsers] = useState([]);
    const [loading, setLoading] = useState(false);
    useEffect(() => {
      const getUsers = async () => {
        setLoading(true);
        try {
          const token = Cookies.get("jwt");
          console.log("Token: ", token);
          const response = await axios.get("/api/user/allusers", {
          withCredentials: true,
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        setAllUsers(response.data);
        setLoading(false);
         } catch (error) {
          console.log("Error in useGetAllUsers: " + error);
        }
       };
       getUsers();
     }, []);
     return [allUsers, loading];
    }

    export default useGetAllUsers;
  1. My generateToken file ->
const createTokenAndSaveCookie = (userId, res) => {
    const token = jwt.sign({ userId }, process.env.JWT_TOKEN, {
      expiresIn: "100d",
     });
    console.log("Token from jwt file: ", token);
    res.cookie("jwt", token, {
      httpOnly: true, // xss attacks se bachayega
      // secure: process.env.NODE_ENV === "production",
      secure: true,
      // path: "/",
       sameSite: "Strict", // csrf attacks se bachayega   // use it only locally
     // sameSite: "Lax",          /// use it locally
      // sameSite: "None", // All users will not come
     });
    };
    export default createTokenAndSaveCookie;
  1. my AuthProvider =>
export const AuthProvider = ({ children }) => {
     const initialUserState =
     Cookies.get("jwt") || localStorage.getItem("ChatApp");
     // parse the user data and storing in state.
     const [authUser, setAuthUser] = useState(
     initialUserState ? JSON.parse(initialUserState) : undefined
     );

     const [loading, setLoading] = useState(true);

     useEffect(() => {
     if (initialUserState) {
       setAuthUser(JSON.parse(initialUserState));
      }
     setLoading(false); // Set loading to false once authUser is initialized
     }, []);

     return (
    <AuthContext.Provider value={{ authUser, setAuthUser }}>
      {children}
    </AuthContext.Provider>
    );
    };
    export const useAuth = () => useContext(AuthContext);

This is coming in my browser and in backend, token is coming.

image 1 image 2

Upvotes: 0

Views: 19

Answers (0)

Related Questions