Retrieving API keys on the frontend of NextJS app in production #12531
-
Obviously API keys are secret, so we need to be able to ensure that they're not accessible to the public. But sometimes we will need to fetch from an API using frontend code, and we will need the API key when doing so. However, due to not being in a NodeJS environment, we cannot use process.env. Therefore, I am not able to access environment variables stored on the server. What is best practice for retrieving API keys on the frontend (specifically in a Next.js app) ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
I believe the docs describe how to do it pretty well: https://nextjs.org/docs/api-reference/next.config.js/environment-variables Do you explicitly need the API at the client-side? Or can it also work if you implement getServerSideProps and fetch your data there. Because that would prevent any keys from leaking to the client. |
Beta Was this translation helpful? Give feedback.
-
You shouldn't make protected API calls in the client-side: no matter what you do, the private key will always be exposed. My suggestion is to use API Routes to create your own API route and make the request to the protected API inside it, this way you can safely use your private key without exposing it to the client |
Beta Was this translation helpful? Give feedback.
You shouldn't make protected API calls in the client-side: no matter what you do, the private key will always be exposed.
My suggestion is to use API Routes to create your own API route and make the request to the protected API inside it, this way you can safely use your private key without exposing it to the client