Solana

Solana Beta is live. Try BoltRPC Solana endpoints free - start your trial now.

RPC API Key Security: Best Practices for Production

How to protect your blockchain RPC API keys in production. Covers environment variables, backend proxies, IP whitelisting, key rotation and what happens when a key is compromised.

BoltRPC
BoltRPC Team
8 min read
RPC API Key Security: Best Practices for Production

RPC API Key Security: Best Practices for Production

Your RPC API key is the credential that authenticates your application with your node provider. If it leaks, anyone can drain your request quota, run up your bill, or use your endpoint for their own traffic.

This guide covers every layer of RPC key security: from the basics of keeping keys out of code, to production-grade proxy patterns and incident response.


The Most Common Mistake: Keys in Frontend Code

The fastest way to leak an RPC key is to embed it directly in client-side JavaScript.

// NEVER do this — visible to anyone who views page source
const provider = new ethers.JsonRpcProvider(
  'https://eu.endpoints.matrixed.link/rpc/ethereum?auth=MY_SECRET_KEY'
);

Any key embedded in frontend code is public. Browser developer tools, view-source, npm bundle analyzers: all expose it instantly. Bots scan GitHub and npm packages continuously looking for leaked credentials.


Layer 1: Environment Variables

The baseline. Never hardcode keys. Always load from environment.

# .env (never commit this file)
BOLTRPC_API_KEY=your_key_here
BOLTRPC_RPC_URL=https://eu.endpoints.matrixed.link/rpc/ethereum
// Node.js / server-side
const provider = new ethers.JsonRpcProvider(
  `${process.env.BOLTRPC_RPC_URL}?auth=${process.env.BOLTRPC_API_KEY}`
);
# .gitignore — always include these
.env
.env.local
.env.production
.env*.local

For CI/CD pipelines: store keys in your platform’s secret manager (GitHub Actions Secrets, AWS Secrets Manager, Doppler, HashiCorp Vault). Never pass keys as plain environment variables through public build logs.


Layer 2: Backend Proxy (Required for Frontend Apps)

If your dApp makes RPC calls from the browser, route them through a backend proxy. Your API key stays on the server. The frontend never sees it.

Browser → Your API → Backend Proxy → RPC Provider

                    API key lives here only

Simple Node.js proxy:

// server.js
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';

const app = express();

// Rate limiting middleware
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 100,            // 100 requests per IP per minute
  message: 'Too many requests'
});

app.use('/rpc', limiter);

// Proxy with injected auth — frontend never sees the key
app.use('/rpc', createProxyMiddleware({
  target: 'https://eu.endpoints.matrixed.link',
  changeOrigin: true,
  pathRewrite: { '^/rpc': `/rpc/ethereum?auth=${process.env.BOLTRPC_API_KEY}` },
  on: {
    proxyReq: (proxyReq, req) => {
      // Log requests for monitoring
      console.log(`RPC proxy: ${req.ip} → ${req.body?.method}`);
    }
  }
}));

app.listen(3000);

Frontend connects to your proxy, not the provider directly:

// Frontend — no key visible
const provider = new ethers.JsonRpcProvider('https://yourapp.com/rpc');

Layer 3: IP Allowlisting

If your RPC calls come from known server IPs (backend services, bots, indexers), restrict your key to those IPs. Any request from an unexpected IP is rejected even if the key is valid.

Most providers support IP allowlisting in their dashboard. Configure it for:

  • Your production server IPs
  • Your CI/CD runner IPs (if they make RPC calls during testing)
  • Your team’s office IP (for local development keys, use a separate key)

Use separate keys per environment:

production.key  → IP allowlist: production server IPs only
staging.key     → IP allowlist: staging server IPs only
development.key → No IP restriction (rotating developer IPs)

Layer 4: Separate Keys per Application

If you run multiple applications or services, use a separate API key per application.

Why this matters:

  • If one key is compromised, only that application is affected
  • You can track usage per application
  • You can rotate one key without affecting others
  • You can set different rate limits per key if your provider supports it

Naming convention:

boltrpc-production-main-api
boltrpc-production-indexer
boltrpc-staging-api
boltrpc-development-nito

Layer 5: Request Method Restrictions

Some providers allow you to restrict which RPC methods a key can call. A key used only for reading data should not be able to call eth_sendRawTransaction.

Common restriction patterns:

Key purposeAllowed methods
Read-only dashboardeth_call, eth_getLogs, eth_getBalance, eth_blockNumber
Transaction submittereth_sendRawTransaction, eth_getTransactionReceipt
Monitoring boteth_subscribe, eth_getLogs, eth_blockNumber

Apply the principle of least privilege: each key only gets the permissions it needs.


Layer 6: Monitor for Anomalies

Set up alerts for unusual usage patterns:

// Track RPC usage in your application
async function monitoredRpcCall(method, params) {
  const start = Date.now();

  try {
    const result = await provider.send(method, params);
    const duration = Date.now() - start;

    // Log to your monitoring system
    metrics.record({
      method,
      duration,
      success: true,
      timestamp: Date.now()
    });

    return result;
  } catch (error) {
    metrics.record({
      method,
      success: false,
      error: error.code,
      timestamp: Date.now()
    });
    throw error;
  }
}

Alert on:

  • Sudden spike in request volume (possible key leak)
  • Requests from unexpected IPs
  • Methods being called that your application should not be using
  • Error rate exceeding 5% (possible infrastructure issue or attack)

Layer 7: Key Rotation

Rotate API keys regularly. At minimum:

  • Every 90 days as routine maintenance
  • Immediately after any suspected compromise
  • When a team member with key access leaves

Zero-downtime rotation:

# Step 1: Create new key in provider dashboard
NEW_KEY=your_new_key

# Step 2: Update secret manager / environment
aws secretsmanager update-secret --secret-id boltrpc-api-key --secret-string $NEW_KEY

# Step 3: Deploy application (picks up new key from secret manager)
# Traffic automatically uses new key

# Step 4: Revoke old key in provider dashboard
# Old key is now dead — no traffic interruption

What to Do If a Key Is Compromised

Immediate steps (do these first, in order):

  1. Revoke the key immediately. Log into your provider dashboard and delete the compromised key. Do this before anything else.
  2. Create a new key. Generate a replacement.
  3. Update all applications. Deploy the new key to all services that used the compromised one.
  4. Check your usage logs. How much traffic went through the compromised key? What methods were called? Were there any transaction submissions?
  5. Scan for other leaks. If a key leaked once, there may be other credentials exposed in the same place.

Common leak sources to check:

  • GitHub history (use git log -p | grep YOUR_KEY)
  • npm published packages
  • Docker images pushed to public registries
  • CI/CD build logs
  • Slack/Discord messages
  • Browser local storage or session storage

GitHub Secret Scanning

GitHub scans public repositories for known API key formats automatically. Some providers are registered with GitHub’s secret scanning program. If your key is pushed to a public repo, GitHub notifies the provider who can auto-revoke it.

Do not rely on this as your safety net. Use .gitignore and pre-commit hooks instead:

# Install pre-commit hook to catch secrets before push
pip install detect-secrets
detect-secrets scan > .secrets.baseline
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.4.0
    hooks:
      - id: detect-secrets
        args: ['--baseline', '.secrets.baseline']

Security Checklist

Before going to production, verify:

  • No API keys in frontend JavaScript or mobile app bundles
  • All keys loaded from environment variables or secret manager
  • .env files in .gitignore
  • Backend proxy in place for any browser-side RPC calls
  • IP allowlisting configured for server keys
  • Separate keys per environment (production, staging, development)
  • Separate keys per application/service
  • Usage monitoring and anomaly alerts configured
  • Key rotation schedule documented
  • Incident response process documented

FAQ

Can I use my RPC key in a mobile app?

No. Mobile app bundles can be decompiled and keys extracted. Route mobile RPC traffic through your backend proxy, same as frontend web apps.

What if I need RPC access in a browser extension?

Browser extensions are also reversible. Use a backend proxy or connect to a public endpoint for non-sensitive queries. For authenticated endpoints, implement user-level authentication so each user has their own credentials rather than sharing one API key.

How often should I rotate keys?

Every 90 days for routine rotation. Immediately after any team member with key access leaves, any suspected compromise, or any deployment to a new environment.

Is it safe to use different keys for testing and production?

Yes, this is the recommended approach. Production keys should have IP restrictions and minimal permissions. Development keys can be more permissive but should never be used in production environments.

What happens if someone uses my key to run up my quota?

Contact your provider immediately. Most providers can show you the IP addresses and request patterns that used your key. Revoke the key first, then investigate. Some providers offer usage caps or alerts that trigger before your quota is exhausted.


BoltRPC API keys are authenticated via URL parameter (?auth=YOUR_KEY). Apply all the patterns in this guide (backend proxy, IP allowlisting, environment variables) regardless of provider.

Start your free 2-week trial: trial.boltrpc.io

Related: RPC Failover Guide | How to Handle RPC Errors

Frequently asked questions

Ready to build with high-performance RPC?

Start your free trial today. No credit card required. Access 20+ networks instantly.

Disclaimer: The content in this article is for informational purposes only and does not constitute financial, legal, or technical advice. Code examples and configurations are provided as-is. Always verify information with official documentation and test thoroughly in your own environment before deploying to production.

Continue reading