Browser isnot receiving cookies after deployment

Hi Support team, I deployed my react app on netlify which has backend deployed in heroku. My backend is cookie based authentication system. When user login successsfully, they get cookie in browser. It works fine on local host but after deploying in netlify, my browser doesnot receive cookies. I think it is cors problem. I am using __redirect file to redirect proxies.

My backend controller when someone login successfully is like this

const loginAdmin = asyncHandler(async(req,res)=>{
    const {email,password,code} = req.body
    if(!email || !password || !code){
        throw new Error('Every field is required')
    }
    const user = await User.findOne({email})
    if(!user || (!await user.comparePassword(password,user.password)) ){
        throw new Error('Invalid password or email')
   }
     if(user.role!=='admin'){
        throw new Error("You arenot admin")
    }
   if(code !== process.env.ADMIN_SECRET_key){
       throw new Error('Invalid code')
   }
   
   const token = await user.generateToken(3600*5)
   res.cookie('token',token,{
       httpOnly:true,
       maxAge:3600000*5,
       secure:true,
       sameSite:'none',
       domain: '.netlify.app'
    })
   res.json({message:'Welcome admin '})
})

In my frontend I am calling api like this

export const loginAdmin = (body)=> async dispatch => {
    dispatch({type:LOGIN_ADMIN_REQ})

    try {
        const config = {
            headers: {
                
              'Content-Type': 'application/json',
            },
          };
        await axios.post(`/api/admin/adminlogin`,body,config)
       
        dispatch({type:LOGIN_ADMIN_SUCCESS})
        dispatch(loadUser())
      
    } catch (error) {
      
        dispatch({
            type: LOGIN_ADMIN_FAIL,
            payload:error.response && error.response.data.message ? error.response.data.message
            : error.message
        })
    }
}

After login , I should make request with backend with cookies for authorization, which I am not getting

export const loadUser = ()=> async dispatch=>{
    try {
        const config = {
            headers:{
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            mode:'cors',
            credentials:'include',
            withCredentials:true
        }
        const res = await axios.get(`/api/admin`,config)
        dispatch({
            type: LOAD_ADMIN_SUCCESS,
            payload: res.data
        })
     
        
    } catch (error) {
        console.log(error.response)
      
        dispatch({
            type: LOAD_ADMIN_FAIL,
            payload:error.response && error.response.data.message ? error.response.data.message
            : error.message
        })
    }
}

api response is ok i.e. login is successful but I am not getting cookie in my browser due to which I cannot get user information. Any way to solve it? My site is https://mobyletech-admin.netlify.app

1 Like

Is there a test account that we can try?

Thanks for reply. I dont have test account. Can I provide you link to my github repository that contain backend code as well as front end code too?

@saral, the code might be useful for other volunteers who can check. So you can share it if you can keep it public.

The support team cannot provide help with custom code. We can try to some extent in some cases, but that depends on the load the team has. So, when I asked for a test account, it was because I could then just login with it and check how the cookies are being set in the browser.

@hrishikesh . Again thank you for reply. I updated my question in more detail and
also i made test account for checking
Please go to Admin Panel Mobyle Tech and enter following credentials
email : test@test.com
password : test1234
admincode : admin12345
After login, browser should receive cookie a/c to backend code but not receiving. I havenot added any logic in app , so you wont be redirected in home (if loading button stops, it means it logged in successfully) and I have also console.log any possible error.
Note that my backend code works in localhost , but not after deployment

I think there’s some problem going on with setting cookies. According to my understanding, once I click login, a cookie should be set, right? I don’t see any cookies in the developer tools. The spinner stops spinning, but there’s no cookie unfortunately.

Yes. It works fine in development i.e. local host so I can confirm my backend is working. Problem arrived after deployment.

Where is this backend controller running exactly? On Netlify? I don’t see any Netlify Functions running on your website, so I’m confused.

This must be your client-side JS, right?

From where are you making this request? Client-side?

@hrishikesh
My backend api is deployed in heroku. My front end client side Js is making request from heroku deployed api. I have added backend server side code in main question as well as how I am calling that api

I think, you should try removing the domain option from set cookie. While I’m not sure if it applies to Netlify (I’ll confirm this internally), it’s quite possible that you can’t set a cookie for all subdomains of Netlify (which is what you’re trying). If you do that, you could probably set a cookie for all websites hosted on Netlify and that would be a big problem. So either remove the option or set it for your subdomain only.

Let us know how that goes.

Here’s a page by Heroku explaining it: Cookies and the Public Suffix List | Heroku Dev Center

EDIT: Yes, Netlify exists in the list: https://publicsuffix.org/list/public_suffix_list.dat

Boom after removing domain, it worked. Thank you so much . Support team for netlify is great

Hello Saral

I am facing the same problem

Did it work on ur side? I am using JWT which uses cookies for authentication

Hello hrishikesh

I am facing the similar challenge

My app uses JWT and wont set cookies on deployment enviroment(netlify and heroku) but works fine on development

Do you have like a short answer as to why many people are facing thos issue and resourves i can visit

I cannot know your problem without seeing your code. I solved my error when I removed the domain option while setting up cookie in backend server, I guess you can try that and see if it works.

I am facing a similar problem. But on login cookies are sent and received but on taking other actions like liking, unliking, subscribing, etc. cookies are not requested from the backend. Everything works fine on localhost but on deployment, it is not working. My backend is hosted on render.
Test account - {name: lego10 , password: lego10}
Site link - https://vocal-sprite-dd6c42.netlify.app
frontend repo - GitHub - LEGO-SUDO/YTfrontend
backend repo - GitHub - LEGO-SUDO/YTbackend

Hi @lego :wave:t6: welcome to the forums! What have you tried so far?

I have tried setting the CORS configuration

and setting sameSite =‘none’ while sending cookies after login

res
        .cookie('access_token', token, {
          expires: new Date(Date.now() + 604800000),
          secure: env.ENVIRONMENT === 'LIVE',
          sameSite: env.ENVIRONMENT === 'LIVE' ? 'none' : 'lax',
          httpOnly: true,
        })

These were the only solutions I could find out.

Hey @lego,

It appears you’ve configured Axios incorrectly:

Based on Axios docs: Axios API | Axios Docs, the second parameter when using axios.put() is data which is request body. What you’re trying to set is config, which is the third parameter. So, your request should look like:

axios.put('url', null, {
  withCredentials: true
})

Oh god! Thank you so much. I was scratching my head over this for almost a month now. What a rookie mistake. It works correctly now.

Hi, @hrishikesh. I’m student and I came across the same problem, I’m using express-session and connect-mongo. On localhost, the program code is running well. However, when running online the user can only log in, and cannot verify the user. So, the middleware cannot detect user. Can you help me?
Test account - (email: admin@gmail.com, password: admin).
Site link: https://stulib.netlify.app/
frontend repo : GitHub - sulthonnn/crud-perpus-client: Perpustakaan menggunakan React JS
backend repo : GitHub - sulthonnn/crud-perpus-server: Perpustakaan menggunakan Node JS, Express JS

Thank you, Sir.