npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

lw-google-sheet

v1.1.0

Published

Optimized Google Sheets API wrapper with connection pooling, retry logic, and enhanced error handling

Readme

LW Google Sheets

An optimized Google Sheets API wrapper with connection pooling, retry logic, and enhanced error handling.

Features

  • 🚀 Connection Pooling: Reuses authentication clients for better performance
  • 🔄 Automatic Retry: Built-in retry logic with exponential backoff
  • 🛡️ Enhanced Error Handling: Custom error types with detailed error codes
  • 📝 TypeScript Support: Full TypeScript support with comprehensive types
  • 🎯 Multiple Operations: Read, write, append, clear, and get spreadsheet info
  • 🔧 Flexible Auth: Support for both credential files and credential objects
  • 🔇 Silent Mode: Optional silent operation for production environments

Installation

npm install lw-google-sheet

Quick Start

import { getSheetData, writeSheetData } from "lw-google-sheet";

// Read data from a sheet
const data = await getSheetData({
  credentialsPath: "./credentials.json",
  sheetId: "your-sheet-id",
  range: "A1:C10",
});

// Write data to a sheet
await writeSheetData({
  credentialsPath: "./credentials.json",
  sheetId: "your-sheet-id",
  range: "A1:C3",
  values: [
    ["Name", "Age", "City"],
    ["John", "25", "New York"],
    ["Jane", "30", "San Francisco"],
  ],
});

API Reference

Configuration

All functions accept a configuration object with the following properties:

interface SheetConfig {
  credentialsPath?: string; // Path to Google credentials JSON file
  credentials?: any; // Credentials object (alternative to credentialsPath)
  sheetId: string; // Google Sheets ID
  namedRange?: string; // Named range (optional)
  range: string; // Cell range (e.g., 'A1:C10')
  sheetIndexFallback?: number; // Fallback sheet index (default: 0)
  silent?: boolean; // Suppress console output (default: false)
  retryAttempts?: number; // Number of retry attempts (default: 3)
  retryDelay?: number; // Initial retry delay in ms (default: 1000)
}

Functions

getSheetData(config: SheetConfig): Promise<string[][]>

Reads data from a Google Sheet.

const data = await getSheetData({
  credentialsPath: "./credentials.json",
  sheetId: "1ABC123...",
  range: "A1:E10",
  namedRange: "DataRange", // Optional
  retryAttempts: 5,
  silent: true,
});

writeSheetData(config: WriteConfig): Promise<void>

Writes data to a Google Sheet (overwrites existing data).

await writeSheetData({
  credentialsPath: "./credentials.json",
  sheetId: "1ABC123...",
  range: "A1:C3",
  values: [
    ["Header 1", "Header 2", "Header 3"],
    ["Value 1", "Value 2", "Value 3"],
    ["Value 4", "Value 5", "Value 6"],
  ],
  valueInputOption: "USER_ENTERED", // or 'RAW'
});

appendSheetData(config: WriteConfig): Promise<void>

Appends data to a Google Sheet.

await appendSheetData({
  credentialsPath: "./credentials.json",
  sheetId: "1ABC123...",
  range: "A1:C1",
  values: [["New", "Row", "Data"]],
});

clearSheetData(config: SheetConfig): Promise<void>

Clears data from a Google Sheet range.

await clearSheetData({
  credentialsPath: "./credentials.json",
  sheetId: "1ABC123...",
  range: "A1:Z100",
});

getSpreadsheetInfo(config): Promise<SpreadsheetInfo>

Gets metadata about a spreadsheet and its sheets.

const info = await getSpreadsheetInfo({
  credentialsPath: "./credentials.json",
  sheetId: "1ABC123...",
});

console.log(info.title); // Spreadsheet title
console.log(info.sheets); // Array of sheet metadata

cleanupConnections(maxAge?: number): void

Manually cleanup cached connections (optional, happens automatically).

// Cleanup connections older than 30 minutes
cleanupConnections(30 * 60 * 1000);

Error Handling

The library throws GoogleSheetError instances with specific error codes:

import { getSheetData, GoogleSheetError } from "lw-google-sheet";

try {
  const data = await getSheetData(config);
} catch (error) {
  if (error instanceof GoogleSheetError) {
    console.log("Error code:", error.code);
    console.log("Message:", error.message);
    console.log("Original error:", error.originalError);
  }
}

Common error codes:

  • INVALID_CONFIG: Configuration validation failed
  • SHEET_NOT_FOUND: Specified sheet index not found
  • INVALID_DATA: Data validation failed

Authentication

You can authenticate using either a credentials file or a credentials object:

Using Credentials File

const config = {
  credentialsPath: "./path/to/credentials.json",
  sheetId: "your-sheet-id",
  range: "A1:C10",
};

Using Credentials Object

const config = {
  credentials: {
    type: "service_account",
    project_id: "your-project-id",
    private_key_id: "key-id",
    private_key: "your-private-key",
    client_email: "[email protected]",
    // ... other credential fields
  },
  sheetId: "your-sheet-id",
  range: "A1:C10",
};

Performance Optimizations

  1. Connection Pooling: Authentication clients are cached and reused
  2. Automatic Cleanup: Old connections are automatically cleaned up
  3. Retry Logic: Failed requests are automatically retried with exponential backoff
  4. Efficient Fallbacks: Smart fallback to sheet index when named ranges fail

License

ISC