You can read and write Google Sheets from JavaScript using the official Google Sheets API v4 and the Google APIs client library for JavaScript, either in a browser or in Node.js. The shortest working path is: create a Google Cloud project, enable the Sheets API, create credentials, install the googleapis package (Node.js) or load gapi (browser), then authorize and call spreadsheets.values.get or spreadsheets.values.update. Everything below walks through that path with the choices you have to make about authentication, because that is where most people get stuck.
Note that menu labels in the Google Cloud Console change from time to time, so the exact wording you see may differ slightly from what is written here. Look for the section with a similar name and you will find the right control.
What You'll Need
- A Google account and a Google Cloud project (the free tier is enough for testing).
- The Google Sheets API enabled for that project.
- Credentials: either an API key (read-only, public data only), an OAuth 2.0 client ID (acting on behalf of a user), or a service account (server-to-server, no user present).
- Node.js installed if you are working server-side, or a web page if you are working in the browser.
- The ID of at least one spreadsheet, plus the sheet name (for example
Sheet1). The ID is the long string in the URL between/d/and/edit. - Basic JavaScript familiarity, including promises or async/await.
Step-by-Step
- Create or pick a Cloud project. Go to the Google Cloud Console, open the project selector at the top, and create a new project. Give it a clear name so you can find it later.
- Enable the API. In the console, open the APIs and services area, choose Library, search for Google Sheets API, open it, and click Enable. Enabling the API is per project, so a new project starts with it off.
- Choose your credential type. For reading a sheet that is shared publicly, an API key is simplest. For acting as a signed-in user (their files, their permissions), create an OAuth 2.0 Client ID and add the URL your app runs on as an authorized redirect URI. For a script with no user involved, create a service account and download its JSON key file.
- Install the client library (Node.js). In your project folder run
npm install googleapis. This package bundles the generated clients for Google APIs, including Sheets v4. If you prefer a lighter install,@googleapis/sheetsis the single-API package, but the code below uses the full one. - Write the smallest possible read call. In Node.js with a service account, load the key, build the auth client, and call the values endpoint. The spreadsheet ID and range are the only two inputs you need:
sheets.spreadsheets.values.get({ spreadsheetId, range: 'Sheet1!A1:C10' }). The response contains avaluesarray of rows, each row an array of cells, or novalueskey at all when the range is empty, so guard against that. - Share the spreadsheet with the service account. Open the sheet, click Share, and add the service account's email address (it ends in
iam.gserviceaccount.com) as an Editor if you need to write. This step is skipped constantly and produces a 403 error that looks like a code bug but is a permissions problem. - Write data back. Use
spreadsheets.values.updatewithrange,valueInputOption, andvalues. SetvalueInputOptiontoRAWto store text exactly as sent, orUSER_ENTEREDto let Sheets parse it the way typing into a cell would, so=SUM(A1:A5)becomes a formula and dates become real dates. - Append instead of overwrite. For logs and form submissions, use
spreadsheets.values.appendwithinsertDataOption: 'INSERT_ROWS'. This finds the last row with data and adds below it, so you never have to calculate the target row yourself. - Browser-only alternative. If your code runs in a page rather than a server, load the
gapiclient script from Google, initialize it with your API key and discovery docs, then call the same values methods. Browser use with an API key is limited to public sheets; anything involving a user's private files must use OAuth with a verified redirect URI. - Centralize configuration. Keep the spreadsheet ID, range, and credential paths in environment variables or a config file. Hard-coded IDs are the usual reason a script works locally and fails in a deployed environment.
- Handle the quota. The API enforces per-minute read and write limits per project and per user. Batch reads by asking for a wide range in one call, and batch writes with
spreadsheets.values.batchUpdaterather than looping cell by cell.
Common Mistakes
- Using an API key for private sheets. API keys identify the project, not a user. Any sheet that is not public will return a permissions error no matter how correct the key is.
- Forgetting to share the file with the service account. The most frequent 403 cause. Sharing the file is separate from enabling the API.
- Wrong range syntax. The sheet name must be present when it is not the first sheet, and names containing spaces need single quotes:
'My Sheet'!A1:B2. Ranges are A1 notation, not row/column numbers. - Sending flat arrays.
valuesmust be an array of rows, each row an array of cells. A one-dimensional array is rejected. - Expecting formulas with RAW.
RAWwrites the literal text; onlyUSER_ENTEREDparses formulas and numbers. - Committing the JSON key. Service account keys are secrets. Keep them out of version control and rotate them if leaked.
Tips
- Start with a test sheet you own before pointing code at anything important.
- Request only the scopes you need, such as
spreadsheetsfor full access or the read-only equivalent, rather than the broadest scope available. - Log the full error object including its
statusanderrorsfields; the status code alone rarely tells you enough. - Use spreadsheet properties to look up sheet names and IDs instead of assuming them, so a renamed tab does not break your script.
- For repeated runs, open the sheet once per process rather than re-authorizing on every call.
Troubleshooting
If you get a 403, check three things in order: that the Sheets API is enabled on the right project, that the credential belongs to that project, and that the file is shared with the user or service account you are authenticating as. If you get a 400, the range is malformed or does not exist on that spreadsheet. A 401 usually means the token expired or the credential file is wrong. If the API is enabled but you see an error saying it is disabled, you are almost certainly using credentials from a different project.
If a call returns an empty result rather than an error, ask for a wider range to confirm the data exists and check the tab name. If your writes succeed but formulas appear as text, switch valueInputOption to USER_ENTERED. If you hit rate limits, add exponential backoff and batch your requests. When nothing makes sense, sign out and back in to the console, create a fresh key, and test with the simplest possible call against a new blank sheet.
Frequently Asked Questions
Do I need OAuth or a service account?
If a person must grant access to their own files, use OAuth. For unattended scripts and servers, a service account is the standard choice.
Can I use the Sheets API without a backend?
Yes, for public sheets with an API key. Any private sheet requires OAuth, which needs a hosted redirect URI and works best with a server or a properly configured web app.
How do I read a whole sheet without knowing the row count?
Use a generous range like Sheet1!A1:Z1000 or fetch only the tab name; the API returns whatever has data within the range.
Why does my write land in the wrong place?
Most often the range and values dimensions disagree. Writes start at the top-left of the range and expand to fit, so align your arrays with the range you declare.
Is there a limit on cell text length?
Sheets enforces limits on total cells and characters, but they vary by account type, so check the official Sheets documentation for current figures.