Introduction #
Caching fetch
requests, particularly when developing locally, is a nice addition to your workflow when you're working on your remote data-powered, Astro static site.
One of the packages that I've used in the past with Eleventy, another great SSG, is eleventy-fetch
.
eleventy-fetch
is a simple package that caches fetch
requests based upon a few configuration options. And while the package calls itself a "a plugin for the Eleventy static site generator", there's no reason that it can't be used with other frameworks!
Usage #
- After you've created your Astro site, add
eleventy-fetch
as a dependency.
npm i @11ty/eleventy-fetch
- Declare the package as a module in the
env.d.ts
file generated by Astro, sinceeleventy-fetch
is not written in TypeScript by adding the line below to the end of the file.
declare module "@11ty/eleventy-fetch";
- Now, just use
eleventy-fetch
wherever you'd normally usefetch
! The below will cache the responses on disk in a.cache
directory for 1 hour. You'll see the.cache
directory populate with some files that hold the responses to your API requests.
import EleventyFetch from "@11ty/eleventy-fetch";
const results: any = await EleventyFetch(`https://example.com/api`, {
duration: "1h",
type: "json",
});
- As the docs note, ensure that you add the
.cache
directory to your.gitignore
!
Conclusion #
Sorry if you were looking for some complex method to cache requests with Astro, but I'm going to tell you that if you're looking to cache your requests to avoid hitting that API too frequently when developing locally, just use eleventy-fetch
. Yes, even with Astro! It'll save you some time and headache.