Drew's Blog - Home - Archive

Help! I've lost my session cookie!

For the past 2 weeks or so, I've been working on a Rails app for the first* time since I went back to school. I may write a longer post about the rest of it, but for now I will talk about losing my cookies. I ran in to a problem today where when someone tried to create a schedule, (it's a scheduling app that also shows you which classes that satisfy various major requirements are running) they were instead logged out, because their session cookie was lost. This happens because Rails needs the X-CSRF-Token header to be set to the value of the csrf-token meta tag on AJAX or POST requests. There are two things you need to do to make sure this always happens:

1. If you're using jQuery, you probably have some sort of wrapper for $.ajax (I know I always do, anyway...). Somewhere, (probably in that file,) you need to put this code snippet: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')); } }); That will ensure that you always have it for AJAX requests. (Credit is here: http://stackoverflow.com/questions/5126721/rails-not-reloading-session-on-ajax-post)

2. ...USE <% form_for %> OR <% form_tag %> HELPERS! (This is where I was screwing up, and I really felt dumb once I realized what I was doing.)

But yeah, that's it. Rails does all the heavy lifting for you! Don't try to outsmart it.


*actually second, but I have yet to write any front end for the first one, so it doesn't count.

If you've read this far, you should probably follow me on Twitter.

See more posts

Drew writes code for fun and (sometimes) profit. He's currently studying Computer Science at Carnegie Mellon University. He has previously worked at Facebook, Amazon, and a startup called Intersect.