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:
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF

The Service Account & Script Properties
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:
clientEmail/ Value:your-service-account@... - 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
SELECTresults for up to 300 minutes (5 hours) by default. Pass0as 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.getQueryResultsfor 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.
