Sessions can be used to store small amounts of data that will be persisted between requests, on a per-visitor basis. This data is usually stored on the backend side (depending on the chosen session storage), and it is associated with a session ID that is persisted on the client through the use of a dedicated cookie.
In order to use sessions, you need to make sure that the
Marten::Middleware::Session middleware is part of your project's middleware chain, which can be configured in the
middleware setting. Note that the session middleware class is automatically added to this setting when initializing new projects.
If your project does not require the use of sessions, you can simply ensure that the
middleware setting does not include the
Marten::Middleware::Session middleware class.
How the session ID cookie is generated can also be tweaked by leveraging the following settings:
How session data is actually persisted can be defined by configuring the right session store backend, which can be done through the use of the
By default, sessions are stored within a single cookie (
:cookie session store). Cookies have a 4K size limit, which is usually sufficient in order to persist things like a user ID and flash messages.
:cookie is the only store that is built in the Marten web framework presently.
Other session stores can be installed as separate shards. For example, the
marten-db-session-store shard can be leveraged to persist session data in the database.
Marten::Middleware::Session, each HTTP request object will have a
#session method returning the session store for the current request. The session store is an instance of
Marten::HTTP::Session::Store::Base and provides a hash-like interface:
# Persisting values:
request.session[:foo] = "bar"
# Accessing values:
# Deleting values:
# Checking emptiness:
Both symbol and string keys can be used when trying to interact with the session store, but only string values can be stored.
If you are trying to access the session store from within a handler, it should be noted that you can leverage the
#session method instead of using the request object:
class MyHandler < Marten::Handler
session[:foo] = "bar"
respond "Hello World!"