Imagine writing tests with mocked requests. Now apply that same logic to all calls to fetch() on the server. Does that make sense?
So to the front end when fetch() is called, it actually makes the request. On the server, when fetch() is called it hits a mock plugin which fetches "mocked" data which is just fetching data from whatever local store you normally would on your backend be it a JSON blob on the file system, a database or an in memory cache.
editing to say that @exogen gave what may be a better explanation below: https://news.ycombinator.com/item?id=12273029
That's what I'm apparently failing to describe how to accomplish :).
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...