skip to Main Content

I am buidling an app that uses OpenAI’s API (with Next.js and Vercel). In order to make it work, I can let the frontend make the API call directly. However, doing so will expose the API key to the browser (I know it’s never safe to store secrets in the frontend side). Thus, I’m wondering what is the easiest way to run a backend service and make the api call? Since the only goal is to hide my API key, I would prefer a super lightweight solution. Thanks guys.

I tried using Environment Variables in Vercel, however it seems still require a backend service.

2

Answers


  1. You can follow these steps to hide KEYS using nextjs and vercel :

    1. create an API route or serverless function in next that will act as backend service.This will be responsible for securely storing and handling the API key.
    2. Store API keys as an env variable: In Vercel, you define env variables that can be accessed within your Next application. Store your API key as an env variable in Vercel.
    3. Make use of env variable in your serverless function with ‘process.env’ make sure you obtain the key in this serverless function.
    4. Make the API call from the serverless function: Within the serverless function, use the API key to make the API call to OpenAI’s API. This way, the API key will not be exposed to the frontend.

    let me know if this resolves your query 🙂

    Login or Signup to reply.
  2. If you’re looking for a solution that doesn’t involve creating a serverless function and you don’t anticipate calling your function more than 2 million times, I would recommend considering Firebase Cloud Functions. It provides an easy implementation and deployment process. Additionally, instead of managing environment variables (.env files), you can adjust permissions for domains that are allowed to call your Cloud Function directly in the Firebase settings.

    Firebase Cloud Functions are lightweight and offer a straightforward way to achieve your goal without the need for complex infrastructure setup. You can quickly set up and deploy your function, and then define which domains are authorized to invoke it. This approach eliminates the need for managing environment variables separately and simplifies the overall setup process.

    Overall, Firebase Cloud Functions offer a convenient and efficient solution for implementing your desired functionality without the overhead of creating and managing a separate serverless function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search