JAVASCRIPT
Securely Access Third-Party APIs via Server-Side Proxy
Learn to protect sensitive API keys by making third-party API calls from your backend server, acting as a proxy to prevent exposure in client-side code.
// This is a simplified Node.js Express example.
// In a real application, ensure proper error handling, logging,
// and security practices (e.g., rate limiting, authentication for this proxy endpoint).
const express = require('express');
const fetch = require('node-fetch'); // For Node.js, fetch is not global by default
const cors = require('cors'); // To allow client-side requests to this proxy
const app = express();
const PORT = process.env.PORT || 3000;
// Load sensitive API key from environment variables.
// NEVER hardcode API keys directly in your code.
// For local development, use a .env file and a library like 'dotenv'.
// In production, configure environment variables in your hosting platform.
const THIRD_PARTY_API_KEY = process.env.THIRD_PARTY_API_KEY;
const THIRD_PARTY_API_BASE_URL = 'https://api.thirdparty.com/v1';
if (!THIRD_PARTY_API_KEY) {
console.error('THIRD_PARTY_API_KEY environment variable is not set!');
process.exit(1);
}
app.use(cors()); // Enable CORS for client-side applications
app.use(express.json()); // To parse JSON request bodies
// Proxy endpoint for a third-party API call
app.get('/api/proxy/data', async (req, res) => {
// Extract any necessary parameters from client request (e.g., query params, path params)
const { searchParam } = req.query;
if (!searchParam) {
return res.status(400).json({ error: 'Missing searchParam' });
}
try {
const thirdPartyUrl = `${THIRD_PARTY_API_BASE_URL}/resource?query=${searchParam}`;
const response = await fetch(thirdPartyUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${THIRD_PARTY_API_KEY}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorText = await response.text();
console.error(`Third-party API error: ${response.status} - ${errorText}`);
return res.status(response.status).json({
error: `Failed to fetch data from third-party API`,
details: errorText,
});
}
const data = await response.json();
res.json(data); // Send the data back to the client
} catch (error) {
console.error('Error in proxying third-party API request:', error);
res.status(500).json({ error: 'Internal server error while fetching external data.' });
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log('To test: curl "http://localhost:3000/api/proxy/data?searchParam=example"');
});
// Client-side JavaScript would then call:
// fetch('/api/proxy/data?searchParam=test')
// .then(response => response.json())
// .then(data => console.log(data))
// .catch(error => console.error('Client-side fetch error:', error));
How it works: This Node.js Express snippet demonstrates how to securely interact with third-party APIs that require sensitive API keys. Instead of exposing the key in client-side code, it sets up a backend proxy endpoint (`/api/proxy/data`). Client-side applications make requests to this backend endpoint, which then internally uses the `THIRD_PARTY_API_KEY` (loaded from environment variables, preventing exposure in source control or client bundles) to call the actual third-party API. The backend retrieves the data and forwards it back to the client. This pattern ensures that sensitive credentials are never accessible in the browser, significantly enhancing application security.