Cannot use http only cookies when deploy my rails backend application to heroku

35 views Asked by At

Currently I have finished backend and I tried to deploy it on heroku, but when I change api calls of my frontend(react typescript) to the new heroku.com url, the session just cannot work (can't save login status and every time I went to a new page it just needs me to login again), I haven't deploy my frontend react app now so it's still on localhost:3000, so here's my config/initializer/session_store.rb file and cors.rb file. session_store.rb:

Rails.application.config.session_store :cookie_store, key: "_web_forum", domain: :all

cors.rb:

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 "http://localhost:3001" #replace this with final react website
        resource "*", headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head], credentials: true
    end
end

I am totally new to react and rails so if there's any code needed to update please tell me :)

I changed the domain in session_store.rb file but it seems unsuccessful. My cookie session uses http only cookies for authentication.

1

There are 1 answers

2
8bithero On

Your cors.rb file is currently set to allow origins only from localhost:3000 and localhost:3001. Once you deploy your React app, you'll need to update this to include the deployed frontend's URL.

Regarding your session_store.rb you probably don't want :all for the domain. Instead set it to your heroku domain. Additionally since you are using HTTP make sure you set httponly to true:

Rails.application.config.session_store :cookie_store, key: "_web_forum", domain: "your-heroku-app-name.herokuapp.com", httponly: true

And finally make sure you are including credentals in your frontend request. So it should look like this:

fetch('http://your-heroku-app-name.herokuapp.com/api/endpoint', {
  method: 'GET', // or 'POST', etc.
  credentials: 'include', // Important for including cookies
  // other settings...
});