JAVASCRIPT

Create a Node.js Proxy for External APIs to Bypass CORS

Set up a simple Node.js Express server as a proxy to make requests to external APIs, effectively bypassing Cross-Origin Resource Sharing (CORS) restrictions from client-side code.

// server.js
const express = require('express');
const axios = require('axios');
const cors = require('cors'); // Required for allowing frontend to talk to this proxy

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

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

// Middleware to parse JSON bodies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Define a proxy endpoint
app.all('/proxy/:apiName/*', async (req, res) => {
  // In a real application, you would configure actual external API bases
  // based on `apiName` or other indicators. For example:
  // const apiMap = { 
  //   'github': 'https://api.github.com',
  //   'weather': 'https://api.openweathermap.org/data/2.5'
  // };
  // const externalApiBase = apiMap[req.params.apiName];
  // if (!externalApiBase) { return res.status(404).send('API not found'); }

  // For this example, let's assume a single external API endpoint for simplicity.
  const externalApiBase = 'https://jsonplaceholder.typicode.com'; // Example external API

  const path = req.params[0]; // The rest of the path after /proxy/:apiName/
  const externalUrl = `${externalApiBase}/${path || ''}`;

  console.log(`Proxying ${req.method} request to: ${externalUrl}`);

  try {
    const config = {
      method: req.method,
      url: externalUrl,
      headers: {
        // Forward relevant headers, or add new ones
        'Content-Type': req.headers['content-type'] || 'application/json',
        // Example: 'Authorization': `Bearer ${process.env.EXTERNAL_API_TOKEN}`
      },
      params: req.query, // Forward query parameters
      data: req.body, // Forward request body for POST, PUT, PATCH
    };

    const apiResponse = await axios(config);

    // Forward the external API's response status and data to the client
    res.status(apiResponse.status).send(apiResponse.data);

  } catch (error) {
    console.error(`Proxy error for ${externalUrl}:`, error.message);
    if (error.response) {
      res.status(error.response.status).send(error.response.data);
    } else if (error.request) {
      res.status(503).send({ message: 'No response from external API.' });
    } else {
      res.status(500).send({ message: 'Internal proxy error.' });
    }
  }
});

app.get('/', (req, res) => {
    res.send('Node.js API Proxy is running. Use /proxy/:apiName/* to access external APIs.');
});

app.listen(PORT, () => {
  console.log(`Proxy server listening on port ${PORT}`);
  console.log(`To run: npm init -y && npm install express axios cors && node server.js`);
  console.log(`Example client-side usage: fetch('http://localhost:${PORT}/proxy/todos/1')`);
});
How it works: This Node.js Express snippet creates a simple server-side proxy. Frontend applications can make requests to this proxy, which then forwards them to an external API. This pattern is crucial for bypassing CORS restrictions when the external API cannot be directly accessed from the client-side. It also allows for centralizing API keys, performing server-side logic (like rate limiting or data transformation), and hiding sensitive configuration before forwarding requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs