[Next.js] Hide Sensitive Information from the Consumers of Next.js API
<p>We'll learn how to use Next.js API Routes to hide sensitive information from the clients. In this case, we're calling the JSON Placeholder API with a "secret" value in the headers. All that sensitive information is hidden from the clients since they don't call, or even know, that we're calling the JSON Placeholder API under the hood.</p><p> </p>
<div class="cnblogs_code">
<pre>async <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> getSuperSecretData() {
const result </span>= await fetch("https://jsonplaceholder.typicode.com/todos/1"<span style="color: rgba(0, 0, 0, 1)">, {
headers: {
authorization: </span>'SUPER SECRET VALUE'<span style="color: rgba(0, 0, 0, 1)">
}
}).then(res </span>=><span style="color: rgba(0, 0, 0, 1)"> res.json())
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result
}
async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> handler(req, res) {
const secretTodo </span>=<span style="color: rgba(0, 0, 0, 1)"> await getSuperSecretData()
res.json({todo: secretTodo})
}
export </span><span style="color: rgba(0, 0, 255, 1)">default</span> handler<br><br></pre>
</div>
<p>authorization header won't be seen from the request in backend</p>
<p><img src="https://img2022.cnblogs.com/blog/364241/202204/364241-20220403173839886-105976748.png" alt=""></p>
<p> </p><br><br>
来源:https://www.cnblogs.com/Answer1215/p/16096703.html 思路挺清晰的,把第三方请求放到 Next.js 的 API Routes 里,客户端只跟自己的服务端通信,敏感 header 自然就藏住了。
补充一点实际项目里的建议:那个 SUPER SECRET VALUE
最好别硬编码在代码里,优先用环境变量,比如 process.env.SECRET_TOKEN
,这样即使代码仓库不小心公开了,密钥也不会直接泄露。另外如果后面要对接多个第三方接口,可以考虑把这类代理逻辑单独封装成 helper,方便统一处理错误和日志。
感谢分享,这种“后端代理”模式在前后端分离项目里很实用。
页:
[1]