I've been in the dev game long enough that I often forget CORS is still a major roadblock. Then I browse Reddit or StackOverflow and realize it's still the #1 hurdle for new developers.
CORS (Cross-Origin Resource Sharing) is a 4-letter acronym for a security feature that is actually "the good guy." It prevents malicious sites from acting on your behalf. But when you're trying to fetch public data from an API that hasn't enabled the right headers, it feels like a brick wall.
If you don't control the target server, you can't "fix" CORS. But you can route around it. Since Google Apps Script (GAS) runs on Google's servers, it acts as a neutral third party not bound by browser origin restrictions.
The Backend (GAS)
function doGet(e) {
const targetUrl = decodeURIComponent(e.queryString);
const response = UrlFetchApp.fetch(targetUrl);
return ContentService.createTextOutput(response.getContentText());
}
The Frontend
const proxyFetch = async(url) => {
const loc = `https://script.google.com/macros/s/YOUR_ID/exec?${encodeURIComponent(url)}`;
const res = await fetch(loc);
return await res.text();
}
Method 2: The "JSONP" Evolution (Bypassing CSP)
Strict Content Security Policies (CSP) can block fetch calls even if the target has CORS enabled. Historically, we used JSONP to bypass this by loading data as a <script>. We can do a modern version of this using ES Modules.
The Backend (GAS)
function doGet(e) {
const payload = UrlFetchApp.fetch(decodeURIComponent(e.queryString)).getBlob().getBytes();
return ContentService.createTextOutput(
`export const payload = '${Utilities.base64Encode(payload)}';`
).setMimeType(ContentService.MimeType.JAVASCRIPT);
}
The Frontend
async function proxyImport(url){
const loc = `https://script.google.com/macros/s/YOUR_ID/exec?${encodeURIComponent(url)}`;
const res = await import(loc);
return atob(res.payload);
}
Why This Works
- CORS Bypass: The request happens on Google's IP, not yours.
- CSP Bypass: Serving data as MimeType.JAVASCRIPT lets it pass through security layers that allow script imports but block data connections.
- Binary Friendly: Base64 encoding allows you to move images or small PDFs without corruption.
Top comments (0)