JAVASCRIPT
Securing API Keys on the Server-Side and Proxying Requests
Securely manage and proxy API keys from your Node.js backend. Protect sensitive credentials by preventing direct exposure in client-side code, enhancing application security.
// server.js (Node.js with Express)
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch'); // Requires 'npm install node-fetch express cors dotenv'
require('dotenv').config(); // Load environment variables from .env file
const app = express();
const port = process.env.PORT || 3000;
// Use CORS middleware to allow requests from your frontend origin
// IMPORTANT: In production, restrict to your specific frontend URL(s)
app.use(cors({ origin: 'http://localhost:5173' })); // Example for a Vite dev server
// Middleware to parse JSON bodies
app.use(express.json());
// Endpoint to proxy requests to an external API using a server-side API key
app.get('/api/proxy/external-service', async (req, res) => {
const EXTERNAL_API_KEY = process.env.EXTERNAL_API_KEY; // Stored securely in .env
const EXTERNAL_API_BASE_URL = 'https://api.external-service.com';
// Example: construct endpoint and params based on client request
const { param1, param2 } = req.query;
const externalEndpoint = `/data?param1=${param1}¶m2=${param2}`;
if (!EXTERNAL_API_KEY) {
return res.status(500).json({ error: 'Server configuration error: API key missing.' });
}
try {
const response = await fetch(`${EXTERNAL_API_BASE_URL}${externalEndpoint}`, {
headers: {
'Authorization': `Bearer ${EXTERNAL_API_KEY}`, // Use server-side key
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`External API error: ${response.status} - ${errorBody}`);
}
const data = await response.json();
res.json(data); // Send data back to client
} catch (error) {
console.error('Error proxying request:', error.message);
res.status(500).json({ error: 'Failed to fetch data from external service.' });
}
});
app.listen(port, () => {
console.log(`Proxy server listening at http://localhost:${port}`);
});
// --- .env file example (in the same directory as server.js) ---
// EXTERNAL_API_KEY="your_super_secret_api_key_here"
How it works: This Node.js Express snippet demonstrates how to securely manage sensitive API keys by proxying requests through your backend. Instead of exposing API keys directly in client-side code, the client requests data from your server, which then makes the actual authenticated call to the third-party API using a securely stored `EXTERNAL_API_KEY` from environment variables. This pattern prevents credential leakage and enhances application security.