3

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
Haren Sarma
  • 2,267
  • 6
  • 43
  • 72

2 Answers2

2

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)

  • Thank you! This didn't solved reading the file from the filesystem at Vercel. But it did provide a good alternative solution that worked for me as well. – Rutger Apr 14 '23 at 16:43
0

I have a different and easy solution -

  1. configure your credentials in next.config.js file -
const nextConfig = {
  env: {
    privateKey:
      "-----BEGIN PRIVATE KEY-----\nasdfdasfasdf=\n-----END PRIVATE KEY-----\n",
    clientEmail: "your-client-email",
    projectID: 'your-project-id'
  },
 
};

module.exports = nextConfig;
  1. use required credentials like -
const storage = new Storage({
  credentials: {
    client_email: process.env.clientEmail,
    private_key: process.env.privateKey
  },
  projectId: process.env.projectID
});
  1. And Deploy. Setting environment variable in next.config.js file gives a benefit like you don't have to set variables in vercel. During build time, the required variables are pushed into codes. More information on how to use nextjs environment variables is here
Nickname
  • 65
  • 1
  • 8