openai / openai-quickstart-node

Node.js example app from the OpenAI API quickstart tutorial
https://platform.openai.com/docs/quickstart?context=node
MIT License
2.54k stars 1.99k forks source link

OpenAI API Key Security in Next.js #84

Closed joseph-106 closed 1 year ago

joseph-106 commented 1 year ago

Describe the bug

OpenAI's official documentation explains API keys as follows:

"Remember that your API key is a secret! Do not share it with others or expose it in any client-side code (browsers, apps). Production requests must be routed through your own backend server where your API key can be securely loaded from an environment variable or key management service."

Does the API Route provided in the current example for Next.js correspond to the own backend server? If we put the API key in an environment variable and use Vercel for deployment, would there be no security issues?

Thanks in advance :)

To Reproduce

Status quo of the provided example

OS

No response

Node version

No response

AleksandrHovhannisyan commented 1 year ago

There would only be a security issue if you were somehow using the API key on the client side, such as when making a fetch request and putting the API key in the request object. Anyone looking at their network tab would then be able to see your API key. Similarly, anyone could find it in the JavaScript loaded by the page.

In this example repo, the API key is only being used on a server-side API route defined in api/generate:

https://github.com/openai/openai-quickstart-node/blob/43d9a3c750b7458f09ba48414f55923e1ef6701b/pages/api/generate.js#L3-L5

And we hit that endpoint when submitting the client-side form:

https://github.com/openai/openai-quickstart-node/blob/43d9a3c750b7458f09ba48414f55923e1ef6701b/pages/index.js#L9-L12

Since generate only runs on the server, the API key is only accessible on the server, and hence it remains private.

joseph-106 commented 1 year ago

@AleksandrHovhannisyan Thank you for your kind response :)