SSR Helper
Notes
This is a fork of alawi:ssr-helper
with minor tweaks.
- Bugfixes
- Fields to be published are taken from Meteor.settings.userFields
This pacakge aims to simplify Meteor's server rendering process. Specifically:
- Make Meteor.User() works during server rendering, accessing
Meteor.user()
during Meteor server rendering process will result in
Meteor.userId can only be invoked in method calls or publications
this is because the Meteor DDP session has not been instaniated yet. However, it is a common to require the user object in order to personalize the server render page thus the package will patch Meteor.user()
to make it work during SSR.
- Simplify the marshaling of data from server to client during SSR.
Installation
$ meteor add settlin:ssr-helper
Usage
Server:
1import { SSRServerHelper } from 'meteor/settlin:ssr-helper'; 2 3onPageLoad(async sink => { 4 5 // Meteor.user() will work as expected, instead of throwing out of context error. 6 console.log(Meteor.user()) 7 8 // Instantiate the server helper. 9 const ssrHelper = new SSRServerHelper(sink); 10 11 // Set items to be passed to the client. 12 ssrHelper.setItem('count', {name: '1'}); 13 14 // Inject the data to the page body. 15 // It will also inject user doc by default. 16 ssrHelper.injectData(); 17});
Client:
Somewhere in the client initialization code:
1import { SSRClientHelper } from 'meteor/alawi:ssr-helper'; 2 3// Process the injected SSR data. 4SSRClientHelper.processData(); 5 6// Get the SSR data. 7console.log(SSRClientHelper.getItem('name')); 8 9// SSR user is injected by default when inject() is called. 10console.log(SSRClientHelper.getItem('user')); 11
How
A cookie is set when the user is logged-in to keep track of their state. The cookie them gets passed to the server on the http initial request which is then used to fetch the user doc from the users collection.
The data is then injected in the body of the server rendered page. The client parses the injected data and store in the session storage.
Security
Using the user token to fetch the user data when doing SSR has some security concerns that were discussed here, and here.
Next Steps
- Patch
Meteor.userId
on the server during SSR - Patch
Meteor.user()
at the client during SSR
Credits
The code is based on the snippets from kadira's fast render package.