DEV Community

Cover image for Google Sheets as a Database with Node.js and Google APIs
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

5

Google Sheets as a Database with Node.js and Google APIs

Google Sheets can be a simple and effective way to store structured data. In this guide, you'll learn how to integrate Google Sheets with a Node.js (TypeScript) application using the googleapis package.

πŸš€ Step 1: Create a New Google Cloud Project

  1. Go to Google Cloud Console
  2. Click New Project

Create a new project

New project page


πŸ” Step 2: Enable Google Sheets API

  • Search for Google Sheets API

Search API

  • Click Enable

Enable API


πŸ”‘ Step 3: Create Credentials

  • Navigate to the Credentials tab
  • Click Create Credentials β†’ Service Account

Create Credentials

  • Select Application Data β†’ Click Next

Application Data

  • Click Create and Continue, then Done

Redirected Page

Click Done


πŸ” Step 4: Generate JSON Key

  • Go to Credentials β†’ Select the service account you created

Service Account

  • Navigate to Keys β†’ Click Add Key β†’ Create New Key

Add Key

Choose JSON

  • A JSON file will be downloaded. Keep it safe!

Download JSON


πŸ“„ Step 5: Share Google Sheet Access

  • Create a new Google Sheet
  • Click Share

Share Sheet

  • Open the downloaded JSON file and find client_email

Find client email

  • Paste the copied email in the Share section and give Editor access.

Paste Email


βš™οΈ Step 6: Set Up Node.js Project

1️⃣ Install Dependencies

npm init -y
npm install googleapis dotenv
Enter fullscreen mode Exit fullscreen mode

2️⃣ Write Code to Save Data to Google Sheets

import { google } from "googleapis";
import fs from "fs";
import dotenv from "dotenv";

dotenv.config();

const credentials = JSON.parse(fs.readFileSync("path-to-downloaded-json-key.json", "utf8"));

const auth = new google.auth.GoogleAuth({
  credentials,
  scopes: ["https://www.googleapis.com/auth/spreadsheets"],
});

async function saveToGoogleSheet(data: any[]) {
  const sheets = google.sheets({ version: "v4", auth });

  const values = data.map((item) => [
    item.firstName,
    item.lastName,
    item.email,
    item.phone,
    item.plan,
    item.premium_amount,
    item.start_policy_date,
    item.end_policy_date,
  ]);

  await sheets.spreadsheets.values.append({
    spreadsheetId: process.env.GOOGLE_SHEET_ID!,
    range: "Sheet1!A2", // Adjust based on your sheet structure
    valueInputOption: "RAW",
    requestBody: { values },
  });

  console.log("Data saved successfully!");
}

const exampleData = [
  {
    firstName: "John",
    lastName: "Doe",
    email: "johndoe@example.com",
    phone: "+1234567890",
    plan: "Gold Plan",
    premium_amount: 50000,
    start_policy_date: "2025-01-01",
    end_policy_date: "2026-01-01",
  },
];

saveToGoogleSheet(exampleData).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

πŸ” Step 7: Get Your Google Sheet ID

To find your Sheet ID, look at the URL of your Google Sheet.

Find Sheet ID

Copy this ID and set it in your .env file:

GOOGLE_SHEET_ID=your-google-sheet-id
Enter fullscreen mode Exit fullscreen mode

βœ… Step 8: Test Your Code

Run your script and check your Google Sheet. You should see something like this:

Google Sheet Data


🎯 Conclusion

You’ve successfully integrated Google Sheets with Node.js using the Google Sheets API! πŸŽ‰

This method is great for small projects, logging data, or quickly storing structured records without setting up a database. If you need more complex features, consider using a dedicated database like Firebase, PostgreSQL, or MongoDB.

Got questions? Drop them in the comments below! πŸš€

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
fredabod profile image
FredAbod β€’

Amazing

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay