JAVASCRIPT

Create a Simple Node.js Proxy to Bypass CORS

Set up a lightweight Node.js Express server to act as an intermediary, effectively circumventing Cross-Origin Resource Sharing (CORS) issues when interacting with third-party APIs.

// server.js
const express = require('express');
const axios = require('axios');
const cors = require('cors'); // npm install express axios cors

const app = express();
const PORT = process.env.PORT || 3001;

// Enable CORS for all origins, or specify allowed origins for better security
app.use(cors());

// Example proxy endpoint
app.get('/proxy/:endpoint', async (req, res) => {
  const targetApiBaseUrl = 'https://api.example.com'; // The actual API you want to proxy
  const { endpoint } = req.params;
  const targetUrl = `${targetApiBaseUrl}/${endpoint}${req.url.slice(req.url.indexOf('?')) || ''}`; // Include query params

  try {
    const apiResponse = await axios.get(targetUrl, {
      headers: {
        // You might need to forward specific headers from the client or add API keys here
        // 'Authorization': `Bearer ${process.env.API_KEY}` 
      },
      params: req.query // Pass client query parameters to the target API
    });
    res.json(apiResponse.data);
  } catch (error) {
    console.error(`Proxy error for ${targetUrl}:`, error.message);
    if (error.response) {
      res.status(error.response.status).json(error.response.data);
    } else {
      res.status(500).json({ message: 'Internal Server Error' });
    }
  }
});

// For POST requests, you'll need `express.json()` and handle `axios.post`
// app.use(express.json());
// app.post('/proxy/:endpoint', async (req, res) => { /* ... similar logic with axios.post(targetUrl, req.body) ... */ });

app.listen(PORT, () => {
  console.log(`Proxy server running on port ${PORT}`);
});

// Client-side fetch example:
// fetch('http://localhost:3001/proxy/products?category=electronics')
//   .then(response => response.json())
//   .then(data => console.log(data))
//   .catch(error => console.error('Error fetching via proxy:', error));
How it works: This Node.js Express snippet sets up a simple proxy server. When a client-side application requests `http://localhost:3001/proxy/products`, the proxy server internally makes a request to `https://api.example.com/products`. Since the proxy runs on the server, it's not subject to browser-imposed CORS restrictions, allowing the client to safely access third-party APIs through the proxy. It's crucial to handle query parameters and potentially request bodies/headers when setting up such a proxy.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs