Skip to content

Instantly share code, notes, and snippets.

@MicahZoltu
Created March 11, 2024 03:04
Show Gist options
  • Save MicahZoltu/742d985d0878fbcbdbffbed8b4aca200 to your computer and use it in GitHub Desktop.
Save MicahZoltu/742d985d0878fbcbdbffbed8b4aca200 to your computer and use it in GitHub Desktop.
Standard Notes CloudFlare Proxy
export default {
/**
* @param {Request} request
*/
async fetch(request) {
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
};
/**
* @param {Request} request
*/
async function handleRequest(request) {
// Rewrite request to point to API URL. This also makes the request mutable so you can add the correct Origin header to make the API server think that this request is not cross-site.
const newUrl = new URL(request.url)
newUrl.hostname = 'api.standardnotes.com/'
const newRequest = new Request(newUrl.toString(), request);
newRequest.headers.set('Origin', 'https://app.standardnotes.com');
let response = await fetch(newRequest);
// Recreate the response so you can modify the headers
response = new Response(response.body, response);
// Set CORS headers
response.headers.set("Access-Control-Allow-Origin", request.headers.get("Origin"));
// Append to/Add Vary header so browser will cache response correctly
response.headers.append("Vary", "Origin");
return response;
}
/**
* @param {Request} request
*/
async function handleOptions(request) {
if (
request.headers.get("Origin") !== null &&
request.headers.get("Access-Control-Request-Method") !== null &&
request.headers.get("Access-Control-Request-Headers") !== null
) {
// Handle CORS preflight requests.
return new Response(null, {
headers: {
...corsHeaders,
"Access-Control-Allow-Headers": request.headers.get(
"Access-Control-Request-Headers"
),
},
});
} else {
// Handle standard OPTIONS request.
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
});
}
}
if (request.method === "OPTIONS") {
// Handle CORS preflight requests
return handleOptions(request);
} else if (
request.method === "GET" ||
request.method === "HEAD" ||
request.method === "POST"
) {
// Handle requests to the API server
return handleRequest(request);
} else {
return new Response(null, {
status: 405,
statusText: "Method Not Allowed",
});
}
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment