Sessions in my Sinatra App

Derek Le
3 min readMay 27, 2021

Sessions play a crucial part in making sure a user has a good experience when navigating an app. When a user opens a website, the site by itself will not remember who the user is. This is because the web uses HTTP, which means webpages do not retain information from any previous requests — thus there’s no way for a page to know who to cater any of its user-centric elements to as we navigate from page to page. To fix this, we use cookies and sessions, which is provided to us through Sinatra, which gets this ability from the Rack gem that it’s built on.

Both cookies and sessions act like hashes that contain data related to the user’s interactions on a webpage that need to persist (login information, submitted forms, etc). Webapps will store session the information in a cookie which will live in the browser. Now the browser sends the persisted information in the cookie along with any request it makes to the server.

In order to utilize the power of sessions, we must first implement this line in our application controller:

enable :sessions

This line tells Sinatra to a create sessions object, and to start storing relevant information in it. The most basic use of sessions is user authentication. Here is my code for logging in a user:

When a user inputs login information on the webpage, the client sends a POST request to the server with that info. the application first checks if there is a user in the database that has a matching username, and then runs the authenticate method provided to us by ActiveRecord. The User class is given this method when the following line is added:

Once authenticated, the controller sets the user_id attribute in the session hash to the id of the user logging in.

A user object with id 4, and the session hash with user_id 4

Now when a user navigates from page to page, the webapp will remember the information stored in the session hash (user_id = 4) until changed or destroyed. We can now use this in other parts of our controller when we need to find out who the current user is, in order to render pertinent information on the webpage:

Returns true if the user_id has a value other than nil.
This method takes advantage of the session hash we created by returning the User with an id matching the stored user_id attribute.

To conclude, sessions are simply hashes of information containing information about the user’s interactions the website. This helps our website know what to render and who to render it for.

--

--