How to work around the "Unexpected error" in Google Apps Script's UrlFetchApp.fetch()

Tim Hanlon

Some time last week, Google started having some issues with CSV files, impacting the IMPORTDATA function of Google Sheets and the UrlFetchApp.fetch function of Google Apps Script.

At the time of writing, the IssueTracker for this issue has 739 stars.

We're using a simple Cloudflare Worker to work around the issue in one of our published add-ons, which uses UrlFetchApp.fetch.

Here is the source of our worker:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  const { searchParams } = new URL(request.url)
  const csvUrl = searchParams.get('csvUrl')
  const response = await fetch(csvUrl)
  const text = await response.text()
  return new Response(text)
}

And our Apps Script:

var workaroundUrl = 'https://replace-this-with-your-worker-url.workers.dev?csvUrl='+encodeURIComponent(csvUrl);
var csvContent = UrlFetchApp.fetch(workaroundUrl, options).getContentText();
var csvData = Utilities.parseCsv(csvContent);
© twofutures Pty Ltd 2020