In-Memory Caching
Using a JavaScript variable, values can be cached in-memory for use in subsequent requests. Note that multiple instances of scripts process requests based on where the requests are coming from, and each instance will have its own separate memory space. Generally, scripts will remain active and running as long as they continue to see traffic.
This script utilizes in-memory caching between requests to create and store an OAuth Token.
// Cached token between requests
let token;
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
// If the token is not set yet, get one
if (!token) {
try {
await fetchAndSetToken();
} catch (e) {
return new Response("Failed to get token", {
status: 500
});
}
}
// Get stackId and siteId from request search
const url = new URL(request.url);
const stackId = url.searchParams.get("stackId");
const siteId = url.searchParams.get("siteId");
// See https://developer.stackpath.com/en/api/cdn/#operation/GetSiteScripts
return fetch(
`https://gateway.stackpath.com/cdn/v1/stacks/${stackId}/sites/${siteId}/scripts`,
{
headers: { authorization: token }
}
);
}
// See https://developer.stackpath.com/docs/en/getting-started/
const CLIENT_ID = "CLIENT_ID";
const CLIENT_SECRET = "CLIENT_SECRET";
// Create an oauth token and set the token variable
async function fetchAndSetToken() {
let tokenResp = await fetch(
"https://gateway.stackpath.com/identity/v1/oauth2/token",
{
method: "POST",
body: JSON.stringify({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: "client_credentials"
}),
headers: {
"Content-Type": "application/json"
}
}
);
// Leave token as is if another request fetched it at the same time and finished first
if (!token) {
if (!tokenResp.ok) {
throw new Error("Failed to retrieve token");
}
const { token_type, access_token, expires_in } = await tokenResp.json();
token = `${token_type} ${access_token}`;
// Get a new token a minute before the current token is set to expire
setTimeout(() => {
fetchAndSetToken();
}, Math.max(expires_in * 1000 - 60000, 0));
}
}
Updated 5 months ago
What’s Next