TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: How to securely load API key in JavaScript?

2 点作者 imheretolearn超过 1 年前
I&#x27;m trying to implement Place Autocomplete in my project. Google provides the following snippet to load the library<p>&lt;script async src=&quot;https:&#x2F;&#x2F;maps.googleapis.com&#x2F;maps&#x2F;api&#x2F;js?key=YOUR_API_KEY&amp;libraries=places&amp;callback=initMap&quot;&gt; &lt;&#x2F;script&gt;<p>I know that I can .gitignore .env files and pass the API KEY as an env variable. I can also restrict the API KEY to accept requests from my referrer domain. I think even if I place my API KEY in .env files users can inspect element and see the key. I was wondering if it is possible to spoof a referrer and use my API KEY. I am currently making an api call to my backend server which relays the result to the front end but that adds unnecessary latency. Hence, if possible I would like to use the Google snippet. What are industry standard practices of loading the API KEY securely in Javascript?

3 条评论

jfengel超过 1 年前
Google has tools to restrict usage of your API key to certain HTTP referrers and apps.<p><a href="https:&#x2F;&#x2F;cloud.google.com&#x2F;docs&#x2F;authentication&#x2F;api-keys?hl=en&amp;visit_id=638343634249811087-3665802784&amp;rd=1#api_key_restrictions" rel="nofollow noreferrer">https:&#x2F;&#x2F;cloud.google.com&#x2F;docs&#x2F;authentication&#x2F;api-keys?hl=en&amp;...</a><p>It&#x27;s not perfect; there are ways to subvert it. But it makes it trickier for somebody to make much of a profit off it, reducing interest in stealing the key.
necovek超过 1 年前
In essence, the best you can do is have an authorization dance that results in a short lived authentication token.<p>Or you could use some obfuscation like symmetrically encrypting the key, but clients will see the encryption key too (and in the inspector when Maps API is hit).<p>Or you could have a server side proxy, but that proxy will be publicly available too.<p>As frontend code works on the client, there is no real way to hide the API key, so I wouldn&#x27;t really bother adding any complexity.
compressedgas超过 1 年前
Set up your key so that you can frequently rotate it.