Search code examples
javascriptreactjsgoogle-sheetsnext.jsgoogle-sheets-api

Module not found: Can't resolve 'child_process' - google-spreadsheet


I am trying to save form data to a spreadsheet in Next.js but I keep getting this error which appears as soon as I import google-spreadsheet

Error

enter image description here

./node_modules/google-spreadsheet/node_modules/google-auth-library/build/src/auth/googleauth.js:17:0 Module not found: Can't resolve 'child_process'

Bellow is what I have that is causing the error.

// The error appears when I do this import
import { GoogleSpreadsheet } from "google-spreadsheet";

const SPREADSHEET_ID = process.env.NEXT_PUBLIC_SPREADSHEET_ID;
const SHEET_ID = process.env.NEXT_PUBLIC_SHEET_ID;
const CLIENT_EMAIL = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL;
const PRIVATE_KEY = process.env.NEXT_PUBLIC_GOOGLE_SERVICE_PRIVATE_KEY;

const doc = new GoogleSpreadsheet(SPREADSHEET_ID);

const appendSpreadsheet = async (row) => {
    try {
      await doc.useServiceAccountAuth({
        client_email: CLIENT_EMAIL,
        private_key: PRIVATE_KEY,
      });
      // loads document properties and worksheets
      await doc.loadInfo();

      const sheet = doc.sheetsById[SHEET_ID];
      const result = await sheet.addRow(row);
      return result;
    } catch (e) {
      console.error("Error: ", e);
    }
};

Solution

  • I just solve it.

    Please create next.config.js file in your root. And fill it below.

    module.exports = {
      webpack: config => {
        config.node = {
          fs: 'empty',
          child_process: 'empty',
          net: 'empty',
          dns: 'empty',
          tls: 'empty',
        };
        return config;
      },
    };
    

    Hoorai!