/    Sign up×
Bounties /Pin to ProfileBookmark

How to configure Cloudflare caching for a SvelteKit endpoint?

+ 5,000
Copy linkTweet thisAlerts:
Oct 18.2023

I want Cloudflare CDN to cache GET responses from a SvelteKit server endpoint using the cloudflare-adapter. The goal is for users to receive the same cached response if it was previously requested by someone else. When the TTL expires, Cloudflare should fetch a new response from the endpoint. How can I achieve this?

to post a answer
CloudSvelteWeb Hosting

1 Replies

Davinci•003 auto-replyConfiguring Cloudflare caching for a SvelteKit endpoint involves setting up page rules in your Cloudflare dashboard and configuring your SvelteKit server to send the appropriate caching headers.

Here's a step-by-step guide:

1. **Set up Cloudflare Page Rules**

Go to your Cloudflare dashboard, select your site, and navigate to the "Page Rules" section. Create a new page rule for the path of your SvelteKit endpoint (e.g., https://yourdomain.com/endpoint*). In the settings, choose "Cache Level" and set it to "Cache Everything". This tells Cloudflare to cache the responses from your SvelteKit endpoint.

2. **Configure SvelteKit to Send Caching Headers**

In your SvelteKit server, you need to set the Cache-Control header for the responses from your endpoint. This tells Cloudflare how long to cache the response. Here's an example of how to do this in a SvelteKit endpoint:

export async function get(request) {
const data = await fetchData(); // Fetch your data here

return {
body: data,
headers: {
'Cache-Control': 'public, max-age=3600', // Cache for 1 hour

In this example, the
Cache-Control header is set to public, max-age=3600, which tells Cloudflare to cache the response for 1 hour.

Remember, the effectiveness of caching depends on the nature of your data. If your data changes frequently, you might want to set a lower
max-age. If your data rarely changes, you can set a higher max-age` to benefit more from caching.

Was this helpful?



Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ

legal: ({
terms: of use,
privacy: policy
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,