Working with Sessions

Remember with routes, everything that goes away after it’s called. Any variables we create are destroyed as soon as the task is completed. But our users are likely to make use of more than one action on our web application. Wouldn’t it be great if we could keep some information around for the next time they do something with our application?

We’ll with sessions we can. Sessions allow us to store bits of information that are just about a single user. Those bits of information are maintained by the web server even after a request completes. That way the next time a user visits, it’ll be available.

Illustration of how sessions work

Using Sessions in your project

To use sessions, you just need to add one line of code to your application (typically at the top)

enable :sessions

Then we can use sessions like this:

get '/' do
  "value = " << session[:value].inspect
end

get '/:value' do
  # store a parameter in a session
  session['value'] = params['value']
end

An Example

Let’s look at a basic example, if we wanted to personalize the experience of the application by asking the user to tell us their name:

get '/'
    if session["name"].nil?
      'Welcome!'
    else
      'Welcome back ' + session["name"]
    end
end	


get '/set_name/:name' do
  
  # here we're assigning the parameter
  # into a session variable 
  # this information then persists across
  # requests to the webservice
  # i.e. the server will maintain this information
  # specific to a single visitor / user
  
  session["name"] = params["name"]
  "Hello there, " + params["name"]
end


get '/unset_name' do
  session["name"] = nil
end

Sidebar: This is essentially how authentication works for most web applications too. Instead of set_name, you have log in. Instead of unset_name you have logout. And then you’d look up the credentials and store them in a session so you don’t have to log in before every single request you make.

Keep in Mind: Expiry

Sessions are really useful but you can’t rely on them to be there forerver. They will eventually EXPIRE.

Sessions will disppear after an specified ‘idle time’. Your sessions might also be reset when you restart your server or deploy new code to a remote server.

Keep this in mind as you’re using sessions. It’s great for sharing information between your routes in the short term but it’s not a long term solution.

×

Subscribe

The latest tutorials sent straight to your inbox.