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

React JS隐藏WebService调用凭证的最佳实践(Heroku部署)

解决React + Heroku应用中API凭证暴露的最佳实践

Hey there, let's work through fixing those credential exposure issues in your React app deployed on Heroku—this is a super common pitfall, so you're definitely not alone here.

1. 绝对禁止在客户端代码中存储敏感信息

First off: React apps are compiled and sent to the user's browser, any hardcoded credentials, API keys, or tokens in your frontend code will be visible to anyone who inspects your bundle.js or uses browser dev tools. Even if you use .env.local with REACT_APP_ prefixes, those values get baked into the compiled code—so never put sensitive data there.

2. 搭建后端代理层(最可靠的解决方案)

The gold standard here is to add a lightweight Node.js/Express backend to your Heroku app, acting as a middleman between your React frontend and the external API. This way, all sensitive credentials live only on the server (Heroku's runtime environment), and your frontend never touches them.

Here's a quick example of how to set this up:

Backend (server.js)

require('dotenv').config();
const express = require('express');
const axios = require('axios');
const path = require('path');
const app = express();

// Serve React's static build files
app.use(express.static(path.join(__dirname, 'build')));

// Proxy endpoint for your external API call
app.get('/api/proxy-data', async (req, res) => {
  try {
    const externalResponse = await axios.get('https://your-external-api.com/protected-endpoint', {
      headers: {
        'Authorization': `Bearer ${process.env.YOUR_SECRET_API_TOKEN}`,
        'API-Key': process.env.ANOTHER_SENSITIVE_KEY
      }
    });
    res.json(externalResponse.data);
  } catch (error) {
    res.status(error.response?.status || 500).json({ error: error.message });
  }
});

// Catch-all route to serve React app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Proxy server running on port ${PORT}`));

Frontend (React component)

const fetchProtectedData = async () => {
  try {
    // Call your backend's proxy endpoint, not the external API directly
    const response = await fetch('/api/proxy-data');
    const data = await response.json();
    // Use the data in your component
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
};

3. 正确配置Heroku环境变量

Once you have your backend set up, add your sensitive credentials to Heroku's config vars:

  • Go to your Heroku app dashboard → Settings → Config Vars
  • Add key-value pairs like YOUR_SECRET_API_TOKEN=your-actual-token
  • Alternatively, use the Heroku CLI: heroku config:set YOUR_SECRET_API_TOKEN=your-actual-token

These variables are injected into your backend's runtime environment and are never exposed to the client.

4. 用授权流程替代全局凭证(如果适用)

If you're working with an API that supports user-specific authorization (like OAuth2), use flows like the Authorization Code Flow instead of using a global server-side token. This way, users authenticate with the external service directly, and your app uses their individual access tokens—so you never have to expose your own credentials to the frontend.

5. 额外安全加固

  • Force HTTPS: Heroku automatically supports HTTPS—make sure your app is only accessed via https:// to prevent man-in-the-middle attacks.
  • Restrict CORS: In your backend, use a CORS middleware to only allow requests from your Heroku app's domain. For example:
    const cors = require('cors');
    app.use(cors({ origin: 'https://your-heroku-app-name.herokuapp.com' }));
    
  • Rotate credentials regularly: Even with all safeguards, periodically rotating your API keys and tokens reduces risk if a breach ever occurs.

These steps should fully eliminate the risk of credential exposure in your app. If you hit any snags with the setup, feel free to share more details about your specific API integration!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:33:44