One of the biggest strengths of Google Apps Script is how easily it interacts with other Google products. Reading a Google Sheet, creating a Drive file, or updating a document requires almost no setup. You don’t have to think about authentication, token management, or security flows. Google automatically prompts the required scopes and takes care of the authorization for you.
This convenience can make OAuth feel invisible, even unnecessary. Until the day your script needs to talk to something outside Google.
This article takes a step back to explain what OAuth and OAuth 2.0 actually are, why Apps Script usually hides them from you, and what changes when you integrate external services. We’ll also look at how the OAuth2 library fits into the picture when built-in authorization is no longer enough.
OAuth in simple terms
OAuth 2.0 allows an application to access a user’s data without ever handling their password. Instead of sharing credentials, the user approves a limited set of permissions, and the service issues a token representing what the application is allowed to do and for how long.
In an OAuth flow, the user authenticates directly with the service that owns the data. Once consent is given, the service provides a token to the application. From that point on, the application uses this token to make requests, and the service validates it before allowing access. The application never sees the user’s credentials.
OAuth 2.0 is an evolution of the original OAuth concept. It formalizes this permission model using short-lived access tokens and refresh tokens, making integrations more secure, easier to revoke, and better suited to modern applications. Today, when we talk about OAuth, we almost always mean OAuth 2.0.
OAuth in Apps Script
When an Apps Script project interacts only with Google products, OAuth is handled entirely by the platform. Permissions are inferred from the services you use, Google displays the consent screen, and tokens are stored and refreshed automatically. In this context, we don’t really htink about OAuth at all.
You can see the project scopes in the information panel
This changes as soon as your script needs to communicate with a service outside Google.
Most external APIs rely on OAuth 2.0, which means your script must explicitly request user consent, obtain access tokens, refresh them when they expire, and attach them to API requests. At this point, OAuth is no longer automatic and becomes part of your implementation.
To make this manageable, Apps Script relies on a community OAuth2 library. The library implements the OAuth 2.0 protocol for you, handling redirects, callbacks, token exchanges, storage, and refresh logic. You configure it once, then reuse it whenever your script needs to authenticate with the external API.
How the OAuth2 library works in Apps Script
The OAuth2 library revolves around the idea of a service. A service represents a configured OAuth connection to an external provider. It contains everything needed to authenticate with that API:
Authorization URL This is the endpoint where the user is redirected to grant consent. It displays the provider’s login and consent screen and is the entry point of the OAuth flow.
Token endpoint This endpoint is used after consent is granted. It exchanges the authorization code for an access token (and usually a refresh token), and is also used later to refresh expired access tokens.
Client credentials (Client ID and Client Secret) These identify your Apps Script project to the OAuth provider. They are issued when you register your application and allow the provider to trust who is requesting tokens.
Requested scopes Scopes define what the application is allowed to do. They limit access to specific actions or resources and are shown to the user on the consent screen.
Callback function This is the function Apps Script calls after the provider redirects back to your project. It completes the OAuth flow by handing the response to the library, which then retrieves and stores the tokens.
Property store This defines where access and refresh tokens are persisted. The service uses PropertiesService to store tokens so the user does not need to re-authorize on every execution.
In short, the service is the OAuth contract between Apps Script and an external provider. Once configured, your code no longer deals with OAuth mechanics directly, it simply asks the service for a valid access token and makes API requests.
A short example
The first step is to add the OAuth2 library to your Apps Script project. This can be done by searching for the library using its script ID:
/**
* Creates and returns the OAuth2 service.
* @returns {OAuth2.Service}
*/
function getService_() {
return OAuth2.createService('MyApi')
// Authorization and token endpoints provided by the API
.setAuthorizationBaseUrl('https://example.com/oauth/authorize')
.setTokenUrl('https://example.com/oauth/token')
// Credentials issued by the provider
.setClientId('YOUR_CLIENT_ID')
.setClientSecret('YOUR_CLIENT_SECRET')
// Callback function called after user consent
.setCallbackFunction('authCallback')
// Where tokens are stored
.setPropertyStore(PropertiesService.getUserProperties())
// Permissions requested
.setScope('read write');
}
Apps Script cannot redirect automatically, so you typically show the authorization URL as a link.
/**
* Shows an authorization link if access is missing.
*/
function authorize() {
const service = getService_();
if (!service.hasAccess()) {
const url = service.getAuthorizationUrl();
Logger.log('Authorize this app by visiting: %s', url);
}
}
This function is called by Apps Script when the provider redirects back after consent.
Once authorized, the library automatically returns a valid token and refreshes it if needed.
/**
* Makes an authenticated API request.
*/
function callApi() {
const service = getService_();
if (!service.hasAccess()) {
throw new Error('Service not authorized');
}
const response = UrlFetchApp.fetch('https://example.com/api/data', {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
Logger.log(response.getContentText());
}
Conclusion
OAuth can feel complex at first, but in practice it follows a simple idea: allowing an application to act on behalf of a user without ever handling their credentials. In Google Apps Script, this complexity is often hidden when working with Google services, which is why OAuth can go unnoticed for a long time.
As soon as you integrate an external API, OAuth becomes explicit. The OAuth2 library provides a structured and reliable way to handle authorization, token storage, and refresh logic, without forcing you to reimplement the OAuth 2.0 protocol yourself. Once the service is configured, the rest of your code can focus purely on business logic and API interactions.
To go further, see the follow-up article with a complete OAuth2 implementation in Apps Script using Xero.
If you use Xero and Google Sheets on a daily basis, this automation tutorial is for you. In this post, you’ll learn how to automatically sync your Xero bills into a Google Sheet on a schedule, so your spending table stays up to date without copy-pasting.
We’ll build it in a production-friendly way: OAuth2 authorization (so Xero can securely grant access), safe credential storage in Apps Script, a sync function that writes into your sheet, and refresh tokens (via offline_access) so the automation keeps running long-term.
Create a Xero OAuth2 app
Create a Xero OAuth2 app in the Xero Developer portal and choose the web app / Standard auth code type (the standard flow Xero documents for third-party apps).The standard authorization code flow
The most important field is Redirect URI. Xero requires an exact, absolute redirect URI (no wildcards), so we will need the exact callback URL generated by your Apps Script project. Xero API – OAuth 2.0
Get a temporary redirect URI to create the app
In Apps Script, the OAuth2 library can generate the exact redirect URI for this project. Run the function below, copy the URL from the logs, and paste it into your Xero app settings to finish creating the app.
/**
* Logs the Redirect URI you must paste into your Xero app settings.
* This does NOT require Client ID/Secret.
*
* @returns {void}
*/
function logXeroRedirectUri() {
const service = OAuth2.createService('Xero')
.setCallbackFunction('xeroAuthCallback');
Logger.log(service.getRedirectUri());
}
/**
* OAuth callback endpoint (stub is fine for this step).
* @param {Object} e
* @returns {GoogleAppsScript.HTML.HtmlOutput}
*/
function xeroAuthCallback(e) {
return HtmlService.createHtmlOutput('Callback ready.');
}
The Apps Script OAuth2 library is the standard way to handle OAuth consent and token refresh in Apps Script. (Link to the setup guide here).
Get and store Client ID / Client Secret in Script Properties
Once the app is created, copy the Client ID and Client Secret. You’ll need them in Apps Script to complete the OAuth flow.
Store only the Client ID and Client Secret in Script Properties. OAuth tokens are user-specific, so we store them in User Properties via the OAuth2 library’s property store.
Replace the temporary callback with the real OAuth service + callback
Now that we have Client ID/Secret stored, we can build the real OAuth service and the real callback that stores tokens.
Important: tokens are user-specific, so we store them in User Properties via .setPropertyStore(PropertiesService.getUserProperties()).
Let’s replace the previous xeroAuthCallback() with this version:
/**
* Creates and returns the OAuth2 service configured for Xero.
* Client ID/Secret are in Script Properties; OAuth tokens are stored per-user in User Properties.
*
* @returns {OAuth2.Service}
*/
function getXeroService_() {
const { clientId, clientSecret } = getXeroCredentials_();
return OAuth2.createService('Xero')
.setAuthorizationBaseUrl('https://login.xero.com/identity/connect/authorize')
.setTokenUrl('https://identity.xero.com/connect/token')
.setClientId(clientId)
.setClientSecret(clientSecret)
.setCallbackFunction('xeroAuthCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setLock(LockService.getUserLock())
.setScope([
'openid',
'profile',
'email',
'offline_access',
'accounting.transactions',
].join(' '))
.setTokenHeaders({
Authorization: 'Basic ' + Utilities.base64Encode(`${clientId}:${clientSecret}`),
});
}
/**
* OAuth callback endpoint called by Xero after consent.
* This stores the access token + refresh token in the OAuth2 property store.
*
* @param {Object} e
* @returns {GoogleAppsScript.HTML.HtmlOutput}
*/
function xeroAuthCallback(e) {
const service = getXeroService_();
const ok = service.handleCallback(e);
return HtmlService.createHtmlOutput(ok ? 'Success! You can close this tab.' : 'Denied');
}
Authorize once
This is a one-time consent step: generate the authorization URL, open it in your browser, click Allow, then Xero redirects back to xeroAuthCallback() to finalize the connection.
You must request offline_access to receive a refresh token. Xero Developer – Offline access Xero’s docs also note refresh tokens expire after a period (so if the integration stops running for too long, you may need to re-authorize).
/**
* Returns the Xero consent screen URL. Open it and approve access.
*
* @returns {string}
*/
function getXeroAuthorizationUrl_() {
const service = getXeroService_();
return service.getAuthorizationUrl();
}
/**
* Logs the authorization URL in Apps Script logs.
*
* @returns {void}
*/
function logXeroAuthorizationUrl_() {
Logger.log(getXeroAuthorizationUrl_());
}
Run logXeroAuthorizationUrl_(), copy the logged URL, open it, and approve access. After that, your script can call Xero without prompting again.
Sync bills into Sheets (then add a trigger)
Xero is multi-tenant: first call the Connections endpoint to get a tenantId, then include xero-tenant-id in every API request. For incremental sync, use the If-Modified-Since header so each run only pulls bills modified since your last sync timestamp.
const XERO_API_BASE_ = 'https://api.xero.com/api.xro/2.0';
const XERO_BILLS_SHEET_ = 'Xero Bills';
/**
* Resolves the active tenant ID from Xero connections.
*
* @param {OAuth2.Service} service
* @returns {string}
*/
function getXeroTenantId_(service) {
const res = UrlFetchApp.fetch('https://api.xero.com/connections', {
method: 'get',
headers: { Authorization: `Bearer ${service.getAccessToken()}` },
muteHttpExceptions: true,
});
if (res.getResponseCode() !== 200) {
throw new Error(`Failed to resolve tenant. ${res.getResponseCode()} — ${res.getContentText()}`);
}
const tenants = JSON.parse(res.getContentText());
const tenantId = tenants?.[0]?.tenantId;
if (!tenantId) throw new Error('No tenant connected to this token.');
return tenantId;
}
/**
* Performs a JSON request to Xero with common headers.
*
* @param {"get"|"post"|"put"|"delete"} method
* @param {string} url
* @param {Object|null} body
* @param {{ ifModifiedSinceIso?: string }} [opts]
* @returns {{code: number, text: string, json?: Object}}
*/
function xeroJsonRequest_(method, url, body, opts = {}) {
const service = getXeroService_();
if (!service.hasAccess()) throw new Error('Xero access not granted. Run the authorization flow first.');
const tenantId = getXeroTenantId_(service);
/** @type {GoogleAppsScript.URL_Fetch.URLFetchRequestOptions} */
const options = {
method,
headers: {
Authorization: `Bearer ${service.getAccessToken()}`,
'xero-tenant-id': tenantId,
Accept: 'application/json',
...(opts.ifModifiedSinceIso ? { 'If-Modified-Since': opts.ifModifiedSinceIso } : {}),
},
muteHttpExceptions: true,
};
if (body != null) {
options.contentType = 'application/json';
options.payload = JSON.stringify(body);
}
const res = UrlFetchApp.fetch(url, options);
const code = res.getResponseCode();
const text = res.getContentText();
let json;
try {
json = text ? JSON.parse(text) : undefined;
} catch (e) {}
return { code, text, json };
}
/**
* Returns ACCPAY invoices (bills) from Xero.
*
* @param {{ ifModifiedSinceIso?: string }} [params]
* @returns {Array<Object>}
*/
function listBills_(params = {}) {
const where = encodeURIComponent('Type=="ACCPAY"');
const url = `${XERO_API_BASE_}/Invoices?where=${where}`;
const { code, text, json } = xeroJsonRequest_('get', url, null, {
ifModifiedSinceIso: params.ifModifiedSinceIso,
});
if (code !== 200) throw new Error(`Failed to list bills. ${code} — ${text}`);
return /** @type {Array<Object>} */ (json?.Invoices || []);
}
/**
* Upserts bills into a sheet using InvoiceID as the key.
*
* @param {SpreadsheetApp.Sheet} sheet
* @param {Array<Object>} bills
* @returns {void}
*/
function upsertBillsToSheet_(sheet, bills) {
const headers = [
'InvoiceID',
'InvoiceNumber',
'ContactName',
'Status',
'Date',
'DueDate',
'CurrencyCode',
'Total',
'AmountDue',
'UpdatedDateUTC',
];
const current = sheet.getDataRange().getValues();
if (!current.length || current[0].join() !== headers.join()) {
sheet.clear();
sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
}
const data = sheet.getDataRange().getValues();
/** @type {Map<string, number>} */
const rowById = new Map();
for (let r = 2; r <= data.length; r++) {
const id = String(data[r - 1][0] || '');
if (id) rowById.set(id, r);
}
const rowsToAppend = [];
bills.forEach(b => {
const row = [
b.InvoiceID || '',
b.InvoiceNumber || '',
b.Contact?.Name || '',
b.Status || '',
b.Date || '',
b.DueDate || '',
b.CurrencyCode || '',
b.Total ?? '',
b.AmountDue ?? '',
b.UpdatedDateUTC || '',
];
const invoiceId = String(b.InvoiceID || '');
const existingRow = rowById.get(invoiceId);
if (existingRow) {
sheet.getRange(existingRow, 1, 1, headers.length).setValues([row]);
} else {
rowsToAppend.push(row);
}
});
if (rowsToAppend.length) {
sheet.getRange(sheet.getLastRow() + 1, 1, rowsToAppend.length, headers.length).setValues(rowsToAppend);
}
}
/**
* Main sync: pulls bills changed since last sync and writes them into Google Sheets.
*
* @returns {void}
*/
function syncXeroBillsToSheet() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(XERO_BILLS_SHEET_) || ss.insertSheet(XERO_BILLS_SHEET_);
const props = PropertiesService.getScriptProperties();
const lastSyncIso = props.getProperty(XERO_PROPS_.lastSyncIso) || '';
const bills = listBills_({ ifModifiedSinceIso: lastSyncIso || undefined });
upsertBillsToSheet_(sheet, bills);
props.setProperty(XERO_PROPS_.lastSyncIso, new Date().toISOString());
}
/**
* Creates an hourly time-driven trigger for syncXeroBillsToSheet().
*
* @returns {void}
*/
function installXeroBillsTrigger_() {
ScriptApp.newTrigger('syncXeroBillsToSheet')
.timeBased()
.everyHours(1)
.create();
}
A clean first run is: save credentials → run logXeroAuthorizationUrl_() and approve → run syncXeroBillsToSheet() once → run installXeroBillsTrigger_() to automate the sync.
You can now install a simple time-driven trigger on syncXeroBillsToSheet() to keep your spreadsheet up to date automatically. From here, it’s easy to adapt the same structure to pull other Xero data: switch from bills (ACCPAY) to sales invoices (ACCREC), filter only paid documents, or add extra columns depending on what you want to analyse.
Google BigQuery provides a scalable solution for querying and analyzing datasets beyond the practical limits of Google Sheets. Integrating BigQuery with Google Apps Script enables automated reporting, data processing and workflows across Google Workspace and Google Cloud.
While the built-in BigQuery Advanced Service supports straightforward integrations, more specialized workflows may require control over authentication, query execution and result retrieval. For example, an application might use a dedicated service account rather than the executing user’s credentials, or need to handle long-running queries and paginated responses.
BigQueryManager is a lightweight BigQuery utility for Apps Script designed to address these requirements. It supports authentication with the executing Google account or a configured service account, asynchronous query polling, result pagination and optional caching.
This article explains the authentication options, required configuration and implementation, including the considerations involved in choosing between user-based and service-account access.
Auth: What is it and why do we need it?
Authentication (“Auth”) is simply the process of proving who you are. It’s the digital bouncer checking your ID at the door of your Google Cloud project.
In Apps Script, the initial “Review permissions” prompt grants the script the scopes it requests. After authorization, the script can obtain an access token for its effective execution identity, including during eligible installable trigger executions. You do not have to approve every scheduled run.
But OAuth2 with a Service Account is different. Instead of a human clicking “Allow,” we use a Service Account, a “robot” identity. It authenticates by exchanging a cryptographic key for a temporary access pass (a token). This allows the script to prove its own identity without a human ever being involved.
A service account is useful when a workload needs its own Google Cloud identity and a deliberately scoped set of IAM permissions. Here are two situations where it can help:
Independent workload identity: A service account can separate BigQuery authorization from the individual who runs the script. Installable triggers already run without an interactive sign-in, so headless execution alone is not a reason to use one.
Access across projects: The chosen identity can run jobs and read datasets in other projects if it has the necessary IAM permissions. This is not a bypass of project security or billing rules; the query job still runs in the selected BigQuery project.
The OAuth2 Library
For service-account authentication, the script signs a JWT assertion with the account’s private key and exchanges it for a short-lived OAuth2 access token. For the executing user, Apps Script can supply an authorized token directly through ScriptApp.getOAuthToken().
We won’t implement JWT signing ourselves. For service accounts, BigQueryManager uses the open-source OAuth2 for Apps Script library. You only need this dependency if you configure service-account credentials.
If you use a service account, go to Libraries in the Apps Script editor and add this Script ID:
Optional: service-account setup. If you want to run queries with your own Google account, skip this section and leave clientEmail and privateKey unset. Otherwise, create a service account in Google Cloud. For read-only queries, a common starting point is BigQuery Job User on the job-execution project and BigQuery Data Viewer on the datasets or tables being queried. Grant broader roles only when the workload actually needs them.
If you use this key-based OAuth2 implementation, generate a service-account JSON key only where your organization permits key creation. Open it securely and locate client_email and private_key. Service-account keys are sensitive long-lived credentials: restrict access, rotate them as needed and avoid generating them when a keyless alternative is practical.
Never hardcode or publish these credentials. Script Properties keep values out of source code, but they are not a dedicated secrets vault; limit access to the Apps Script project.
In Project Settings > Script Properties, add both of these values only if you want service-account authentication:
Property: privateKey / Value: (Paste the entire key string)
The Script
Before using the script, set BQ_CONFIG.projectId to your BigQuery job-execution project. For the user-authentication fallback, add https://www.googleapis.com/auth/bigquery and https://www.googleapis.com/auth/script.external_request to the existing oauthScopes array in appsscript.json (preserving other required scopes). Your Google account must have the relevant BigQuery IAM permissions. The BigQuery Advanced Service is not required for this REST implementation.
The library handles the following:
Authentication: It uses the current Apps Script execution identity when no service-account properties are configured, or the OAuth2 service-account flow when both properties exist.
Caching: It optionally caches qualifying SELECT results for up to 300 minutes (5 hours) by default. Pass 0 as the fourth argument to disable caching. CacheService is best-effort, cached data may be stale, and caching does not guarantee cost savings. Only use caching where the data and authorization context make it appropriate.
Long-running queries: When the initial query is incomplete, the library polls jobs.getQueryResults for results. It also follows page tokens for both fast and slow queries, although execution is still bounded by Apps Script runtime limits.
/**
* BigQueryManager - BigQuery Library for Google Apps Script.
*
* Features:
* - Automatic user / service account authentication
* - BigQuery Standard SQL execution
* - Long-running query polling
* - Automatic result pagination
* - Optional query result caching
* - HTTP and query error handling
*
* DEPENDENCIES:
* OAuth2 library (only for service account authentication):
* 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
*
* OPTIONAL SCRIPT PROPERTIES:
* - clientEmail
* - privateKey
*
* Without these properties, the executing Google account is used.
*/
// ============================================================================
// 1. CONFIGURATION
// ============================================================================
const BQ_CONFIG = {
projectId: 'your-gcp-project-id-123456',
datasetId: 'analytics_data_set'
};
const BQ_CACHE_CONFIG = {
chunkSize: 90000,
maxParts: 10,
maxExpirationSeconds: 21600
};
// ============================================================================
// 2. AUTHENTICATION
// ============================================================================
/**
* Returns the authentication service for BigQuery.
*
* Uses a service account when both credentials are configured.
* Otherwise, uses the executing user's Google account.
*
* @returns {Object} Authentication service.
*/
function getBQOAuthService() {
const scriptProps = PropertiesService.getScriptProperties();
const clientEmail = scriptProps.getProperty('clientEmail');
const privateKeyRaw = scriptProps.getProperty('privateKey');
// Use current user when no service account is configured.
if (!clientEmail && !privateKeyRaw) {
console.log('BigQuery authentication: current user');
return {
hasAccess: () => true,
getAccessToken: () => ScriptApp.getOAuthToken(),
getLastError: () => null
};
}
// Prevent incomplete configuration.
if (!clientEmail || !privateKeyRaw) {
throw new Error(
'Incomplete BigQuery service account configuration. ' +
'Provide both clientEmail and privateKey, or neither.'
);
}
console.log('BigQuery authentication: service account');
const privateKey = privateKeyRaw.replace(/\\n/g, '\n');
return OAuth2.createService('BQ')
.setTokenUrl('https://oauth2.googleapis.com/token')
.setPrivateKey(privateKey)
.setIssuer(clientEmail)
.setPropertyStore(scriptProps)
.setScope('https://www.googleapis.com/auth/bigquery');
}
// ============================================================================
// 3. CORE BIGQUERY FUNCTION
// ============================================================================
/**
* Executes a BigQuery query and returns all result pages.
*
* Automatically waits for long-running queries and optionally
* caches simple SELECT queries.
*
* Cache is disabled when cacheExpirationMinutes is 0.
*
* @param {string} query Standard SQL query.
* @param {Object} oauthService Authentication service.
* @param {string} gcpProject Google Cloud project ID.
* @param {number} cacheExpirationMinutes Cache duration in minutes.
* @returns {Array<Object>} Query results.
*/
function runBigQuery(
query,
oauthService = getBQOAuthService(),
gcpProject = BQ_CONFIG.projectId,
cacheExpirationMinutes = 300
) {
if (!oauthService.hasAccess()) {
throw new Error(
'BigQuery authorization error: ' +
oauthService.getLastError()
);
}
const accessToken = oauthService.getAccessToken();
const headers = {
Authorization: `Bearer ${accessToken}`
};
// Cache only simple SELECT statements.
const useCache =
cacheExpirationMinutes > 0 &&
/^\s*SELECT\b/i.test(query);
let cacheKey = null;
// 1. Check cache.
if (useCache) {
cacheKey = _getBQCacheKey(
query,
gcpProject,
accessToken
);
const cachedData = _retrieveFromCache(cacheKey);
if (cachedData !== null) {
console.log('BigQuery results retrieved from cache.');
return JSON.parse(cachedData);
}
}
const url =
`https://bigquery.googleapis.com/bigquery/v2/projects/` +
`${encodeURIComponent(gcpProject)}/queries`;
try {
// 2. Execute query.
const responseData = _fetchBQJson(url, {
method: 'post',
headers,
contentType: 'application/json',
payload: JSON.stringify({
query,
useLegacySql: false
})
});
const jobId = responseData.jobReference?.jobId;
const location = responseData.jobReference?.location;
let result = responseData;
// 3. Wait if query is still running.
if (!result.jobComplete) {
if (!jobId) {
throw new Error(
'BigQuery returned an incomplete query without a job ID.'
);
}
console.log(`Waiting for BigQuery job: ${jobId}`);
result = _waitForJobCompletion(
gcpProject,
jobId,
oauthService,
2000,
180000,
{ location }
);
}
// 4. Validate completed query.
_checkBQQueryErrors(result, gcpProject, jobId, location, headers);
// 5. Parse first result page.
let finalData = _parseBigQueryResponse(result);
let pageToken = result.pageToken || null;
// 6. Retrieve additional pages.
while (pageToken) {
if (!jobId) {
throw new Error(
'Cannot retrieve additional pages without a job ID.'
);
}
const params = [
`pageToken=${encodeURIComponent(pageToken)}`
];
if (location) {
params.push(
`location=${encodeURIComponent(location)}`
);
}
const paginatedUrl =
`https://bigquery.googleapis.com/bigquery/v2/projects/` +
`${encodeURIComponent(gcpProject)}/queries/` +
`${encodeURIComponent(jobId)}?${params.join('&')}`;
const pageData = _fetchBQJson(paginatedUrl, {
method: 'get',
headers
});
if (!pageData.jobComplete) {
throw new Error(
`BigQuery result page is not ready: ${jobId}`
);
}
_checkBQQueryErrors(pageData, gcpProject, jobId, location, headers);
finalData = finalData.concat(
_parseBigQueryResponse({
...pageData,
schema: pageData.schema || result.schema
})
);
pageToken = pageData.pageToken || null;
}
// 7. Cache complete results.
if (useCache) {
_storeInCache(
cacheKey,
JSON.stringify(finalData),
cacheExpirationMinutes
);
}
console.log(
`BigQuery query completed: ${finalData.length} rows.`
);
return finalData;
} catch (error) {
console.error('BigQuery execution error:', error);
throw error;
}
}
// ============================================================================
// 4. BIGQUERY HELPERS
// ============================================================================
/**
* Executes a BigQuery REST request and validates HTTP status.
*
* @param {string} url BigQuery API endpoint.
* @param {Object} options UrlFetchApp request options.
* @returns {Object} Parsed JSON response.
*/
function _fetchBQJson(url, options) {
const response = UrlFetchApp.fetch(url, {
...options,
muteHttpExceptions: true
});
const status = response.getResponseCode();
const body = response.getContentText();
if (status < 200 || status >= 300) {
let message = body;
try {
const errorData = JSON.parse(body);
message = errorData.error?.message || body;
} catch (error) {
// Keep original response body.
}
throw new Error(
`BigQuery API error (${status}): ${message}`
);
}
return JSON.parse(body);
}
/**
* Checks query errors against the actual BigQuery job status.
* Query response errors may include nonfatal warnings.
*
* @param {Object} response BigQuery query response.
* @param {string} projectId BigQuery job-execution project.
* @param {string} jobId BigQuery job ID.
* @param {string} location BigQuery job location.
* @param {Object} headers Request authorization headers.
* @returns {void}
*/
function _checkBQQueryErrors(response, projectId, jobId, location, headers) {
if (!response.errors?.length) return;
if (!jobId) {
console.warn('BigQuery reported warnings:', JSON.stringify(response.errors));
return;
}
const params = location
? `?location=${encodeURIComponent(location)}`
: '';
const url =
`https://bigquery.googleapis.com/bigquery/v2/projects/` +
`${encodeURIComponent(projectId)}/jobs/` +
`${encodeURIComponent(jobId)}${params}`;
const job = _fetchBQJson(url, { method: 'get', headers });
if (job.status?.errorResult) {
throw new Error(
`BigQuery job failed: ${job.status.errorResult.message}`
);
}
console.warn('BigQuery job warnings:', JSON.stringify(response.errors));
}
/**
* Waits for a BigQuery job and retrieves its first result page.
*
* Uses jobs.getQueryResults instead of jobs.get.
*
* @param {string} projectId Google Cloud project ID.
* @param {string} jobId BigQuery job ID.
* @param {Object} oauthService Authentication service.
* @param {number} interval Polling interval in milliseconds.
* @param {number} maxWait Maximum waiting time in milliseconds.
* @param {Object} opts Additional configuration.
* @returns {Object} Completed query results response.
*/
function _waitForJobCompletion(
projectId,
jobId,
oauthService,
interval = 2000,
maxWait = 180000,
opts = {}
) {
const start = Date.now();
const params = ['timeoutMs=1000'];
if (opts.location) {
params.push(
`location=${encodeURIComponent(opts.location)}`
);
}
const url =
`https://bigquery.googleapis.com/bigquery/v2/projects/` +
`${encodeURIComponent(projectId)}/queries/` +
`${encodeURIComponent(jobId)}?${params.join('&')}`;
while (Date.now() - start < maxWait) {
const result = _fetchBQJson(url, {
method: 'get',
headers: {
Authorization: `Bearer ${oauthService.getAccessToken()}`
}
});
if (result.jobComplete) {
return result;
}
Utilities.sleep(interval);
}
throw new Error(
`Timeout waiting for BigQuery job ${jobId}.`
);
}
/**
* Converts BigQuery REST result rows into objects.
*
* Uses the top-level schema to map column names.
* Nested and repeated values remain in their REST representation.
*
* @param {Object} data BigQuery response.
* @returns {Array<Object>} Parsed rows.
*/
function _parseBigQueryResponse(data) {
if (!data.rows || data.rows.length === 0) {
return [];
}
if (!data.schema?.fields) {
throw new Error(
'BigQuery returned rows without a schema.'
);
}
const headers = data.schema.fields.map(
field => field.name
);
return data.rows.map(row => {
const obj = {};
row.f.forEach((cell, index) => {
obj[headers[index]] = cell.v;
});
return obj;
});
}
// ============================================================================
// 5. CACHE HELPERS
// ============================================================================
/**
* Generates a cache key from query, project and access token.
*
* The token hash isolates cached data between credentials.
* Token refreshes can reduce cache reuse.
*
* @param {string} query SQL query.
* @param {string} projectId Google Cloud project ID.
* @param {string} accessToken OAuth2 token.
* @returns {string} Cache key.
*/
function _getBQCacheKey(query, projectId, accessToken) {
const input = JSON.stringify({
query,
projectId,
accessToken
});
const digest = Utilities.computeDigest(
Utilities.DigestAlgorithm.SHA_256,
input
);
return `bq_v2_${_convertByteArrayToHex(digest)}`;
}
/**
* Stores UTF-8 data as Base64 chunks in user cache.
*
* CacheService supports a maximum of 100 KB per entry
* and a maximum expiration of 21600 seconds.
*
* @param {string} key Cache identifier.
* @param {string} data Data to store.
* @param {number} minutes Expiration in minutes.
* @returns {boolean} Whether data was cached.
*/
function _storeInCache(key, data, minutes) {
if (!Number.isFinite(minutes) || minutes <= 0) {
return false;
}
const cache = CacheService.getUserCache();
const seconds = Math.min(
BQ_CACHE_CONFIG.maxExpirationSeconds,
Math.max(1, Math.floor(minutes * 60))
);
const encoded = Utilities.base64Encode(
data,
Utilities.Charset.UTF_8
);
const chunkSize = BQ_CACHE_CONFIG.chunkSize;
const parts = Math.ceil(encoded.length / chunkSize);
if (parts > BQ_CACHE_CONFIG.maxParts) {
console.log(
'BigQuery result too large for cache. Skipping.'
);
return false;
}
// Store data first.
for (let i = 0; i < parts; i++) {
const chunk = encoded.substring(
i * chunkSize,
(i + 1) * chunkSize
);
cache.put(`${key}_p${i}`, chunk, seconds);
}
// Write manifest last.
cache.put(`${key}_count`, String(parts), seconds);
return true;
}
/**
* Retrieves and reconstructs cached data.
*
* @param {string} key Cache identifier.
* @returns {?string} Cached data or null.
*/
function _retrieveFromCache(key) {
const cache = CacheService.getUserCache();
const countStr = cache.get(`${key}_count`);
if (!countStr) {
return null;
}
const count = Number(countStr);
if (
!Number.isInteger(count) ||
count < 1 ||
count > BQ_CACHE_CONFIG.maxParts
) {
return null;
}
let encoded = '';
for (let i = 0; i < count; i++) {
const chunk = cache.get(`${key}_p${i}`);
if (chunk === null) {
return null;
}
encoded += chunk;
}
try {
const bytes = Utilities.base64Decode(encoded);
return Utilities.newBlob(bytes)
.getDataAsString('UTF-8');
} catch (error) {
console.warn('Invalid BigQuery cache entry:', error);
return null;
}
}
/**
* Converts a byte array to hexadecimal.
*
* @param {Array<number>} byteArray Input bytes.
* @returns {string} Hexadecimal string.
*/
function _convertByteArrayToHex(byteArray) {
return byteArray
.map(byte =>
('0' + (byte & 0xFF).toString(16)).slice(-2)
)
.join('');
}
Important limitations: The parser maps top-level fields into objects but does not recursively convert nested or repeated values. Cache entries can expire or be evicted, and a SELECT-prefix check is not a SQL security boundary. Queries still run with the permissions of the selected identity, so grant the minimum needed access and test before production deployment.
I’ve open-sourced this library, so if you want to improve it or suggest features, feel free to contribute on GitHub.
If you’re building Google Workspace Add-ons or Editor Add-ons, there’s a good chance you’ve encountered mysterious PERMISSION_DENIED errors, especially when using google.script.run in custom sidebars.
The kicker? The same code works flawlessly for some users, and fails catastrophically for others — without any obvious reason.
Welcome to the multi-account execution context problem.
In this article, I’ll break down:
When and why this error occurs
How to reproduce it
What you can do to avoid it (or at least handle it gracefully)