Securing OpenAI API key in JavaScript

Hey everyone,

I’m a student, developing a client-side web application with vanilla JS (HTML, CSS, and JavaScript) without Node.js. For my project I’m using the OpenAI API key.

However, I recently discovered that my API key is visible in the browser’s source code when I navigate to the browser settings :frowning:

Since I haven’t used Node.js in my project, I’m unable to utilize methods like .env files, process.env, or require to secure my API key. I tried to solve my problem using netlify.toml file and Netlify environment variables. However, I haven’t been successful in accessing these variables within my code, especially since my website doesn’t use Node.js.

As my project’s deadline is quickly approaching, I’m feeling quite overwhelmed and would greatly appreciate your help :slight_smile:


These would not secure the key anyway, if it was still being referenced and inserted/compiled into front-end code.

Same issue, these will also not secure the key if you’re only going to insert/compile them into the front-end code.

Environment variables let you keep values out of your source code or repository, they aren’t about keeping those values out of your compiled code. How you reference them and what your build does will dictate where they may end up.

One way to keep a “secret key” a secret, is for the actual call to the 3rd party API to be made from your own back-end API code, for example a Serverless Function.

You write your own function that when you call it and provide the appropriate values, it then makes the actual call to OpenAI, (and references the Netlify environment variable for your key), it receives the response from OpenAI and passes the results back to the front-end.

Your front-end thus has no visibility of the key, and nor does anyone else.

If you build the key into front-end code it will always be visible.

1 Like

Thank you for the reply.
I just discovered that Netlify serverless functions have 10 second execution limit.
Since my website uses OpenAI API for answering questions, I dont think these functions will be a good idea.
What do you think about that, is there another solution?

@mapahama If your function time runs long, or you don’t want to use functions, your options are:

  1. Function execution times can be increased on Pro plans, (but still to a fairly short upper limit)
  2. You can host your back-end elsewhere and your front-end on Netlify, and make your API calls across providers (proxying to the other service).
  3. You can host your entire application (front-end & back-end) somewhere else.

I had the same problem. This won’t trick a human, but it’ll sneak past a bot. Feel free to obfuscate dummy however you like. Again, a hacker will figure it out, but a bot won’t.

import OpenAI from "openai"

const dummy = ["sk-V...Cy", "WbpGI...BlbkFJ", "q5GtW...4hH6h"]

const openai = new OpenAI({

  apiKey: dummy.join(),
  dangerouslyAllowBrowser: true,