kadirahq / flow-router

Carefully Designed Client Side Router for Meteor
MIT License
1.09k stars 192 forks source link

Access user agent during ssr #576

Open imkost opened 8 years ago

imkost commented 8 years ago

Radium requires global navigator object with valid user agent to be defined during ssr.

How can I access navigator object on ssr?

arunoda commented 8 years ago

You can get it from the context. It has the raw request object. See: https://github.com/kadirahq/flow-router/blob/ssr/server/route.js#L147

Get headers from that.

imkost commented 8 years ago

Thank you for replay, but, sorry, I still don't understand. How can I get context?

What I'm trying to achieve:

FlowRouter.route('/', {
  action() {
    if (Meteor.isServer) {
      // Define `global.navigator.userAgent`
      // in order to make Radium work correctly during ssr.
      global.navigator = {
        userAgent: ??? // How?
      };
    }

    mount(App);
  }
});

I examined the code and figured out this solution:

if (Meteor.isServer) {
  const { Route } = FlowRouter;
  const originalBuildContext = Route.prototype._buildContext;

  Route.prototype._buildContext = function(...args) {
    var context = originalBuildContext.apply(this, args);

    global.navigator = {
      userAgent: context._serverRequest.headers['user-agent'],
    };

    return context;
  }
}

FlowRouter.route('/', {
  action() {
    mount(App);
  },
});

But this solution looks hacky. Is there a more natural way of getting user agent?