Reputation: 1
Currently, my team and I have a website up and running.
Our current method of storing API keys is placing them in a .env file. However, this method still allows the API keys to be accessed through this method of inspecting a web page.
Any suggestions or fixes that could prevent this key from being visible to the public?
Upvotes: 0
Views: 776
Reputation: 43
If the data being fetched is static (not reliant on user input) it can be fetched during build time using the Next.js getStaticProps
method and thus avoid being detected in the frontend altogether.
Users will never be able to see the actual endpoints which were originally called during build time to be stored for later retrieval in a lib/
directory.
Next is React-based, so it's relatively "easy" to migrate to from React.
As getStaticProps runs only on the server-side, it will never run on the client-side. It won’t even be included in the JS bundle for the browser, so you can write direct database queries without them being sent to browsers.
This means that instead of fetching an API route from getStaticProps (that itself fetches data from an external source), you can write the server-side code directly in getStaticProps.
Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from getStaticProps. This produces an additional call, reducing performance. Instead, the logic for fetching the data from the CMS can be shared by using a lib/ directory. Then it can be shared with getStaticProps.
https://nextjs.org/docs/basic-features/data-fetching/get-static-props
Upvotes: 0
Reputation: 2918
You cannot hide your keys anywhere in the browser, frontend, or client-side. They should always be on your server.
What you need is a server env with an API, here's how you will do it:
Upvotes: 1