Home > Software design >  Cookie Not Being Set on Netlify Hosted React App
Cookie Not Being Set on Netlify Hosted React App

Time:03-07

I have a React app that calls into a Rails App.

The React app is hosted on Netlify, and the Rails app on Heroku.

Locally, I am able to create a session and have the rails app set a cookie in the browser.

The network requests work just fine. However, after deploying to Netlify the production app isn't setting cookies.

Here is my login function

    fetch(`${API_ROOT}/api/sessions`, {
      headers: {'Content-Type': 'application/json'},
      method: 'post',
      credentials: 'include',
      withCredentials: true,
      body: JSON.stringify(body)
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === 'created' && data.user){
        props.handleLogin(data)
        navigate("/");
      } else
      {
        setAuthErrorState({
          isError: true,
          message: data.message
        });
      }
    });
  }

And my session_store.rb and cors.rb files

cors (domain redacted)

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "http://localhost:3000"
    resource "*", headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head],
    credentials: true
  end

  allow do
    origins "https://www.[domain].io"
    resource "*", headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head],
    credentials: true
  end
end

session_store.rb

Rails.application.config.session_store :cookie_store, key: "_authentication_app"

CodePudding user response:

I would request you to go to the "Network" tab in the dev tools of your browser and go to the request :'${API_ROOT}/api/sessions', and and confirm 2 things in the response headers of this request:

  1. Is your React app domain name(i.e,: "https://www.[domain].io") present in the header Access-Control-Allow-Origin of the response? If not, what is the header set to ?
  2. Is the said cookie present in the Cookie header of the response ? If not, please mention.

Purpose of this activity: To pinpoint the issue to either a CORS red flag by the browser , or the cookie not having the proper domain name set in it, and hence the cookie might appear to vanish.

CodePudding user response:

This post helped me resolve the issue:

https://medium.com/@ArturoAlvarezV/use-session-cookies-to-authenticate-a-user-with-a-rails-api-backend-hosted-in-heroku-on-one-domain-f702ddf8c07

  • Related