× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Meteor: Session variables

Seán C McCord
Jul 07, 2015
<p>Session variables in Meteor are a great tool to facilitate decoupling of application components on the client side.</p> <p> </p> <p>While the template's data context provides easy access to resources, and helpers provide a means of extracting and manipulating any data in a per-template scope, complex and modern sites will typically have global contexts which transcend the template data inheritence hierarchy.</p> <p> </p> <p>For example, if you have a button to add a resource in your navigation bar, but you want that addition to be contextually-sensitive to what you are working with in the main panel, you cannot simply use template data inheritence, since (ideally), these templates exist in different inheritence trees.  However, if you store your contextual data (say, the current category of item) to a (global) Session variable, any other template in the system can reference those to create context-sensitive reactions and interactions.</p> <blockquote> <p>You have an online database with media categories, and the user is browsing videos.  When they click the nav-bar's 'Add' button, the form that pops up has the category 'Video' preselected.</p> </blockquote> <p>You should use Session variables discriminately, however.  They are a global namespace.</p> <p> </p> <p>Key facts about Session variables:</p> <ul> <li>They are scoped to only the individual client <ul> <li>The server has no visibility to a client's session variables</li> <li>Clients do not share session variables</li> </ul> </li> <li>They are not stored across connected sessions.  These should not be used as a means of data persistence.</li> <li>They are fully reactive, when scalar.  Try to keep non-scalar values such as arrays out of session variables.  For those, use client-side-only collections or custom reactive data types instead.</li> <li>There exists the `Session.equals()` test function, which is EJSON-aware and reactive.  Use it.  Always.  Never do `if( Session.get() == 'alpha' ) {}`.</li> </ul> <p> </p>
comments powered by Disqus