menu

React Static

A fast, lightweight, and powerful framework for building static-progressive React applications and websites.

Channels
Team

Caching API requests in development

March 11, 2019 at 3:47pm

Caching API requests in development

March 11, 2019 at 3:47pm

Could anyone suggest a good approach to cache 3rd party API requests in development for React Static?

One of the sites I've built has grown a lot and due to React Static fetching all the data each time I run yarn start, I keep killing the 3rd party API with requests when developing new features.

This is not so crucial for the front-end features, but I want to clean up the data in node when creating the routes, which requires constant restarts, so would be ideal to be able to cache these requests locally and read from the cache instead.


March 13, 2019 at 3:05pm

What kind of API requests are you making, and does your 3rd party enable webbooks?

  • reply
  • like

I assume you mean webhooks? Yes, but that has nothing to do with this really.

I'm fetching all the site data from Prismic JS API, but there's a lot of it, so would like to cache the requests locally to not bombard the API too much when building the code for routes and cleaning the JSON responses prior serving these to the front-end.

  • reply
  • like

March 19, 2019 at 7:49pm

Well if your CMS has webhooks you might be able to leverage them to push changes to your repo and trigger builds as they occur vs having a build process that fetches all of the content at once. For instance, all of my WordPress content lives in my repo as .json files. Every time there is a change on WP, I am using a webhook to update the repo and trigger the build. Since all of the content lives in the repo, there is no need for api requests at build-time. There is some overhead and still some things to iron out, but for a couple reasons I think it is a decent solution.

  • reply
  • like

April 2, 2019 at 5:05pm

I would suggest storing any assets you get in a cache.json file or something in your project (ideally in a temp folder)

  • reply
  • like

When you start the server, check for the file first and use it if if exists

  • reply
  • like

Otherwise, fetch the data and store it in that file

  • reply
  • like

You could pass an env variable to bypass the cache file and rerequest

  • reply
  • like

something like TANNER_REFRESH_CACHE=true yarn start

  • reply
  • like

then use process.env.TANNER_REFRESH_CACHE === 'true' in your code to bypass the cache

  • reply
  • like