↖️ Show all posts

Persistent cookies with Sinatra

Simple example

# in app.rb

require "sinatra/cookies"
require 'rack/contrib'
# require ...

class MyApp < Sinatra::Base
    enable :sessions
    use Rack::Cookies
    helpers Sinatra::Cookies

    get '/' do
        response.set_cookie("test_cookie", {
            :value => "This is a random test cookie",
            :expires => Time.new(2019,6,15),
            :path => '/'
            })
        haml :index
    end

    get '/test/cookie/reader'
        @cookieval = request.cookies['test_cookie']
        haml @cookieval
        # => "This is a random test cookie"
    end
end

You can find the implementation in the Sinatra MVC App i put together on my github account.

Badosus Example worked nearly out of the box in my Sinatra App (Username/Password auth already - read more). I had to modify the code just a little. Make sure to set your cookies like in my example above and provide a proper fail! in your Warden strategies.

Git some of my Sinatra MVC skeleton on github

I pulled off a customized “remember me” login option with a cookie-based user authentication option, thanks to these wonderful docs, blogs and gists.


⬅️ Read previous Read next ➡️