1

Things work fine locally. User logs in -> user id is saved in rails session -> refresh browser -> still logged in as expected. However, on Heroku, the flow is broken. User logs in -> user id is saved in rails session -> refresh browser -> session variable :current_user_id is gone and they’re logged out.

It was set up as a standard rails app (not api only).

config.ru (also put this in cors.rb)

use Rack::Cors do
    allow do
        origins 'http://localhost:3000', 'https://client-side.herokuapp.com'
        resource '*',
           headers: :any,
           methods: [:get, :post, :delete, :put, :options],
           credentials: true
    end
end

session_store.rb

if Rails.env === 'production' 
    Rails.application.config.session_store :cookie_store, :key => '_myapp', domain: 'app-client.herokuapp.com'
  else
    Rails.application.config.session_store :cookie_store, key: '_myapp' 
  end

application.rb

config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
config.middleware.insert_after(ActionDispatch::Cookies, ActionDispatch::Session::CookieStore)

Copied the application.rb code snippet above from this post: Adding cookie session store back to Rails API app but it made no difference. Maybe because mine is a standard Rails app and theirs was an API only app.

Does anyone know what would cause the session variable key :current_user_id and it's value to not exist in the session object only in production mode (Heroku)? ie cookies are never written.

devmonkey
  • 11
  • 2
  • This isn't exactly the cause of the issue but `Rails.env === 'production' ` is really smelly. The triple-equals operator does different things depending on what class the left and right operands are. If you you want to do string comparison use `Rails.env == 'production'` - but you can also just use `Rails.env.production?` since its an instance of [StringInquirier](https://api.rubyonrails.org/classes/ActiveSupport/StringInquirer.html). See https://medium.com/rubyinside/triple-equals-black-magic-d934936a6379 – max Oct 17 '20 at 10:54

1 Answers1

0

I had a very similar problem and I think I've found a solution. The same as you, my code was working in development but after pushing to Heroku I would lose session upon reload.

In my case I had my React app hosted on x-frontend.herokuapp.com and rails app on x-backend.herokuapp.com. The rails app must have treated this setup as two different domains and one domain was being blocked from holding cookies that are used in the other domain.

What worked for me:

In gemfile.rb:

gem 'rails_same_site_cookie'

In config/environments/production.rb:

config.action_dispatch.cookies_same_site_protection = :None
grzalamp
  • 21
  • 4