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

React全公开无登录网站API Key保护方案咨询

How to Protect API Keys in a Public React App (No Login/Secured Zones)

Hey there! I totally get why this is such a frustrating problem—you’ve got a fully public React app that relies entirely on third-party APIs, but exposing your API keys directly in the frontend is a massive security risk, and standard solutions might not feel like they fit your no-login setup. Let’s break down the most practical, secure ways to handle this:

1. Use a Backend Proxy Server (Most Reliable Approach)

The gold standard here is to route all your API requests through your own backend server. Your React app sends requests to your backend, which then adds the API key and forwards the request to the third-party service. This way, your API key never leaves the server, so it’s completely hidden from frontend users.

Example Setup:

Backend Proxy (Node.js/Express)

const express = require('express');
const axios = require('axios');
const app = express();

// Store your API key in environment variables—never hardcode it!
const THIRD_PARTY_API_KEY = process.env.THIRD_PARTY_API_KEY;

// Proxy endpoint for your frontend to call
app.get('/api/proxy-third-party', async (req, res) => {
  try {
    const thirdPartyResponse = await axios.get('https://third-party-api.com/your-endpoint', {
      headers: {
        'Authorization': `Bearer ${THIRD_PARTY_API_KEY}`,
        // Add any other required headers for the third-party API
      },
      params: req.query // Pass along any query params from the frontend
    });

    res.json(thirdPartyResponse.data);
  } catch (error) {
    res.status(error.response?.status || 500).json({ 
      error: 'Failed to fetch data from third-party API' 
    });
  }
});

app.listen(3001, () => console.log('Proxy server running on port 3001'));

Frontend React Request

const fetchData = async () => {
  try {
    // Call your proxy endpoint instead of the third-party API directly
    const response = await fetch('/api/proxy-third-party?param=your-value');
    const data = await response.json();
    // Handle the returned data
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

Pros: 100% secure key storage, full control over request filtering/rate limiting.
Cons: Requires maintaining a backend server (though even a tiny Node.js service works, and platforms like Vercel/Netlify make deployment trivial).

2. Use Serverless Functions (Lightweight Proxy Alternative)

If you don’t want to manage a full backend server, serverless functions (like Vercel Functions, Netlify Functions, or AWS Lambda) are a perfect middle ground. They act as lightweight proxies, run only when requested, and require zero server maintenance.

Example Vercel Function:

// pages/api/proxy.js (Next.js/Vercel project)
import axios from 'axios';

export default async function handler(req, res) {
  const apiKey = process.env.THIRD_PARTY_API_KEY;
  
  try {
    const response = await axios.get('https://third-party-api.com/your-endpoint', {
      headers: { 'Authorization': `Bearer ${apiKey}` },
      params: req.query
    });
    res.status(200).json(response.data);
  } catch (err) {
    res.status(err.response?.status || 500).json({ error: err.message });
  }
}

Pros: No server management, low cost (often free for small traffic), same security as a full proxy.
Cons: Slightly limited compared to a full backend if you need advanced request handling.

3. Restrict API Keys (If Supported by the Third-Party)

Some third-party APIs let you restrict your keys to specific domains, IPs, or request limits. For example, Google Maps API allows you to set referrer restrictions so the key only works on your website’s domain.

This isn’t a standalone solution (a determined user could still grab the key and use it in a script from your domain), but it adds an extra layer of protection. Combine this with a proxy for best results.

What You Should Never Do

  • Never hardcode API keys in your React code: Even if you put them in a .env file with a REACT_APP_ prefix, they’ll be bundled into your static frontend files and visible via browser dev tools.
  • Never send API keys directly from the frontend: Any request from the browser can be inspected, so your key will be exposed instantly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:13:18