I’m trying to connect a React form to a Google Apps Script web app, but I’m getting CORS errors:
Access to fetch at 'https://script.google.com/macros/s/SCRIPT_ID/exec' from origin 'http://localhost:5173' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My Setup
Google Apps Script (backend):
function doPost(e) {
try {
const formData = JSON.parse(e.postData.contents);
// Save to Google Sheets
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
sheet.appendRow([new Date(), formData.name, formData.email]);
return ContentService.createTextOutput(
JSON.stringify({ success: true })
).setMimeType(ContentService.MimeType.JSON);
} catch(error) {
return ContentService.createTextOutput(
JSON.stringify({ success: false, error: error.message })
).setMimeType(ContentService.MimeType.JSON);
}
}
React (frontend):
const handleSubmit = async (formData) => {
try {
const response = await fetch('https://script.google.com/macros/s/SCRIPT_ID/exec', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
const result = await response.json();
return result;
} catch(error) {
console.error('Submission failed:', error);
}
}
What I’ve Tried:
1. Setting mode: ‘no-cors’
This makes the request go through but I can’t read the response.
2. Adding CORS headers in Apps Script
Tried using HtmlService with setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL) but still getting errors.
3. Creating a proxy API
Works but adds complexity – would prefer direct connection if possible.
Question:
How can I properly handle CORS when connecting React directly to a Google Apps Script web app?
- Is there a way to configure Apps Script to accept cross-origin requests?
- Are there any workarounds that still allow reading the response?
- What’s the most reliable production solution?
Why This is Different From Other Questions:
Most solutions suggest using no-cors mode or a proxy server, but:
- no-cors prevents reading responses
- Proxy adds latency and another point of failure
I’m looking for a way to make direct requests work properly with CORS.