1

I am making use of the googleapis in a nodejs application, and I am trying to interact with the calendar from a gmail account. When I test this on my local machine it works perfectly, but on deploying it I get the error

5|index    | Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
5|index    |     at Sign.sign (crypto.js:331:26)
5|index    |     at Object.sign (/home/ec2-user/api/node_modules/jwa/index.js:55:45)
5|index    |     at Object.jwsSign [as sign] (/home/ec2-user/api/node_modules/jws/lib/sign-stream.js:23:24)
5|index    |     at GoogleToken.<anonymous> (/home/ec2-user/api/node_modules/gtoken/src/index.ts:251:13)
5|index    |     at step (/home/ec2-user/api/node_modules/gtoken/build/src/index.js:42:23)
5|index    |     at Object.next (/home/ec2-user/api/node_modules/gtoken/build/src/index.js:23:53)
5|index    |     at /home/ec2-user/api/node_modules/gtoken/build/src/index.js:17:71
5|index    |     at new Promise (<anonymous>)

Below is the controller in which I try to use it.

import { google } from 'googleapis'
import { Request, Response, NextFunction } from 'express';

export class HolidayController {
    fetchHolidays(req: Request, res: Response, next: NextFunction) {
        const jwtClient = new google.auth.JWT(
            process.env.GOOGLE_SERVICE_CLIENT_EMAIL,
            null,
            process.env.GOOGLE_SERVICE_PRIVATE_KEY,
            [
                'https://www.googleapis.com/auth/calendar'
            ]
        )


        const calendar = google.calendar({ version: 'v3', auth: jwtClient});
        calendar.events.list({
            calendarId: 'en.ae#holiday@group.v.calendar.google.com',
            timeMin: (new Date()).toISOString(),
            orderBy: 'startTime',
            singleEvents: true,
        }, (err, response: any) => {

            if (err) {
                return next(err)
            }

            if (response.data.items.length == 0) {
                return res.status(200).json({ message: 'No events in calendar' })
            }


            res.status(200).json({ events: response.data.items })
        })
    }
}

Been on this for the last 3 hours. Any help?

The error comes from calling calendar.events.list

The Key comes from the env like this

export GOOGLE_SERVICE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----**************\n-----END PRIVATE KEY-----\n"

George
  • 3,757
  • 9
  • 51
  • 86

1 Answers1

9

I had the same issue and after hours of searching I found the following fix worked for me. Extra slashes were added when bringing the key over.

const fixedKey = process.env.GOOGLE_SERVICE_PRIVATE_KEY.replace(new RegExp("\\\\n", "\g"), "\n")
const jwtClient = new google.auth.JWT(
        process.env.GOOGLE_SERVICE_CLIENT_EMAIL,
        null,
        fixedKey,
        [
            'https://www.googleapis.com/auth/calendar'
        ]
    )

source

Matt King
  • 136
  • 2
  • 6