JAVASCRIPT
Node.js Proxy Server for Bypassing Client-Side CORS
Set up a simple Node.js (Express) proxy to securely bypass client-side CORS restrictions for integrating with external APIs from your frontend.
const express = require('express');
const axios = require('axios'); // or 'node-fetch'
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
// Use CORS middleware for your proxy to allow frontend access
// Configure origins as needed for production environment
app.use(cors());
app.use(express.json()); // For parsing application/json
// Proxy endpoint
app.all('/proxy/:apiPath(*)', async (req, res) => {
const targetUrl = `https://external-api.com/${req.params.apiPath}`; // The actual external API URL
try {
const config = {
method: req.method,
url: targetUrl,
headers: { ...req.headers },
data: req.body, // For POST, PUT, PATCH
params: req.query // For GET
};
// Remove headers that might cause issues or are handled by the proxy
delete config.headers.host;
delete config.headers['content-length'];
delete config.headers.connection;
delete config.headers['accept-encoding']; // Let axios handle compression
const response = await axios(config);
// Forward all headers and status from the external API to the client
res.set(response.headers);
res.status(response.status).send(response.data);
} catch (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('Error proxying request:', error.response.status, error.response.data);
res.status(error.response.status).send(error.response.data);
} else if (error.request) {
// The request was made but no response was received
console.error('No response received from target API:', error.request);
res.status(500).send('No response from target API');
} else {
// Something happened in setting up the request that triggered an Error
console.error('Request setup error:', error.message);
res.status(500).send('Error setting up proxy request');
}
}
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
});
How it works: This Node.js snippet creates a simple Express-based proxy server to bypass client-side Cross-Origin Resource Sharing (CORS) restrictions. When a frontend application needs to access a third-party API that doesn't provide appropriate CORS headers, it can route its requests through this proxy. The proxy acts as an intermediary, fetching data from the external API (server-to-server, avoiding browser CORS) and then forwarding the response back to the frontend, which is allowed because the proxy server is on the same origin (or explicitly allowed via its own CORS configuration).