A Service Account is a 2-legged OAuth method designed for applications to act as a bot user rather than an individual end-user. This is the recommended method for apps that need to access specific documents shared with the service account's email address.
Setup Instructions
- Enable the Sheets API in the Google Cloud Console.
- Create a Service Account in APIs & Services > Credentials.
- Generate a JSON key for the service account and download it.
- Crucial: Share the target Google Spreadsheet with the service account's email address (found in the JSON file).
Implementation
You can use the JWT class from google-auth-library to initialize the connection. It is best practice to load credentials from environment variables.
Note for Heroku/Platform users: Private keys containing newlines (\n) can sometimes be corrupted by environment variable managers. You may need to use .replace(/\n/g, "\n") when loading the key from an environment variable.
import { JWT } from 'google-auth-library'
const SCOPES = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive.file',
];
// Using environment variables (Recommended)
const jwtFromEnv = new JWT({
email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
key: process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n"),
scopes: SCOPES,
});
const doc = new GoogleSpreadsheet('<YOUR-DOC-ID>', jwtFromEnv);