JAVASCRIPT
Node.js Express API Proxy for External Services
Set up a Node.js Express proxy to securely fetch data from external APIs, hide API keys, and bypass CORS issues for client-side applications.
const express = require('express');
const axios = require('axios'); // A promise-based HTTP client for the browser and node.js
const dotenv = require('dotenv');
dotenv.config(); // Load environment variables from .env file
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// Example proxy endpoint for a public API (e.g., GitHub API)
// This endpoint fetches user data from GitHub
app.get('/api/github/user/:username', async (req, res) => {
const { username } = req.params;
try {
const response = await axios.get(`https://api.github.com/users/${username}`, {
headers: {
// If GitHub required an API key, it would be passed here
// Authorization: `token ${process.env.GITHUB_API_TOKEN}`
}
});
res.json(response.data);
} catch (error) {
console.error('Error fetching GitHub user:', 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 endpoint requiring a secret API key (e.g., a hypothetical weather API)
app.get('/api/weather/:city', async (req, res) => {
const { city } = req.params;
const WEATHER_API_KEY = process.env.WEATHER_API_KEY; // Stored securely in .env
if (!WEATHER_API_KEY) {
return res.status(500).json({ message: 'Weather API key not configured.' });
}
try {
const response = await axios.get(`https://api.example.com/weather?city=${city}&apiKey=${WEATHER_API_KEY}`);
res.json(response.data);
} catch (error) {
console.error('Error fetching weather:', 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 listening on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to create a simple API proxy. It uses `axios` to make HTTP requests to external services from the server side. This pattern is highly useful for several reasons: it hides sensitive API keys from the client, allows you to bypass client-side CORS restrictions by acting as an intermediary, and can be used to aggregate data from multiple external APIs before sending a single, unified response to the client. Environment variables, loaded via `dotenv`, are used to securely manage API keys. Proper error handling ensures that external API failures are gracefully managed and communicated to the client.