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...