JAVASCRIPT

Create a Simple API Proxy to Bypass CORS Issues (Node.js/Express)

Resolve cross-origin resource sharing (CORS) restrictions by setting up a basic Node.js Express proxy to securely forward frontend API requests.

// 1. Install Express and node-fetch: npm install express node-fetch
// 2. Create server.js:

const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors'); // Optional: for allowing specific origins to access this proxy

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

// Use CORS middleware if your frontend is on a different origin than this proxy
// app.use(cors({ origin: 'http://localhost:3000' })); 
app.use(cors()); // Allow all origins for simplicity in example

// Define the target API base URL (e.g., a third-party API)
const TARGET_API_BASE_URL = 'https://api.example.com'; // Replace with your actual target API
const API_KEY = process.env.API_KEY || 'YOUR_SECURE_API_KEY'; // Load from .env in production

app.get('/api-proxy/:endpoint*', async (req, res) => {
  const endpoint = req.params.endpoint + req.params[0]; // Capture the full endpoint path
  const targetUrl = `${TARGET_API_BASE_URL}/${endpoint}${req.url.includes('?') ? '&' : '?'}_=${API_KEY}`; // Append API key

  console.log(`Proxying request to: ${targetUrl}`);

  try {
    const apiResponse = await fetch(targetUrl, {
      method: req.method,
      headers: { 'Content-Type': 'application/json' }
      // Add other headers as needed, e.g., Authorization: `Bearer ${API_KEY}` if target API uses it in header
    });
    
    // Forward headers from target API to client, e.g., Content-Type
    res.set(apiResponse.headers.raw());
    res.status(apiResponse.status).send(await apiResponse.text());
  } catch (error) {
    console.error('Proxy error:', error);
    res.status(500).json({ error: 'Failed to proxy request' });
  }
});

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

// Frontend JavaScript to use the proxy:
// fetch('/api-proxy/data?param=value')
//   .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 creates a simple server-side proxy to circumvent Cross-Origin Resource Sharing (CORS) restrictions often encountered when a frontend application tries to directly access a third-party API. The frontend requests data from its own server (the proxy), which then securely forwards the request to the target API, retrieves the response, and sends it back to the frontend. This approach keeps sensitive API keys hidden on the server and ensures that browser security policies don't block legitimate API calls.

Need help integrating this into your project?

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

Hire DigitalCodeLabs