All posts
Blog

How to Read Google Sheets Data with JavaScript

Three ways to read Google Sheets data in JavaScript: the official Sheets API, SheetsAPI (simpler), and the CSV export trick.

4 min read

There are three meaningfully different ways to read data from a Google Sheet in JavaScript. They trade off complexity, reliability, and capability in different ways — the right choice depends on what you are building.

This guide walks through all three honestly, with working code for each.


Option 1: The official Google Sheets API

Google's Sheets API v4 is the authoritative way to read from (and write to) any sheet. It is powerful, stable, and supported indefinitely. It is also the most involved to set up.

When to use it: You need write access, you are doing complex range operations, you are building a server-side integration where full OAuth is already wired up, or you need access to cell formatting, formulas, or named ranges.

Setup

Install the official client library:

npm install googleapis

You need a Google Cloud project with the Sheets API enabled and a service account with its credentials JSON file. Share your sheet with the service account's email address.

Reading data

import { google } from "googleapis";
import credentials from "./service-account-key.json" assert { type: "json" };
 
const auth = new google.auth.GoogleAuth({
  credentials,
  scopes: ["https://www.googleapis.com/auth/spreadsheets.readonly"],
});
 
const sheets = google.sheets({ version: "v4", auth });
 
async function getSheetData(spreadsheetId, range) {
  const response = await sheets.spreadsheets.values.get({
    spreadsheetId,
    range, // e.g. "Sheet1!A1:D100"
  });
 
  const [headers, ...rows] = response.data.values;
 
  return rows.map((row) =>
    Object.fromEntries(headers.map((key, i) => [key, row[i] ?? ""]))
  );
}
 
const data = await getSheetData("YOUR_SPREADSHEET_ID", "Products!A:D");
console.log(data);
// [{ name: "...", price: "...", ... }, ...]

The spreadsheetId is the long string in the sheet's URL between /d/ and /edit. The range uses A1 notation.

Tradeoff: Credential management is real work. You need a Google Cloud project, a service account, a downloaded JSON key, and you must remember to share each sheet with the service account email. For read-only use cases this overhead is often not worth it.


Option 2: GKit SheetsAPI

SheetsAPI is a REST layer over Google Sheets. You connect your sheet once through the GKit dashboard, and it becomes a plain JSON endpoint with filtering, sorting, and pagination built in.

When to use it: You are building a read-mostly app — product catalog, content site, team directory, event listings — and you want an endpoint you can call with a plain fetch from any JavaScript environment without managing OAuth credentials in your code.

Reading data

const BASE = "https://sheetsapi.gkit.mreshank.com/api/spreadsheets";
const USER_KEY = "YOUR_USER_KEY"; // from GKit dashboard
 
async function getProducts() {
  const res = await fetch(`${BASE}/${USER_KEY}/Products`);
  if (!res.ok) throw new Error(`SheetsAPI error: ${res.status}`);
  const { data, meta } = await res.json();
  return { data, total: meta.total };
}
 
const { data, total } = await getProducts();
console.log(`${total} products`, data);

You can pass query parameters to filter, sort, and paginate without touching your spreadsheet:

// Top 5 products in the Audio category, sorted by price ascending
const url = new URL(`${BASE}/${USER_KEY}/Products`);
url.searchParams.set("search", "category:Audio");
url.searchParams.set("sort", "price");
url.searchParams.set("limit", "5");
 
const res = await fetch(url);
const { data } = await res.json();

For private sheets, add an API key from the GKit dashboard:

const res = await fetch(url, {
  headers: { Authorization: "Bearer YOUR_API_KEY" },
});

Tradeoff: SheetsAPI handles reads well but is not the right tool for heavy write workflows or operations that need cell-level control (merging cells, formatting, named ranges). For those, use the official API.


Option 3: The CSV export URL

Every published Google Sheet has a URL that exports the active tab as a CSV file. You can fetch this URL from JavaScript and parse it yourself.

When to use it: The sheet is fully public (not just "anyone with the link" — actually published via File → Share → Publish to web), you need zero auth setup, and you are prototyping something quickly.

How it works

The export URL pattern is:

https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?format=csv&gid=SHEET_GID

The gid is the numeric sheet ID visible in the URL when you click on a tab. For the first sheet it is usually 0.

async function fetchSheetCSV(spreadsheetId, gid = 0) {
  const url = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export?format=csv&gid=${gid}`;
  const res = await fetch(url);
 
  if (!res.ok) throw new Error(`CSV fetch failed: ${res.status}`);
 
  const text = await res.text();
 
  // Minimal CSV parser — does not handle quoted commas or newlines in cells
  const [headerLine, ...lines] = text.trim().split("\n");
  const headers = headerLine.split(",").map((h) => h.trim());
 
  return lines.map((line) => {
    const values = line.split(",");
    return Object.fromEntries(headers.map((key, i) => [key, values[i]?.trim() ?? ""]));
  });
}
 
const data = await fetchSheetCSV("YOUR_SPREADSHEET_ID");
console.log(data);

Tradeoffs — and they are significant:

  • The sheet must be published to the web. A sheet shared as "anyone with the link can view" is not the same as published — the CSV URL will return a login redirect, not data.
  • The export URL format is undocumented and has changed before. It works today; there is no guarantee it works in six months.
  • The built-in CSV parser above breaks on any cell that contains a comma or a newline. Real CSV handling requires a library like Papa Parse.
  • No filtering, sorting, or pagination — you get the entire sheet every time.
  • No auth. This is convenient for prototyping and completely inappropriate for anything that should stay private.

Choosing between the three

Official Sheets APIGKit SheetsAPICSV export
Setup effortHighLowNone
Write supportYesPOST/appendNo
Filtering / sortingManualBuilt-inNo
Auth requiredYes (service account)No (for public sheets)Sheet must be published
ReliabilityStable, versionedStableUndocumented, brittle
Best forServer apps, write-heavyRead-mostly front-end appsQuick prototypes only

For most front-end projects where a non-engineer is managing the data, SheetsAPI is the practical choice — it removes the credential management without giving up reliability. For anything with significant write volume or administrative access needs, set up the official API properly. And treat the CSV export as a shortcut you use once while building a proof of concept, not something you ship.

SheetsAPI is free during beta. Connect your first sheet →

Share