Why is the browser not setting cookies after an AJAX request returns?

OK, so I finally figured out the problem. It turns out that setting the Path option is important when sending cookies in an AJAX request. If you set Path=/, e.g.:

Set-Cookie:SessionId=foo; Path=/; HttpOnly

…then the browser will set the cookie when you navigate to a different page. Without setting Path, the browser uses the “default” path. Apparently, the default path for a cookie set by an AJAX request is different from the default path used when you navigate to a page directly. I’m using Go/Martini, so on the server-side I do this:

session.Options(session.Options{HttpOnly: true, Path:"https://stackoverflow.com/"})

I’d guess that Python/Ruby/etc. have a similar mechanism for setting Path.

See also: cookies problem in PHP and AJAX

Leave a Comment