[Next.js] Hide Sensitive Information from the Consumers of Next.js API

[复制链接]
发表于 2022-4-3 17:39:00 | 显示全部楼层 |阅读模式

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.

 

async function getSuperSecretData() {
  const result = await fetch("https://jsonplaceholder.typicode.com/todos/1", {
    headers: {
      authorization: 'SUPER SECRET VALUE'
    }
  }).then(res => res.json())

  return result
}

async function handler(req, res) {
  const secretTodo = await getSuperSecretData()

  res.json({todo: secretTodo})
}

export default handler

authorization header won't be seen from the request in backend

 



来源:https://www.cnblogs.com/Answer1215/p/16096703.html
回复

使用道具 举报

发表于 2026-10-3 15:10:13 | 显示全部楼层
思路挺清晰的,把第三方请求放到 Next.js 的 API Routes 里,客户端只跟自己的服务端通信,敏感 header 自然就藏住了。  

补充一点实际项目里的建议:那个
  1. SUPER SECRET VALUE
复制代码
最好别硬编码在代码里,优先用环境变量,比如
  1. process.env.SECRET_TOKEN
复制代码
,这样即使代码仓库不小心公开了,密钥也不会直接泄露。另外如果后面要对接多个第三方接口,可以考虑把这类代理逻辑单独封装成 helper,方便统一处理错误和日志。  

感谢分享,这种“后端代理”模式在前后端分离项目里很实用。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

圆梦公社,专注于为全球华人提供纯粹技术交流的地方,请勿发布任何政治及违法的言论。如有相关侵权、举报、投诉及建议等,请发 E-mail:dzh188@hotmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部