Fix Broken Media Links From Expired fal.ai & Replicate URLs
HTTP 403 Forbidden / 404 Not Found on https://replicate.delivery/xezq/... or https://v3.fal.media/files/... | S3 XML: <Code>AccessDenied</Code><Message>Request has expired</Message> | Remotion / FFmpeg: Server returned 403 Forbidden Your generated AI videos, thumbnails, and product images render and load perfectly immediately after an API job completes, yet break with HTTP 403/404 errors an hour later (on Replicate) or days later (on fal.ai, Gemini Files API, Runway, and Kling)—crashing live galleries, client review links, and scheduled Remotion renders.
Inference providers serve generated outputs from ephemeral signed object-storage URLs with strict retention windows (1 hour on Replicate replicate.delivery, hours to days on fal.media and Gemini/Veo download URIs)—never intended to act as a permanent production CDN.
Copy-Paste Verified Fix
#!/usr/bin/env bash
set -euo pipefail
# Usage: ./ingest-ephemeral-media.sh <ephemeral_url> <local_archive_dir> [s3_or_r2_uri]
# Example: ./ingest-ephemeral-media.sh "https://v3.fal.media/files/..." ./archive "s3://my-media-bucket/renders"
URL="${1:?Provide temporary fal.ai / Replicate / Veo output URL}"
ARCHIVE_DIR="${2:-./media-archive}"
REMOTE_URI="${3:-}"
mkdir -p "$ARCHIVE_DIR"
TMP_FILE="$(mktemp "$ARCHIVE_DIR/.ingest_XXXXXX.tmp")"
trap 'rm -f "$TMP_FILE"' EXIT
# 1. Download immediately with fail-on-HTTP-error (-f) and inspect Content-Type + HTTP code
META="$(curl -fsSL --retry 3 --retry-delay 2 --max-time 180 \
-o "$TMP_FILE" -w '%{http_code} %{content_type} %{size_download}' "$URL")"
read -r HTTP_CODE CONTENT_TYPE BYTES <<< "$META"
if [[ "$HTTP_CODE" != "200" ]] || (( BYTES < 4096 )); then
echo "ERROR: Invalid download (HTTP=$HTTP_CODE, bytes=$BYTES, type=$CONTENT_TYPE)" >&2
exit 1
fi
# Guard against expired S3/R2 XML or HTML error pages saved as .mp4/.png
if [[ "$CONTENT_TYPE" =~ (xml|html|json|text/plain) ]]; then
echo "ERROR: Refusing to archive non-media response (Content-Type=$CONTENT_TYPE)" >&2
head -c 240 "$TMP_FILE" >&2
exit 1
fi
# 2. Pick clean extension from MIME type and content-address with SHA-256
case "$CONTENT_TYPE" in
*video/mp4*) EXT="mp4" ;;
*video/webm*) EXT="webm" ;;
*image/png*) EXT="png" ;;
*image/webp*) EXT="webp" ;;
*image/jpeg*) EXT="jpg" ;;
*audio/mpeg*) EXT="mp3" ;;
*audio/wav*|*audio/x-wav*) EXT="wav" ;;
*) EXT="bin" ;;
esac
SHA256="$(shasum -a 256 "$TMP_FILE" | awk '{print $1}')"
FINAL_LOCAL="$ARCHIVE_DIR/${SHA256:0:16}.${EXT}"
mv "$TMP_FILE" "$FINAL_LOCAL"
# 3. Verify valid media container with ffprobe (catches truncated streams immediately)
if command -v ffprobe >/dev/null 2>&1 && [[ "$EXT" =~ ^(mp4|webm|mp3|wav)$ ]]; then
ffprobe -v error -show_entries format=format_name,duration -of compact=p=0 "$FINAL_LOCAL"
fi
echo "ARCHIVED_LOCAL=$FINAL_LOCAL (sha256=${SHA256:0:16}, bytes=$BYTES, type=$CONTENT_TYPE)"
# 4. Optional durable upload to Cloudflare R2 (via --endpoint-url) or AWS S3
if [[ -n "$REMOTE_URI" ]]; then
AWS_ARGS=()
if [[ -n "${R2_ENDPOINT_URL:-}" ]]; then
AWS_ARGS+=(--endpoint-url "$R2_ENDPOINT_URL")
fi
aws "${AWS_ARGS[@]}" s3 cp "$FINAL_LOCAL" "${REMOTE_URI%/}/${SHA256:0:16}.${EXT}" \
--content-type "$CONTENT_TYPE" \
--cache-control "public, max-age=31536000, immutable"
echo "ARCHIVED_REMOTE=${REMOTE_URI%/}/${SHA256:0:16}.${EXT}"
fi Before vs. After (Broken Pattern vs. Verified Fix)
// Replicate URL expires in 1 hour; fal/Veo signed links expire on vendor retention:
await db.assets.insert({
shotId: 'S01',
videoUrl: prediction.output[0], // "https://replicate.delivery/xezq/.../out.mp4" -> 404 in 60 min!
}); // 1. Stream download immediately on completion; reject XML error bodies (check Content-Type + bytes)
// 2. Validate MP4/PNG/WAV container cleanly with ffprobe before accepting
// 3. Upload content-addressed key (sha256.mp4) to owned Cloudflare R2 / AWS S3 bucket
// 4. Persist ONLY permanent owned URL: "https://media.yourdomain.com/renders/<sha256>.mp4" Why this works: Ingesting outputs straight into content-addressed owned storage (Cloudflare R2 has $0 egress fees) guarantees permanent URLs for Remotion, web galleries, and client deliverables with zero vendor expiry risk.
Why This Failure Happens in Real Pipelines
When developers prototype an AI media pipeline with Replicate, fal.ai, Google Gemini Omni 1.2 Flash, Tripo 3D (7-day asset retention), or Runway, the JSON response hands back a crisp HTTPS link like https://replicate.delivery/.../output.mp4 or https://v3.fal.media/files/.../video.mp4. Saving that URL directly into a Postgres media column, headless CMS entry, n8n sheet, or Remotion inputProps JSON works flawlessly during same-minute local testing, hiding a ticking expiration bomb.
Replicate explicitly purges standard API prediction outputs from replicate.delivery after 1 hour; Tripo 3D deletes generated 3D assets after 7 days; Google Gemini File download links carry short-lived authorization tokens; and hosted aggregators rotate signed buckets or enforce retention policies that silently return HTTP 403 AccessDenied XML or 404 Not Found after expiry. Worse, when an automated curl or fetch download script fails to check response status or Content-Type headers, it silently writes a 340-byte XML AccessDenied error document straight into shot01.mp4—which then crashes FFmpeg or Remotion hours later with cryptic "Invalid data found when processing input" errors.
The permanent architectural rule is simple: treat every provider output URL as a one-time ephemeral transfer ticket, NEVER as a persisted asset URL. The instant a job hits status === "completed", stream the bytes directly into your own durable storage (local studio archive plus Cloudflare R2, AWS S3, or Google Cloud Storage behind your own domain), verify HTTP 200, validate Content-Type and minimum byte size, hash the file with SHA-256, confirm container health with ffprobe, and write ONLY your immutable owned CDN URL into databases and render manifests.
Step-by-Step Resolution & Verification
- 01
Audit existing manifests, CMS tables, and codebases for ephemeral provider domains
Search your repository and database exports for replicate.delivery, fal.media, generativelanguage.googleapis.com, and X-Amz-Expires query strings to locate every fragile URL before it expires.
- 02
Wire immediate download, MIME verification, and ffprobe checks into every webhook or poller
Invoke ingest-ephemeral-media.sh (or an equivalent S3 SDK streaming putObject) immediately upon job completion so temporary URLs are consumed within seconds and never written to production columns.
- 03
Serve archived media from content-addressed Cloudflare R2 or S3 with immutable caching
Store files by SHA-256 prefix with Cache-Control: public, max-age=31536000, immutable so Remotion workers, client review portals, and storefronts enjoy permanent high-speed delivery with zero egress surprises.
grep -rnE 'https://(replicate\.delivery|[a-z0-9.-]*fal\.media|generativelanguage\.googleapis\.com/.*files|.*X-Amz-Expires=)' ./src ./render-manifest.json 2>/dev/null || echo "CLEAN: zero ephemeral provider URLs stored" CLEAN: zero ephemeral provider URLs stored # Every saved asset must resolve to owned R2/S3/local paths How to Prevent This Error From Recurring
Enforce a database or Zod schema rejection on ephemeral provider hostnames
Reject any write attempting to store replicate.delivery or fal.media inside a permanent asset_url column so regressions fail loudly during development.
Always check HTTP 200 and Content-Type before writing downloaded bytes to disk
Without -f and MIME validation, expired signed links save 300-byte XML AccessDenied error payloads under .mp4 filenames that silently poison downstream FFmpeg concat batches.
Choose Cloudflare R2 or zero-egress object storage for heavy video pipelines
Remotion batch renders and client review portals download large MP4 intermediates repeatedly; R2 eliminates bandwidth bill spikes compared to raw public S3 egress.
Troubleshooting FAQs
- How long do Replicate replicate.delivery output URLs actually stay alive?
- Replicate documents that API prediction output files on replicate.delivery are automatically deleted after 1 hour. Any production app or Remotion render referencing a replicate.delivery URL directly will break with HTTP 404 sixty minutes after generation.
- Can I stream a fal.ai or Replicate output straight into S3 or R2 inside a webhook without touching disk?
- Yes. Inside Node.js, fetch the ephemeral URL, verify res.ok and a video/image/audio content-type header, read the buffer or ReadableStream, and upload directly with @aws-sdk/client-s3 PutObjectCommand (pointing endpoint to your Cloudflare R2 or S3 bucket) before acknowledging the webhook.
- Why did FFmpeg say "Invalid data found when processing input" on a freshly downloaded clip?
- When curl runs without -f (--fail) against an expired signed URL, it saves the 300-byte HTTP 403 XML AccessDenied response body straight into output.mp4. Running head -c 200 output.mp4 reveals the XML error immediately; always pass curl -fsSL and validate Content-Type.
- Do Google Gemini Omni Flash download URIs (and legacy Vertex AI Veo links) also require immediate archiving?
- Yes. Gemini API file download URIs (for Gemini Omni 1.2 Flash, which replaced Veo 3.1 in the Gemini API on October 22, 2026) and Vertex AI Veo signed URLs expire on short retention windows. Download completed MP4s immediately into your local archive or GCS/R2 bucket and run ffprobe to confirm duration and audio tracks.
- What happens if a webhook fires twice for the same completed video job?
- Because the ingest script content-addresses assets by SHA-256 hash (or deterministic shot_hash), duplicate webhook deliveries overwrite the exact same object key idempotently with zero duplicate storage clutter.