What is SameSite cookie attribute?
Cookies are small text files that are stored on a user’s device to remember their preferences, login information, and other data. SameSite is a cookie attribute that can be used to prevent cross-site request forgery (CSRF) attacks. To ensure that cookies are transmitted securely and only to the intended website, the HTTP specification includes the “SameSite” cookie attribute. This attribute allows websites to specify whether or not a cookie should be sent along with cross-site requests.
Rails 6.1 introduced the SameSite
cookie attribute to the cookies
API.
However, this attribute was set to :lax
by default, which meant that cookies were not sent along with cross-site requests.
Although, the docs mentioned that this attribute could be set as nil. This didn’t work as it would fallback to :lax
by default.
Before
Let’s assume in our Rails application, we want to set a cookie for language set as en
and we want to ensure that this cookie is sent along with cross-site requests.
To do this we would write the following code:
However, this would not work since same_site would fallback to :lax
by default.
After
However in the upcoming Rails 7.1, this would work as expected.
The above code would now correctly set the SameSite
cookie attribute to nil
and the cookie would be sent along with cross-site requests.
This will ensure that the language
cookie is sent with requests to the application, regardless of the source of the request.
This allows the app to remember the user’s preferred language and provide a more personalized experience.
The ability to opt out of the same_site is a valuable addition to the Rails framework, and it provides more control over the behavior of cookies in our application.
Check out the PR for more details.