Skip to main content

Session API

Session provides a global object on the client that you can use to store an arbitrary set of key-value pairs. Use it to store things like the currently selected item in a list. Source: packages/session/session.js Note: Session is a ReactiveDict instance. All methods are reactive data sources. Locus: Client only

Session.set()

Set a variable in the session. Notify any listeners that the value has changed (eg: redraw templates, and rerun any Tracker.autorun computations that called Session.get on this key).
key
string
required
The key to set, eg, selectedItem
value
any
The new value for key. Can be any EJSON-compatible value, or undefined.

Session.setDefault()

Set a variable in the session if it hasn’t been set before. Otherwise works exactly the same as Session.set.
key
string
required
The key to set, eg, selectedItem
value
any
The new value for key

Session.get()

Get the value of a session variable. If inside a reactive computation, invalidate the computation the next time the value of the variable is changed by Session.set. Returns a clone of the session value, so if it’s an object or an array, mutating the returned value has no effect on the value stored in the session.
key
string
required
The name of the session variable to return
Returns: The value of the session variable, or undefined if not set.

Session.equals()

Test if a session variable is equal to a value. If inside a reactive computation, invalidate the computation the next time the variable changes to or from the value.
key
string
required
The name of the session variable to test
value
string | number | boolean | null | undefined
required
The value to test against
Returns: boolean - True if values are equal.

Complete Example

Persistence

By default, Session variables are not persisted across page reloads. If you need persistence, consider using:
  • localStorage for simple key-value storage
  • ReactiveDict with a name parameter for named reactive dictionaries
  • Third-party packages like u2622:persistent-session

Best Practices

  1. Use for UI state only: Session is best for temporary UI state like selected items, current page, or modal visibility.
  2. Initialize with setDefault: Use Session.setDefault() to set initial values to avoid undefined errors.
  3. Use equals() for comparisons: Session.equals() is more efficient than Session.get() when checking for specific values.
  4. Clear on navigation: Consider clearing session variables when navigating between routes to avoid stale state.