Hacker News new | past | comments | ask | show | jobs | submit login

In my experience [1], you'd probably just use an if statement that does something different when you're on the server. That's totally fine and is still a universal app; universal apps don't have to take every exact same code path on the client and server, they just have to run the same code base.

In React, people typically use the ExecutionEnvironment module [2] for this:

    if (ExecutionEnvironment.canUseDOM) {
      // make client side request
    } else {
      // make direct db request
    }
...but you could also just do some simpler check, like see if `window` exists, or make up your own `IS_SERVER` global, etc.

Next you'll wonder: won't that still ship the server-side code to the browser, even if it's not run, and pull in any server-only modules you're importing, e.g. database access stuff? No: you'd fix this with (for example) webpack's `DefinePlugin` [3], telling it that `ExecutionEnvironment.canUseDOM` should always be `true` wherever it occurs in your client-side JS bundle, and dead code elimination will then rip out those server-only `else` branches before that code gets shipped to the browser.

Or a similar setup, like wwalser hinted at: write 2 versions of your 'request' module: one for the client, and one for the server. Tell webpack it should point to the client-side one when you generate your client JS bundle. People use webpack because it lets you do all kinds of overrides like this.

[1]: I work at Formidable, we do a ton of React for big companies.

[2]: https://github.com/JedWatson/exenv

[3]: https://webpack.github.io/docs/list-of-plugins.html#definepl...




I'm actually working on an isomorphic app. My approach is to simply create a PersistenceService interface, with methods returning promises, and to make two classes implementing it, SqlPersistenceService and AjaxPersistenceService. You inject the correct instance when you create the server and when you create the client. No if needed, and as I'm using Typescript, the compiler ensures both SqlPersistenceService and AjaxPersistenceService will keep following the contract of PersistenceService in the future.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: