JAVASCRIPT
Build an API Proxy with Node.js and Express
Create a simple server-side proxy using Node.js and Express to securely fetch data from a third-party API, bypassing CORS issues and protecting sensitive API keys.
const express = require('express');
const fetch = require('node-fetch'); // For Node.js, install with `npm install node-fetch@2` for CommonJS or use native fetch in newer Node.js
const cors = require('cors'); // Install with `npm install cors`
const dotenv = require('dotenv'); // Install with `npm install dotenv`
dotenv.config(); // Load environment variables from .env file
const app = express();
const PORT = process.env.PORT || 3000;
const TARGET_API_URL = 'https://jsonplaceholder.typicode.com/posts'; // Example public API
const API_KEY = process.env.THIRD_PARTY_API_KEY; // Store sensitive keys in .env
// Enable CORS for all origins, or configure specific origins for production
app.use(cors());
// Middleware to log requests (optional)
app.use((req, res, next) => {
console.log(`Proxying request: ${req.method} ${req.originalUrl}`);
next();
});
// Proxy endpoint
app.get('/api/proxy', async (req, res) => {
try {
// Construct the target URL. You might append query parameters from req.query
const fullTargetUrl = `${TARGET_API_URL}${req.query.id ? '/' + req.query.id : ''}`;
// Example of adding an API key to the request to the third-party API
const headers = {
'Content-Type': 'application/json',
// 'Authorization': `Bearer ${API_KEY}` // Uncomment if your API uses Bearer token auth
// 'x-api-key': API_KEY // Uncomment if your API uses a custom header for API key
};
const response = await fetch(fullTargetUrl, { headers: headers });
if (!response.ok) {
return res.status(response.status).json({ error: 'Failed to fetch from external API' });
}
const data = await response.json();
res.json(data); // Send the data received from the external API back to the client
} catch (error) {
console.error('Proxy error:', error);
res.status(500).json({ error: 'Internal server error during proxy request' });
}
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
console.log(`Try: http://localhost:${PORT}/api/proxy`);
console.log(`Try: http://localhost:${PORT}/api/proxy?id=1`);
});
How it works: This Node.js and Express snippet creates a simple API proxy. Frontend applications can make requests to `/api/proxy` on this server, which then securely forwards the request to a third-party API (e.g., `jsonplaceholder.typicode.com`), adds necessary authentication (like an API key from environment variables), and returns the third-party API's response. This pattern helps mitigate Cross-Origin Resource Sharing (CORS) issues and prevents exposure of sensitive API keys in client-side code.