How to read/write to Google Sheets using react js?

Viewed 48

In my project, I need to make a public site with many forms. These forms will read and write some strings into a private Google Sheets document. How should I handle this public-to-private while allowing input/read? When I search for something about this, I only found tutorials using Node Js or Python, but I want to do this on my site (client-side).

I found something in the tutorial below, when I create a KeyFile and an e-mail on Sheets API credentials, but the tutorial use Node Js. How to make this tutorial using just JavaScript?

Tutorial link

1 Answers

You may use the following code from this GitHub repository to solve the problem, but please note that this method is unsafe because it exposes your keys:

import './App.css';

import { GoogleSpreadsheet } from 'google-spreadsheet';
import React, { useEffect } from 'react';

import creds from './cred/credentials.json';

function App() {
    const doc = new GoogleSpreadsheet(creds.sheet_id);

    const gSheetInit = async() => {
        try {
            await doc.useServiceAccountAuth(creds);
            await doc.loadInfo();
        } catch (e) {
            console.error('Error LoadDocInfo: ', e);
        }
    };

    (async function() {
        await gSheetInit()
        console.log(doc.title);
    }());


    return ( < div className = 'App' > < p > Hello world < /p> </div > );
}

export default App;

Related