ENOENT: no such file or directory, open '/var/task/google-cloud-key.json' Vercel

Viewed 954

Please help me to solve..

My JS file file is in Next JS app > pages/api/profile and google-cloud-key.json is in Next JS app root folder itself where package.json is there.

Everything works fine in local, but below error given at Vercel

ENOENT: no such file or directory, open '/var/task/google-cloud-key.json' vercel

My google-cloud-key.json is in the root directory of next JS app.

I have tried below code also:

const storage = new Storage({
            projectId: 'careful-relic-319511',
            keyFilename: __dirname + '/../../../google-cloud-key.json'
        });

This is giving below error now:

ENOENT: no such file or directory, open '/var/task/.next/server/google-cloud-key.json'] {\n  errno: -2,\n  code: 'ENOENT',\n  syscall: 'open',\n  path: '/var/task/.next/server/google-cloud-key.json'\n}\nEND
1 Answers

Hey i found a great solution

  1. Base64 encode the json file. (https://www.base64encode.org/)

  2. Set an env variable (both in local and vercel setting) this encoded string. (In my case GCP_CRED_FILE)

const gcsKey = JSON.parse(
  Buffer.from(process.env.GCP_CRED_FILE, 'base64').toString()
);

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

this works for me. tested using nextjs 11 and vercel deployments

Moreover you dont need to store or push the file to a repo or store it (which can be a security threat)

Related