JAVASCRIPT
Create a Node.js API Proxy to Protect Sensitive Keys
Securely integrate third-party APIs in frontend applications by proxying requests through a Node.js server to hide API keys and bypass CORS issues effectively.
const express = require('express');
const axios = require('axios'); // or 'node-fetch'
const cors = require('cors');
require('dotenv').config(); // Load environment variables from .env file
const app = express();
const PORT = process.env.PORT || 3000;
const EXTERNAL_API_BASE_URL = 'https://api.example.com';
const EXTERNAL_API_KEY = process.env.EXTERNAL_API_KEY; // Keep API key in .env
app.use(cors()); // Enable CORS for all routes, or configure specific origins
app.use(express.json());
// Proxy endpoint
app.get('/api/proxy/external-data', async (req, res) => {
try {
// Construct the external API URL, potentially using query params from client
const externalUrl = `${EXTERNAL_API_BASE_URL}/data${req.url.replace('/api/proxy/external-data', '')}`;
const response = await axios.get(externalUrl, {
headers: {
'Authorization': `Bearer ${EXTERNAL_API_KEY}`, // Add sensitive header here
'Content-Type': 'application/json'
},
params: req.query // Forward query parameters from the client
});
// Forward the external API's response status and data to the client
res.status(response.status).json(response.data);
} catch (error) {
console.error('Proxy Error:', error.message);
if (error.response) {
res.status(error.response.status).json(error.response.data);
} else {
res.status(500).json({ message: 'Internal Server Error' });
}
}
});
// Example: Proxy a POST request
app.post('/api/proxy/external-action', async (req, res) => {
try {
const externalUrl = `${EXTERNAL_API_BASE_URL}/action`;
const response = await axios.post(externalUrl, req.body, {
headers: {
'Authorization': `Bearer ${EXTERNAL_API_KEY}`,
'Content-Type': 'application/json'
}
});
res.status(response.status).json(response.data);
} catch (error) {
console.error('Proxy POST Error:', error.message);
if (error.response) {
res.status(error.response.status).json(error.response.data);
} else {
res.status(500).json({ message: 'Internal Server Error' });
}
}
});
app.listen(PORT, () => {
console.log(`Proxy server running on http://localhost:${PORT}`);
});
How it works: This Node.js snippet, using Express, creates a server-side proxy for external API calls. This pattern is crucial for frontend applications for two main reasons: firstly, it allows you to securely hide sensitive API keys and credentials from the client-side code by storing them on the server. Secondly, it helps bypass Cross-Origin Resource Sharing (CORS) restrictions, as the frontend makes a same-origin request to your proxy, and the proxy then makes the cross-origin request to the external API.