However, I recently discovered that my API key is visible in the browser’s source code when I navigate to the browser settings
Since I haven’t used Node.js in my project, I’m unable to utilize methods like .env files,
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
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.
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:
- Function execution times can be increased on Pro plans, (but still to a fairly short upper limit)
- 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).
- You can host your entire application (front-end & back-end) somewhere else.