Google Cloud Storage call fails with “error:0909006C:PEM routines:get_name:no start line” when run in Blitz.js api handler

Total
1
Shares

When I try to use @google-cloud/storage inside of a Blitz.js /api handler, it generates this error:

error:0909006C:PEM routines:get_name:no start line
    at Sign.sign (internal/crypto/sig.js:110:29)
    at NodeCrypto.sign (C:Usersmarkjworkspacemyappnode_modulesgoogle-auth-librarybuildsrccryptonodecrypto.js:35:23)
    at GoogleAuth.sign (C:Usersmarkjworkspacemyappnode_modulesgoogle-auth-librarybuildsrcauthgoogleauth.js:561:39)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async sign (C:[email protected]signer.js:174:35) {
  name: 'SigningError'

However when I run it locally with node test_api.js, it works fine…

Here is my code:

// test_api.js

const {Storage} = require('@google-cloud/storage');

const client_id = process.env.GCP_STORAGE_ADMIN_CLIENT_ID
const projectId = process.env.GCP_PROJECT_ID
const client_email = process.env.GCP_STORAGE_ADMIN_CLIENT_EMAIL
const private_key = process.env.GCP_STORAGE_ADMIN_PRIVATE_KEY

const storage = new Storage({
    projectId,
    credentials: {
        client_id,
        client_email,
        private_key,
    }
});

async function listBuckets() {
    console.log('PRIVATE KEY: ', private_key) // the error seems to indicate there is an issue here
    // Output: "-----BEGIN PRIVATE KEY-----n[the private key]n-----END PRIVATE KEY-----n"
    const [buckets] = await storage.getBuckets();
    console.log('Buckets:');
    buckets.forEach(bucket => {
      console.log(bucket.name);
    });
}

module.exports = {
    listBuckets // this function errors when called within Next.js /api handler
}

// When I uncomment this and run the file directly with node, it works
// listBuckets()

The error seems to indicate there is something wrong with the start/prefix of my private key, but I copied it exactly from the Google Service Account JSON file. It looks like this:

-----BEGIN PRIVATE KEY-----n[the private key]n-----END PRIVATE KEY-----n


Solution

It turned out to be a misplaced trailing comma in my .env.local environment variables.

GCP_STORAGE_ADMIN_PRIVATE_KEY="[the private key]",

The trailing comma was not obvious because I had word wrap turned off, and the console.logs weren’t displaying the comma, but it was somehow reading the comma and causing the entire private key to be parsed incorrectly.

Leave a Reply

Your email address will not be published. Required fields are marked *