You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在客户端渲染React应用中实现服务端API请求以保护敏感凭证?

无需全量SSR,在React 18中安全执行带敏感凭证的API调用

当然可以实现,不用把整个应用改成SSR,以下几个方案都能确保敏感API调用在服务端执行,避免数据泄露:

1. 搭建API代理服务器

在前端和目标API之间加一层自己的服务端代理,前端只调用这个代理接口,由代理服务器携带敏感凭证去请求目标API,敏感数据全程不会暴露给客户端。

比如用Express快速写个代理:

// 服务端代理代码(Express)
const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

app.post('/api/proxy-target', async (req, res) => {
  try {
    // 敏感凭证存在服务端环境变量里,前端碰不到
    const sensitiveCredentials = process.env.SECRET_KEY;
    const response = await axios.post('https://目标API地址', {
      ...req.body, // 前端传的非敏感数据
      credentials: sensitiveCredentials
    });
    res.json(response.data);
  } catch (error) {
    res.status(error.response?.status || 500).json({ error: error.message });
  }
});

app.listen(3001, () => console.log('代理服务器运行在3001端口'));

前端React里调用代理接口就行,不用带敏感信息:

// React前端代码
const callApi = async () => {
  try {
    const response = await fetch('http://localhost:3001/api/proxy-target', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ nonSensitiveData: '需要传递的普通数据' })
    });
    const data = await response.json();
    console.log('接口返回数据:', data);
  } catch (error) {
    console.error('请求失败:', error);
  }
};

2. 用React 18的Server Components(服务器组件)

React 18支持的Server Components不需要全量SSR,你可以在组件树里单独用这类组件执行敏感API调用——它们的代码完全在服务端运行,不会打包发送到客户端,敏感凭证自然不会泄露。

比如创建一个Server Component(部分框架需要用.server.js后缀区分,比如Next.js):

// DataFetcher.server.js - 服务器组件
async function fetchDataWithCredentials() {
  const sensitiveCredentials = process.env.SECRET_KEY;
  const response = await fetch('https://目标API地址', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      credentials: sensitiveCredentials,
      otherData: '需要传递的普通数据'
    })
  });
  return response.json();
}

export default async function DataFetcher() {
  const data = await fetchDataWithCredentials();
  return <div>从API获取的数据:{JSON.stringify(data)}</div>;
}

然后在普通客户端组件里引入这个服务器组件:

// ClientComponent.js - 客户端组件
'use client';
import DataFetcher from './DataFetcher.server';

export default function ClientComponent() {
  return (
    <div>
      <h3>这是客户端组件</h3>
      {/* 服务器组件的逻辑在服务端执行,前端看不到敏感代码 */}
      <DataFetcher />
    </div>
  );
}

3. 使用无服务器函数/边缘函数

如果不想维护完整服务器,可以用Vercel Serverless Functions、Cloudflare Workers这类无服务器服务,本质也是代理逻辑,但不用自己管服务器运维。

比如写个Vercel的无服务器函数:

// api/proxy.js
export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: '只支持POST请求' });
  }
  try {
    const sensitiveCredentials = process.env.SECRET_KEY;
    const response = await fetch('https://目标API地址', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...req.body,
        credentials: sensitiveCredentials
      })
    });
    const data = await response.json();
    res.status(response.status).json(data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

前端直接调用这个函数的接口即可,敏感数据全程在服务端处理。

总结

React 18里执行服务端API请求完全不需要依赖全量SSR,上面三个方案都能满足需求——核心逻辑就是把带敏感凭证的API调用放在服务端执行,前端只负责非敏感的交互和数据展示。

内容的提问来源于stack exchange,提问作者Adel Stiti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 03:23:10