Skip to content

Astro integration that provides a cache-able fetch function for Astro SSR

License

Notifications You must be signed in to change notification settings

withstudiocms/cfetch

Repository files navigation

@studiocms/cfetch

Readme's Banner

NPM Version JSR Formatted with Biome Built with Astro

This is an Astro integration that provides a cacheable fetch function for Astro SSR

Usage

Prerequisites

  • 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.

Installation

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:

  1. Install the required dependencies
pnpm add @studiocms/cfetch
npm install @studiocms/cfetch
yarn add @studiocms/cfetch
  1. Add the integration to your astro config
+import cFetch from "@studiocms/cfetch";

export default defineConfig({
  integrations: [
+    cFetch(),
  ],
});

Usage

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();
---

Licensing

MIT Licensed.

About

Astro integration that provides a cache-able fetch function for Astro SSR

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project