airbnb / hypernova

A service for server-side rendering your JavaScript views
MIT License
5.82k stars 210 forks source link

Caching? #28

Closed tristanoneil closed 8 years ago

tristanoneil commented 8 years ago

Does Hypernova cache components and if so what is the cache key based on? I was looking through the code and it appears like there's some caching going on but only in createVM which doesn't appear to be used unless you're using createGetComponent. I'm not using createGetComponent because I'm just bundling all of my components into a single file and calling the corresponding component given the passed in name like:

getComponent(name) {
  return require('./app/assets/build/server-bundle.js')[name];
}
goatslacker commented 8 years ago

Hypernova itself does not cache. createVM caches the module.exports because VMs are expensive to run on each request (requires need to be resolved, and all of the code needs to be evaluated)

You can use createVM yourself without createGetComponent. createGetComponent is just there as a sugar for using createVM but it's not required.

Though, be aware that caching the VM gives the bundle the ability to leak data between requests of the same VM. This means that if you have a global variable, singleton, or any possible side effect that runs when you call the module.exports of your bundled code, it will persist across different requests.

This is generally OK in today's ReactDOM.renderToString world where rendering is synchronous. It's something to keep in mind though.

With your particular example, you're already caching in the same way createVM does. require caches, so running getComponent(name) again will not re-require ./app/assets/build/server-bundle.js.

That example still suffers from the same leaky behavior as createVM. Also, using plain require will also let any application-code potentially trample onto Hypernova's server since the require is run within the server's context.

tristanoneil commented 8 years ago

@goatslacker Gotcha, is caching recommended? Just not sure how expensive rendering the component to HTML is for each request.

goatslacker commented 8 years ago

Depends on your situation. If you can get fast enough rendering without caching then I'd keep it simple and do that.

Render time is included with each Hypernova response so you can take a look at how long its taking the server to render your HTML.