stereobooster / react-snap

👻 Zero-configuration framework-agnostic static prerendering for SPAs
MIT License
5.04k stars 391 forks source link

Added 'onJsonFetch' callback option #383

Open Stanko opened 5 years ago

Stanko commented 5 years ago

I added onJsonFetch callback option, which will be called every time JSON file is fetched.

This will allow users to cache json files on file system and create gatsby-like system, where everything, including json data is static.

Relates to issue #221. I left a question there some time ago, and finally got some time to implement it.

Let me know what do you think.


Stanko commented 5 years ago

Just to mention that my team implemented this on the project we are working on, and it is working like a charm. We are caching all responses to ./data folder, and then using it in production.

We can differentiate between app running in headless and user's browser by checking user agent:

const isSnap = navigator.userAgent.toLowerCase().search('reactsnap') >= 0;

Then we switch to using cached data instead of the real API:

// In production, if app is not being crawled by react-snap
// we want to use locally cached API data instead of the real API
const useLocalData = !isSnap && process.env.NODE_ENV === 'production';

const API_URL = useLocalData ? '/data' : process.env.API_URL;