JAVASCRIPT
Secure Server-Side API Proxy with Node.js and Express
Learn to create a simple Node.js/Express proxy server to securely make requests to third-party APIs, circumvent CORS issues, and hide sensitive API keys.
// server.js
const express = require('express');
const fetch = require('node-fetch'); // For Node.js, install with `npm install node-fetch@2` for CommonJS
const cors = require('cors'); // Install with `npm install cors`
require('dotenv').config(); // Install with `npm install dotenv` for .env file
const app = express();
const port = process.env.PORT || 3000;
// Use CORS for cross-origin requests from your frontend
app.use(cors());
// Middleware to parse JSON bodies
app.use(express.json());
// Proxy endpoint for an external API
app.get('/api/proxy/external-service', async (req, res) => {
const externalApiKey = process.env.EXTERNAL_API_KEY; // Store in .env file
const externalApiBaseUrl = 'https://api.external-service.com';
const endpoint = req.query.endpoint || '/data'; // Example: /data, /users
const queryParams = new URLSearchParams(req.query);
queryParams.delete('endpoint'); // Remove our custom param
try {
const response = await fetch(`${externalApiBaseUrl}${endpoint}?${queryParams.toString()}`, {
headers: {
'Authorization': `Bearer ${externalApiKey}`, // Pass key securely from server
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
return res.status(response.status).json({ error: 'Failed to fetch from external API', details: errorData });
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Proxy API error:', error);
res.status(500).json({ error: 'Internal server error during proxy request' });
}
});
app.listen(port, () => {
console.log(`Proxy server listening at http://localhost:${port}`);
});
How it works: This Node.js with Express snippet sets up a simple server-side proxy. It allows a frontend application to make requests to `/api/proxy/external-service` which then, in turn, forwards the request to the actual external API. This pattern is crucial for hiding sensitive API keys from the client, bypassing Cross-Origin Resource Sharing (CORS) restrictions, and centralizing API calls. It uses `node-fetch` for making the actual external request and `dotenv` to load API keys from a `.env` file for security.