I’m developing a MERN chat application and I can’t fetch all the avaliable users in the frontend.
Read before answering:
- To fetch all avaliable users, you must login.
- Authentication uses JWT and the JWT Token is stored in the cookies tab in the browser
- Login in the frontend is done using RTK Query
Here’s the code:
JWT method:
UserSchema.methods.getJwtToken = function(){
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_TIME
});
}
JWT Creation:
export default (user, statusCode, res) =>{
const token = user.getJwtToken(); // Create JWT Token
const options ={
expires: new Date(Date.now() + process.env.COOKIE_EXPIRATION_TIME * 24 * 60 * 60 * 1000)
}
res.status(statusCode)
.cookie("token", token, options)
.json({ user, token });
}
User Authentication (Backend):
import asyncHandler from "express-async-handler";
import jwt from "jsonwebtoken";
import User from "path/to/userModel";
import ErrorHandler from "path/to/errorHandler";
export const isAuthenticatedUser = asyncHandler(async (req, res, next) =>{
const { token } = req.cookies
if(!token){
return next(new ErrorHandler("Login to gain access to this resource", 401));
}
const decoded = jwt.verify(token, process.env.JWT_SECRET); // Verify the user's token
req.user = await User.findById(decoded.id);
next();
});
`
Fetching Users (Frontend):
// Imports
const Users = () =>{
const [users, setUsers] = useState([]);
const { refresh, setRefresh } = useContext(chatContext);
const dispatch = useDispatch();
const theme = useSelector((state) => state.theme);
const { user } = useSelector((state) => state.user);
useEffect(() =>{
console.log("Users Refreshed");
const config ={
headers: { Authorization: `Bearer ${user?.data?.token}` },
};
console.log(config)
axios.get("http://localhost:5001/api/v1/fetchusers", config).then((data) => {
console.log("User Data Refreshed");
setUsers(data);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refresh]);
const iconHandler = (e) =>{
e.preventDefault();
}
return(
<>
<MetaData title={"Users"}/>
<div className="list-container d-flex flex-column">
<div className={`usersgroups-header d-flex align-items-center bg-light ${theme ? "" : "dark"}`}>
<img src={user?.picture?.url} alt={user?.name} style={{ height: "2rem", width: "2rem", borderRadius: "20px" }}/>
<p className="usersgroups-title fw-bolder mt-3">Online Users</p>
<Button className="border-0 bg-transparent" style={{ color: "black" }}
onClick={() =>{ setRefresh(!refresh); }}>
<MdOutlineRefresh onClick={iconHandler} className={`icon ${theme ? "" : "dark"}`}/>
</Button>
</div>
<div className={`sb-search d-flex align-items-center bg-light ${theme ? "" : "dark"}`}>
<BsSearch onClick={iconHandler} className={`icon mx-1 my-2 ${theme ? "" : "dark"}`}/>
<input type="search" placeholder="Search" className={`search-box border-0 w-100 ${theme ? "" : "dark"}`}/>
</div>
<div className="usersgroups-list flex-fill overflow-scroll">
{users.map((user, index) =>{
return(
<motion.div
className={`d-flex align-items-center ${theme ? "list-tem" : "dark-list-tem"}`}
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
key={index}
onClick={() =>{
console.log("Creating chat with ", user.name);
const config ={
headers: {Authorization: `Bearer ${user.data.token}` },
};
axios.post("http://localhost:5001/api/v1/chat/",{
userID: user._id
},config);
dispatch(refreshSidebarFun())}}>
<p className=
{`con-icon d-flex justify-content-center align-items-center bg-${theme ? "dark" : "light"} text-${theme ? "light" : "dark"} mt-3`}>T</p>
<p className={`con-title fw-bold mt-3 text-${theme ? "dark" : "light"}`}>Test User</p>
</motion.div>
)
})}
</div>
</div>
</>
)
}
export default Users;
Your help will be appreciated

