1: When a user logs in, I generate a refresh token and create a cookie using 'cookie-parser'. This cookie is then sent to the path '/user/refresh-token'
res.cookie('refreshtoken', refreshtoken, {
httpOnly: true,
path: '/user/refresh-token',
maxAge: 1000 * 60 * 60 * 24 * 7,
});
2: However, when I try to fetch the cookie from the path 'user/refresh-token', I am always getting error 400 indicating that the cookie cannot be read. Strangely, when testing the API on Postman, I can see the cookie without any issues. It seems like there's a problem fetching this specific API route on the client side after logging in.
refreshToken: async (req, res) => {
try {
const refreshtoken = req.cookies.refreshtoken;
if (!refreshtoken) {
return res
.status(400)
.json({ msg: "not authenticated, signup or login" });
}
3: The client-side code utilizes createContext as shown below:
export const DataProvider = ({children}) => {
const [token, setToken] = useState(false)
useEffect(()=> {
const firstLogin = localStorage.getItem('firstLogin')
if(firstLogin){
const refreshToken = async ()=>{
const res = await fetch('http://localhost:8000/user/refresh-token')
await res.json();
}
refreshToken()
}
}, [])
5: To summarize, when a user logs in, a cookie is generated and stored at '/user/refresh-token' path. An item named 'firstLogin' is created and saved in local storage to indicate that the user is logged in. The page then redirects to '/' using 'window.location.href', followed by the context function attempting to fetch the API where the cookie exists. However, this results in an error 400 due to no cookies being sent.