Apps Script doPost 302 Redirect: Why Webhooks Fail and the Fix
An Apps Script web app answers webhook POSTs with a 302 redirect, so senders that never follow redirects mark the delivery failed. Here is why, and a small verified relay that fixes it.
By AyeWatch Team5 min read
Short answer: An Apps Script web app answers a POST to its /exec URL with a 302 redirect to script.googleusercontent.com, because Google serves the output from a one-time URL. A webhook sender that does not follow redirects marks the delivery failed. The fix is a small receiver in front that answers 200 itself and forwards the body to Apps Script.
Why Apps Script answers with a 302
Google's Content service docs say it directly: for security, content returned by the Content service is redirected to a one-time URL at script.googleusercontent.com. Google runs your doPost first, then hands the caller a 302 that points at the output. A browser follows it without you noticing. curl shows the 302 unless you add -L.
You cannot change this from inside the script. The TextOutput object that doPost returns has methods for content, MIME type and file name, and none for a status code or a header. There is no way to answer a plain 200.
Two other details cause the same symptom. The /dev URL only works for people with edit access, so senders must use the deployed URL that ends in /exec. And if the deployment is not open to anyone, Google sends unsigned callers a redirect to a sign-in page, and doPost never runs.
What this means for AyeWatch
AyeWatch never follows a redirect. A 3xx answer fails the delivery at once, and it is not retried. Point AyeWatch at an /exec URL and every alert is marked failed. Because Google ran doPost before redirecting, the row may still be in your sheet. When doPost does break, though, nothing tries again.
There is a second problem. The doPost(e) event object has e.parameter, e.queryString, e.contentLength and e.postData, whose contents is the body text. It has no request headers. Apps Script can compute an HMAC with Utilities.computeHmacSha256Signature, but it cannot see X-AyeWatch-Signature to compare against. Both problems go away with a receiver in front.
The fix: a relay that answers 200 and forwards
This Cloudflare Worker gets the raw body, checks the signature, forwards the same bytes to your /exec URL with a shared token, follows Google's redirect to read the output, and answers AyeWatch with 200 only when the script replied ok. Store AYEWATCH_SECRET, APPS_SCRIPT_URL and RELAY_TOKEN as Worker secrets.
async function verify(raw, header, secret) {
const hex = header.startsWith("sha256=") ? header.slice(7) : "";
if (!/^[0-9a-f]{64}$/.test(hex)) return false;
const sig = new Uint8Array(32);
for (let i = 0; i < 32; i++) sig[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"]
);
return crypto.subtle.verify("HMAC", key, sig, raw);
}
export default {
async fetch(request, env) {
if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
const raw = await request.arrayBuffer();
const header = request.headers.get("X-AyeWatch-Signature") || "";
if (!(await verify(raw, header, env.AYEWATCH_SECRET))) {
return new Response("Bad signature", { status: 401 });
}
const url = env.APPS_SCRIPT_URL + "?token=" + encodeURIComponent(env.RELAY_TOKEN);
try {
// fetch follows the 302 and reads the script's output from googleusercontent.com
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: raw,
signal: AbortSignal.timeout(8000),
});
const text = (await res.text()).trim();
if (res.ok && text === "ok") return new Response("ok");
return new Response("Apps Script answered: " + text.slice(0, 200), { status: 502 });
} catch {
return new Response("Apps Script did not answer in time", { status: 504 });
}
},
};
A 502 or 504 tells AyeWatch to retry with backoff, and the retry carries the same update_id. The 8-second limit leaves room inside AyeWatch's 10 seconds. The Workers guide has the deploy commands.
The doPost side: token, dedupe, then the row
The script checks the token, skips an update_id it has seen, and appends the row. Save RELAY_TOKEN and SHEET_ID under Project Settings, Script Properties.
function doPost(e) {
var props = PropertiesService.getScriptProperties();
if (e.parameter.token !== props.getProperty("RELAY_TOKEN")) {
return ContentService.createTextOutput("forbidden");
}
var alert = JSON.parse(e.postData.contents);
var cache = CacheService.getScriptCache();
var key = "u" + alert.update_id;
if (cache.get(key)) return ContentService.createTextOutput("ok");
SpreadsheetApp.openById(props.getProperty("SHEET_ID"))
.getSheetByName("Alerts")
.appendRow([alert.created_at, alert.topic_name, alert.headline || "", alert.content || "", alert.update_id]);
cache.put(key, "1", 21600);
return ContentService.createTextOutput("ok");
}
The dedupe lives here, next to the write, because of one edge case: the script can finish just after the Worker gives up, and the retry then finds the cached update_id instead of adding a second row. The script cache keeps a key for at most six hours and can drop it sooner, so keep update_id in its own column as a backstop. The Sheets change log guide has the column layout.
Limits and other routes
- Apps Script quotas. One execution can run for six minutes at most, and a user can have 30 running at once. Alerts are small, so this rarely matters.
- Two hops. If Google is slow, the Worker answers 504 and AyeWatch tries later.
- The token is a second secret. Anyone with the
/execURL and the token can add rows. Keep both out of chats and repositories. - No code at all. Make, Zapier and n8n each have a Google Sheets step behind their own webhook trigger. AyeWatch has no Sheets integration of its own.
AyeWatch Pro is $9/mo with 50 topics and hourly checks; Pro+ is $19/mo with 200 topics and ASAP mode. Every plan starts with a 7-day free trial. Five web page monitors checked twice a day at 1 credit a check use 5 × 60 = 300 credits a month. Cloudflare's free Workers plan covers the relay.
Fix a failing Apps Script webhook
- Paste the doPost above into the script bound to your sheet, add an Alerts tab, and set the two Script Properties.
- Deploy it as a web app that runs as you and that anyone can access. Copy the URL that ends in
/exec. - Deploy the Worker with
AYEWATCH_SECRET,APPS_SCRIPT_URLandRELAY_TOKENas secrets. - In AyeWatch, open Notification settings, Webhook, paste the Worker URL, not the Apps Script URL, and select Save Webhook. Reveal the signing secret and store it in the Worker.
- Wait for a real update and check that a row appears and the Worker log shows a 200.
| Caller | What it gets from /exec | Result |
|---|---|---|
| AyeWatch, pointed at /exec | 302 to script.googleusercontent.com | Delivery failed at once, no retry |
| curl without -L | 302 and an HTML page | Looks broken, though doPost ran |
| Worker relay (fetch follows redirects) | 302, then the script's ok text | Worker answers AyeWatch 200 |
| Caller to a deployment not open to anyone | 302 to a Google sign-in page | doPost never runs |
Start a monitor in under a minute
Describe a topic or paste a URL. Cancel before the trial ends and you pay nothing.
Try it free for 7 daysThe bottom line
The 302 is how Apps Script web apps work, not a bug you can fix in the script. Put the Worker in front, keep the dedupe next to the write, and AyeWatch gets the clean 200 it needs.
FAQ
Why does my Apps Script doPost return a 302?
Google serves Content service output from a one-time URL at script.googleusercontent.com, so every web app answer is a 302 to that URL. Callers that follow redirects see the output; others see the 302.
Can an Apps Script web app return a 200 status code?
No. TextOutput has no method for a status code or headers. The relay in front answers 200 for it.
Can doPost read request headers?
No. The event object has parameters, the query string and the POST body, but no headers, so it cannot read a signature header.
Does doPost still run when the caller sees a 302?
Yes, for an /exec deployment open to anyone. Google runs doPost and then redirects to its output. That is why rows can appear while the sender reports a failure.
Why does AyeWatch not just follow the redirect?
AyeWatch never follows redirects for webhooks and treats a 3xx as a failed delivery with no retry. Give it a URL that answers 2xx directly.