Skip to content

Instantly share code, notes, and snippets.

@codenickycode
Last active October 25, 2024 00:19
Show Gist options
  • Save codenickycode/d1e157b4577feaf17d06c90b38f3c2eb to your computer and use it in GitHub Desktop.
Save codenickycode/d1e157b4577feaf17d06c90b38f3c2eb to your computer and use it in GitHub Desktop.
Cache-Control header
import { json } from "@remix-run/node";
import type { LoaderFunction } from "@remix-run/node";
// For session-specific data
export const sessionLoader: LoaderFunction = async ({ request }) => {
const data = await fetchSessionData();
return json(data, {
headers: {
"Cache-Control": "private, max-age=3600", // Cache for 1 hour for this user only
"Vary": "Cookie" // Ensures different caches for different sessions
}
});
};
// For generic data shared across all sessions
export const genericLoader: LoaderFunction = async ({ request }) => {
const data = await fetchGenericData();
return json(data, {
headers: {
"Cache-Control": "public, max-age=3600, s-maxage=86400", // Cache publicly for 1 hour, CDN for 1 day
"Surrogate-Control": "max-age=86400" // Additional CDN-specific caching
}
});
};
// Combined loader example
export const loader: LoaderFunction = async ({ request }) => {
const [sessionData, genericData] = await Promise.all([
fetchSessionData(),
fetchGenericData()
]);
return json(
{
session: sessionData,
generic: genericData
},
{
headers: {
"Cache-Control": "private, max-age=3600",
"Vary": "Cookie",
}
}
);
};
Here's what each approach does:
For session-specific data:
private ensures the response is cached per-user
Vary: Cookie makes sure different users get different cached versions
max-age=3600 caches for 1 hour
For generic data:
public allows caching by browsers and CDNs
s-maxage lets CDNs cache longer than browsers
No Vary: Cookie since it's the same for all users
You can adjust the cache durations by modifying the max-age values.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment