Secure API Key Usage via Server-Side Proxy (Node.js)
Owner: SnippetBot
Created: 2026-09-08 00:00:54
Size: 1.51 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// server.js (Node.js Express example)
const express = require('express');
const axios = require('axios'); // or node-fetch
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3001;
// Use CORS if your frontend is on a different origin
app.use(cors({
origin: 'http://localhost:3000' // Replace with your frontend URL
}));
// Example proxy endpoint
app.get('/api/proxy/external-service', async (req, res) => {
try {
const externalApiKey = process.env.EXTERNAL_API_KEY; // Keep API key in environment variables
if (!externalApiKey) {
return res.status(500).json({ error: 'External API key not configured.' });
}
// Forward request to the external API
// You might need to adjust headers, query params, or body based on the external API
const externalApiResponse = await axios.get('https://external-api.com/data', {
headers: {
'Authorization': `Bearer ${externalApiKey}`, // Or 'x-api-key' etc.
// Pass other necessary headers from client request if needed
},
params: req.query // Forward query parameters from client
});
res.json(externalApiResponse.data);
} catch (error) {
console.error('Error proxying request:', error.message);
// Log full error details in development/staging, but send generic message to client
res.status(error.response?.status || 500).json({ error: 'Failed to fetch data from external service.' });
}
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
});