Chapter 13. Sessions and Cookies

The Web was built to do one thing at a time. Each request is, from the point of view of the client and server, completely independent of every other. A group of requests might all operate on the same database, and there can be clear paths from one part of an application to another, but for the most part, HTTP and scalable web application design both try to keep requests as independent as possible. It makes the underlying infrastructure easier.

Rails balances that simplicity of infrastructure with application developers’ need for a coherent way to maintain context. Rails supports several mechanisms keeping track of information about users. If you want to keep track of users manually, you can work with cookies. If you want to keep track of users for a brief series of interactions, Rails’ built-in session support should meet your needs.

Note

If you want to keep track of users on a long-term basis, you’ll want to use the authentication tools covered in Chapter 14.

Getting Into and Out of Cookies

Like nearly every web framework, Rails provides support for cookies. Cookies are small pieces of text, usually less than 4 KB long, that servers can set on browsers and browsers will pass back with requests to servers. Browsers keep track of where cookies came from and only report cookies’ values to the server where they came from originally. JavaScript code can reach into a cookie from a web page, but Rails itself is more interested in setting and receiving ...

Get Learning Rails: Live Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.