简体   繁体   中英

Nuxt3 and Firebase Cloud Function Hosting: How to access private key in .env file?

I have a Nuxt3 app that is using "server routes" to create backend APIs to use for the front-end.

I have the following server route:

server/api/imagekit/deleteFile.js :

import ImageKit from 'imagekit'

const imagekit = new ImageKit({
  publicKey: useRuntimeConfig().public.imagekitPublicKey,
  privateKey: useRuntimeConfig().imagekitPrivateKey,
  urlEndpoint: useRuntimeConfig().public.imagekitBaseURL
})

export default defineEventHandler(async (event) => {
  // Purge cache of file from Imagekit
  // See detailed email from Rahul @ imagekit dated aug 31, 2022
  const body = await useBody(event)

  const response = await imagekit.purgeCache(body.url)
  return response
})

The above code works fine locally, but once I deploy to Firebase Hosting, I get the following server error when trying to access the API deleteFile :

description: ""
message: "Missing privateKey during ImageKit initialization"
statusCode: 500
statusMessage: "Internal Server Error"
url: "/api/imagekit/deleteFile"

In case it's relevant to this question, here is my code for Nuxt's nuxt.config.ts file where the runtimeConfig property is listed:

    runtimeConfig: {

        imagekitPrivateKey: '',
        public: {
            baseURL: process.env.NODE_ENV === 'production' ? 'https://example.com' : 'http://localhost:3000',
            imagekitBaseURL: 'https://ik.imagekit.io/example/',
            imagekitPublicKey: 'public_AdZM6u2+FvznG/LngYp7Ab3TJy4='
        }
    }

Also, my firebase.json uses 2 codebases for the functions: one for server and one for cloud functions:

{
  "functions": [
    {
      "source": ".output/server",
      "codebase": "nuxt"
    },
    {
      "source": "functions",
      "codebase": "functions"
    }
  ],
  "hosting": [
    {
      "site": "XXX",
      "public": ".output/public",
      "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
      "cleanUrls": true,
      "rewrites": [
        {
          "source": "**",
          "function": "server"
        }
      ]
    }
  ]
}

I do have an .env file in project root that holds the imagekitPrivateKey value.

How would I provide this information to Firebase hosting deployment so ImageKit properly initializes with the private key?

You can read the variables from .env in nuxt.config.ts as shown below:

export default defineNuxtConfig({
  runtimeConfig: {
    // Uppercase preferred in .env file
    imagekitPrivateKey: process.env.IMAGEKIT_PRIVATE_KEY,
  },
});

Then you can access it in your API routes:

export default defineEventHandler((event) => {
  const { imagekitPrivateKey } = useRuntimeConfig();

  return { message: "success" };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM