Both the internet's IP and the world wide web's HTTP use what is called a stateless protocol. This means that the sender and the receiver of data are indifferent to the state of one another and do not have knowledge of any previous states. Requests are sent and received and then forgotten about. No one is responsible for remembering requests and no data is maintained over the life of the session.
In web development, we are often interested in making our web apps dynamically respond to user inputs and remember the state of the current user, so that things like staying logged in from page to page and maintaining a shopping cart are effortless. This demand requires persisting data across requests, which is not in the wheelhouse of a stateless protocol.
But fear not! By leveraging a browser's cookies, we can safely persist data across requests and maintain that data over the lifetime of a user session, effectively transforming our stateless protocol into one that is stateful.
In Ruby on Rails, information can be stored in a hash-like data structure called the session. The values in this hash in one request can be accessed in a subsequent request using the session
method. When a new user accesses the application, a new session hash is created with a session id and other key-value pairs. When a user is recognized, the relevant session information is delivered by the session hash and the user can continue to access data across requests.
Using sessions makes it possible for us to state-ify our otherwise stateless protocol. With power comes responsibility, though, and we need to follow safe practices to prevent session hijacking.
When all goes well, sessions help us transform a fleeting connection to a lasting sharing of secrets.