1

I have a React-App with a Node and Express backend (both are running locally and on different ports) and I'm trying to implement JWT authentication/authorization in my application. I send the accessToken and refreshToken, at the time of login, and store the refreshToken as an httponly cookie. Here is the code used to achieve that at the backend:

        const {accessToken, refreshToken} = await user.generateAuthToken()
        res.cookie('jwt', refreshToken, {httpOnly: true,maxAge: 24*60*60*1000})
        res.json({accessToken,user})

This is pretty straightforward and this flow works on postman by the way. Postman receives the refreshToken and stores it as an httpCookie thus allowing me to refresh a Token whenever my access Token expires. However, I've been trying to achieve the same thing on React frontend for days but am unable to do so. Now I understand that Cross Origin requests are not allowed to set cookies but I'm actually doing the following using Cors:

app.use(cors({
    credentials: true,
    allowedHeaders: ['Content-Type', 'Authorization'],
    origin: ['http://localhost:3000', 'http://localhost:5000']
}));

On the frontend, this is how I make the login request:

const loginUser = await axios.post('/users/login',body,{withCredentials: true})

As far as I understand, this should work and I know that refresh token is received as a cookie when I login (by observing the network tab in the developer tools) so the problem is that it is not being stored on the browser. I've tried almost all the solutions given previously here on stackoverflow but none of them worked for me.

  • Have you checked the browser's developer console? Very often the browser will tell you why it drops a cookie. Maybe you've hit some limits? – Michal Trojanowski Mar 31 '22 at 07:12
  • @MichalTrojanowski Yes I have and there is no hint. I can see the set-cookie header being returned in the developer console but there is no error or warning shown. – infinityEdge Mar 31 '22 at 07:14

1 Answers1

1

For anyone still suffering this issue, turns out the problem was with axios.post. I removed {withCredintials: true} config option from the request and just added

axios.defaults.withCredentials = true;