This is an Astro integration that provides a cacheable fetch function for Astro SSR
- Using with an Astro SSR project, While you could import and use this in an Astro SSG (static) project, it would have no benefit as Astro Static pages are pre-rendered.
Install the integration automatically using the Astro CLI:
pnpm astro add @studiocms/cfetch
npx astro add @studiocms/cfetch
yarn astro add @studiocms/cfetch
Or install it manually:
- Install the required dependencies
pnpm add @studiocms/cfetch
npm install @studiocms/cfetch
yarn add @studiocms/cfetch
- Add the integration to your astro config
+import cFetch from "@studiocms/cfetch";
export default defineConfig({
integrations: [
+ cFetch(),
],
});
You can import the cFetch
function anywhere and use it as you would use a normal fetch
call. cFetch
adapts the same default options as fetch
:
---
import { cFetch } from 'c:fetch';
const response = await cFetch(
'https://example.com', // string | URL | Request
{ /* Normal fetch init optional options here, method, mode, etc. */ },
{ lifetime: "1h" }, // Optional, allows changing the default lifetime of the cache
'json', // Optional, allows changing the type of response object to be cached. 'json' (default) or 'text'
);
const html = await response.text();
---
If you need to access the other available metadata (such as the lastChecked
value which provides the last time the cache was updated), you can pass true
as the fourth parameter, which will change the returned object to the following:
---
import { cFetch } from 'c:fetch';
const { lastCheck, data } = await cFetch(
'https://example.com',
{ /* ... */ },
{ lifetime: "1h" },
'json',
true // Changes the the output to include the lastCheck value
);
const html = await data.text();
---