class litestar.middleware.session.base.BaseBackendConfig#

Bases: ABC, Generic[BaseSessionBackendT]

Configuration for Session middleware backends.

key: str#

Key to use for the cookie inside the header, e.g. session=<data> where session is the cookie key and <data> is the session data.


  • If a session cookie exceeds 4KB in size it is split. In this case the key will be of the format session-{segment number}.

max_age: int#

Maximal age of the cookie before its invalidated.

scopes: Scopes = {ScopeType.HTTP, ScopeType.WEBSOCKET}#

Scopes for the middleware - options are http and websocket with the default being both

path: str#

Path fragment that must exist in the request url for the cookie to be valid.

Defaults to '/'.

domain: str | None#

Domain for which the cookie is valid.

secure: bool#

Https is required for the cookie.

httponly: bool#

Forbids javascript to access the cookie via ‘Document.cookie’.

samesite: Literal['lax', 'strict', 'none']#

Controls whether or not a cookie is sent with cross-site requests.

Defaults to lax.

exclude: str | list[str] | None#

A pattern or list of patterns to skip in the session middleware.

exclude_opt_key: str#

An identifier to use on routes to disable the session middleware for a particular route.

property middleware: DefineMiddleware#

Use this property to insert the config into a middleware list on one of the application layers.


from os import urandom

from litestar import Litestar, Request, get
from litestar.middleware.sessions.cookie_backend import CookieBackendConfig

session_config = CookieBackendConfig(secret=urandom(16))

def my_handler(request: Request) -> None: ...

app = Litestar(route_handlers=[my_handler], middleware=[session_config.middleware])

An instance of DefineMiddleware including self as the config kwarg value.

class litestar.middleware.session.base.BaseSessionBackend#

Bases: ABC, Generic[ConfigT]

Abstract session backend defining the interface between a storage mechanism and the application SessionMiddleware.

This serves as the base class for all client- and server-side backends

__init__(config: ConfigT) None#

Initialize BaseSessionBackend


config – A instance of a subclass of BaseBackendConfig

static serialize_data(data: ScopeSession, scope: Scope | None = None) bytes#

Serialize data into bytes for storage in the backend.

  • data – Session data of the current scope.

  • scope – A scope, if applicable, from which to extract a serializer.



data serialized as bytes.

static deserialize_data(data: Any) dict[str, Any]#

Deserialize data into a dictionary for use in the application scope.


data – Data to be deserialized


Deserialized data as a dictionary

abstract get_session_id(connection: ASGIConnection) str | None#

Try to fetch session id from connection ScopeState. If one does not exist, generate one.


connection – Originating ASGIConnection containing the scope


Session id str or None if the concept of a session id does not apply.

abstract async store_in_message(scope_session: ScopeSession, message: Message, connection: ASGIConnection) None#

Store the necessary information in the outgoing Message

  • scope_session – Current session to store

  • message – Outgoing send-message

  • connection – Originating ASGIConnection containing the scope



abstract async load_from_connection(connection: ASGIConnection) dict[str, Any]#

Load session data from a connection and return it as a dictionary to be used in the current application scope.


connection – An ASGIConnection instance


The session data


  • This should not modify the connection’s scope. The data returned by this method will be stored in the application scope by the middleware

class litestar.middleware.session.base.SessionMiddleware#

Bases: AbstractMiddleware, Generic[BaseSessionBackendT]

Litestar session middleware for storing session data.

__init__(app: ASGIApp, backend: BaseSessionBackendT) None#

Initialize SessionMiddleware

  • app – An ASGI application

  • backend – A BaseSessionBackend instance used to store and retrieve session data

create_send_wrapper(connection: ASGIConnection) Callable[[Message], Awaitable[None]]#

Create a wrapper for the ASGI send function, which handles setting the cookies on the outgoing response.


connection – ASGIConnection