Changing a Cookie’s Domain in Rails

This is one of those things that should be really easy, and that a lot of people probably already know… But in the hopes of saving someone 30 minutes of frustrated searching, here’s what you should know.

If you want to change your session cookie’s path globally, there’s a documented setting. But what if you want to set some one-off cookie to be from something other than your FQDN?

It’s actually simple: rather than setting the cookie to a string (with its value), you use a hash:

cookies[:logged_in_username] = {
:value => "jdoe123", :domain => ".example.com"
}

It’s typical to just do cookies[:logged_in_username] = “jdoe123”, but it does accept a hash. (:expires is available, too.)

It turns out this is documented exactly where it should be, but that page doesn’t seem to get much love from Google.

2 thoughts on “Changing a Cookie’s Domain in Rails

  1. I’ve seen so many things that say *what* to do, but not *where* to put it.

    We have a sessions_controller. Using your example, let’s say I want to change the domain of :logged_in_username. In my sessions_controller’s create() method, I do

    username = cookies[:logged_in_username] # it was already set to a value
    cookies[:logged_in_username] = {
    :value => username,
    :domain => “mydomain.com”
    }

    But by the time I get to the browser, and use Chrome to inspect the cookie values, the domain is not changed.

    Even if I add a new cookie here in my sessions_controller

    cookies[:mycookie] = {
    :value => “CookieMonster”,
    :domain => “.contactusinc.com”
    }

    It’s nowhere to be found by the time the page loads in the browser. Debug printing tells me that it *IS* getting into the create() method in my sessions_controller. And when I print “cookies” the values I changed/added are showing up. But they get lost somewhere along the way.

    What is the correct file in a Rails application to set the cookie according to your example?

    Thanks!

  2. I wrote this in the days of Rails 2, so I’m honestly not sure how pertinent it is today.

    The one thing I remember being an issue is that some browsers would reject cookies not from the same domain. You could set them for a higher-level part of the domain (e.g., foo.example.com could set .example.com), but not for a _separate_ domain. The browser would just reject them. Not sure if that would explain what you’re seeing or not.

Leave a Reply to Gayle Cancel reply

Your email address will not be published. Required fields are marked *