node-google-spreadsheet icon indicating copy to clipboard operation
node-google-spreadsheet copied to clipboard

How to use this in browser?

Open 1pratham opened this issue 5 years ago • 7 comments

Hi,

I got this working in Node but I am trying to set up a quick POC without going into the server-side and want to use this library directly in browser.

I read another issue where someone else might have got it working browserify.

I am trying to use this with Vue/Nuxt. I copied the code sample on the homepage and ran browserify on that file eg: `const { GoogleSpreadsheet } = require('google-spreadsheet'); const key = require('./key.json');

const sheetId = 'sheetId';

// spreadsheet key is the long id in the sheets URL

const start = async () => { const doc = new GoogleSpreadsheet(sheetId, null, { gzip: false }); // use service account creds await doc.useServiceAccountAuth(key);

try {
    await doc.loadInfo(); // loads document properties and worksheets
    console.log(doc.title);
    await doc.updateProperties({ title: 'CovidBot_User_Details' });
    const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id]
    console.log(sheet.title);
    console.log(sheet.rowCount);

    await sheet.addRow({
        DateTime: new Date(),
        PinCode: '400086',
        Gender: 'Male',
        Symptoms1: 'ABC, DEF',
    });

    // // adding / removing sheets
    // await doc.addSheet({ title: 'hot new sheet!' });
    // await newSheet.delete();
} catch (error) {
    console.log(error.message);
}

};

module.exports.default = start; `

imported the output file in a js file like this import start from './output'. However, the next build gives a bunch of error. Should I just use the output file as script tag instead of importing in another js file?

1pratham avatar Apr 25 '20 19:04 1pratham

I'd like to bump this. The error I'm getting is on build (typescript), and it's a series of errors that certain node modules couldn't be found:

e.g.: Module not found: Error: Can't resolve 'tls' in '~/workspace/chrome-extension-typescript-starter-master/extension/node_modules/https-proxy-agent/dist'

And ditto for the fs, net, and child_process modules. These are all required by google-auth-library.

I tried something suggested by some google searching, which was to add the following to my package.json:

"browser": {
    "fs": false,
    "child_process": false,
    "net": false
  },

But that didn't work.

Has anybody figured out a workaround for this?

jondubin avatar Aug 14 '20 18:08 jondubin

I too would like to use it on a Browser. Is it possible? I am unable to "compile" it with webpack? Or is it designed to be used only in NodeJS? Thanks

rmrbytes avatar Jan 15 '21 04:01 rmrbytes

@theoephraim could you please clarify with a short answer? Is this library meant to be used in Node only?

loopmode avatar Apr 27 '21 13:04 loopmode

Also interested in the solution to this issue if anyone has it out there

softwaredeveloptam avatar Aug 12 '21 10:08 softwaredeveloptam

I ended up with a custom implementation around the original google API, and I'm quite happy with it. It's not as terrible as people say. In my case it's a react app, and I built a bunch of hooks and helpers, it's not much code and works well. Can't share tho, unfortunately... (As of now)

loopmode avatar Aug 12 '21 11:08 loopmode

In my case, luckily I set up my repo using NextJs framework which is SSR and I can host an api to get Sheet's data without having to use Express. But seriously a client solution would be very useful

coolcorexix avatar Aug 16 '21 10:08 coolcorexix

The only dependency that fails in the browser is google-auth-library. This is used only with the useServiceAccountAuth authentication method which isn't really applicable in browser use cases anyway.

I got it working by overriding the entire dependency by adding this to package.json scripts section:

"postinstall": "echo 'export default {}' > node_modules/google-spreadsheet/node_modules/google-auth-library/build/src/index.js"

This essentially removes the entire dependency from google-spreadsheet. (You may need to rm -rf node_modules/ && npm install to get it working.)

When using useOAuth2Client method, it expects an OAuth2Client object, but the only method it uses is getAccessToken. Therefore you can pass in an object that returns the access token that has been obtained otherwise (in my case using react-google-login).

    const doc = new GoogleSpreadsheet('<SHEET-ID>');
    const mockOauthClient = {
      getAccessToken: () => ({ token: accessToken }),
    };
    doc.useOAuth2Client(mockOauthClient as any);
    await doc.loadInfo();
    console.log(doc.title);

Would it be possible to make the dependency against google-auth-library dynamic @theoephraim? I'm not sure exactly how though. Possibly a separate import endpoint import { GoogleSpreadsheet } from 'google-spreadsheet/browser'?

That plus a method that accepts just the access token instead of a full OAuth2Client object would make the library fully functional in browser environment as well.

plaa avatar Dec 29 '21 11:12 plaa

I've released a new version which has moved google-auth-library to an optional peer dependency, and I hope that should make this much easier to use in the browser Please give it a try and open a new issue with new details if you run into problems.

theoephraim avatar Jun 26 '23 17:06 theoephraim