ftcoup2021
ftcoup2021

Reputation: 41

Nextjs API request only works locally

I am trying write to google sheet using 'google-spreadsheet' via Next.js API route. It works perfectly fine when I am testing locally. I can see the data being updated in the google sheet. However, when I deploy it to Vercel, it doesn't work. The 'Functions' log from Vercel shows the following error message.

Error authentication FetchError: request to https://www.googleapis.com/oauth2/v4/token failed, reason: Client network socket disconnected before secure TLS connection was established at ClientRequest. (/var/task/node_modules/node-fetch/lib/index.js:1461:11) at ClientRequest.emit (events.js:315:20) at TLSSocket.socketErrorListener (_http_client.js:469:9) at TLSSocket.emit (events.js:315:20) at emitErrorNT (internal/streams/destroy.js:106:8) at emitErrorCloseNT (internal/streams/destroy.js:74:3) at processTicksAndRejections (internal/process/task_queues.js:80:21) { type: 'system', errno: 'ECONNRESET', code: 'ECONNRESET', config: { method: 'POST', url: 'https://www.googleapis.com/oauth2/v4/token', data: { grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: ....

Below is my code if that's any help.

export default async function addRowAPI(req, res) {
  if (req.method === 'POST') {
    try {
      let doc;
      try {
        doc = new GoogleSpreadsheet(process.env.SPREADSHEET_ID);
      } catch (error) {
        console.log('error at line 15:', error);
      }

      try {
        await doc.useServiceAccountAuth({
          client_email: process.env.GOOGLE_SHEETS_CLIENT_EMAIL,
          private_key: (process.env.GOOGLE_SHEETS_PRIVATE_KEY || '').replace(
            /\\n/g,
            '\n'
          ),
        });
      } catch (error) {
        console.log('error authentication', error);
      }

      await doc.loadInfo(); 
      console.log(doc.title);

      const sheet = doc.sheetsByTitle['Test_Sheet']; 
      console.log(sheet.title);
      console.log('addRow Doc:', doc);

      const newRow = await sheet.addRow(req.body);
      

      res.status(201).send();
    } catch (error) {
      res.status(500).json(error);
    }
  } else if (req.method === 'GET') {
    res.status(200).json({ ping: 'pong' });
  }
}

Upvotes: 4

Views: 986

Answers (1)

juliomalves
juliomalves

Reputation: 50278

As mentioned in the comments, the error complains about an authentication issue which indicates wrong/non-existing credentials. Double-check you have all the environment variables properly set in Vercel.

Upvotes: 1

Related Questions