JAVASCRIPT

Implement a Server-Side API Proxy for CORS & Security

Learn to set up a Node.js/Express proxy to securely fetch data from third-party APIs, bypass CORS restrictions, and protect sensitive API keys on the server.

// server.js (Node.js with Express and node-fetch)
const express = require('express');
const fetch = require('node-fetch'); // or 'axios'
const cors = require('cors');
require('dotenv').config(); // For managing environment variables securely

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

// Allow CORS for client applications
app.use(cors());

// Example: Proxy endpoint for a third-party API
app.get('/api/proxy/external-data', async (req, res) => {
  const API_KEY = process.env.EXTERNAL_API_KEY; // Stored securely
  const EXTERNAL_API_URL = 'https://api.example.com/data'; // Target API

  if (!API_KEY) {
    return res.status(500).json({ error: 'API key not configured.' });
  }

  try {
    const response = await fetch(`${EXTERNAL_API_URL}?key=${API_KEY}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // Potentially add other headers required by the external API
      },
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`External API error: ${response.status} - ${JSON.stringify(errorData)}`);
    }

    const data = await response.json();
    res.json(data);
  } catch (error) {
    console.error('Proxy error:', error);
    res.status(500).json({ error: 'Failed to fetch data from external API.' });
  }
});

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

// To run this:
// 1. npm init -y
// 2. npm install express node-fetch cors dotenv
// 3. Create a .env file: EXTERNAL_API_KEY=your_actual_api_key
// 4. node server.js
How it works: This snippet demonstrates creating a simple Node.js Express server to act as a proxy for a third-party API. It allows client-side applications to fetch data from a backend endpoint (`/api/proxy/external-data`) which then securely makes the actual request to the external API. This architecture bypasses Cross-Origin Resource Sharing (CORS) issues and protects sensitive API keys by keeping them on the server, never exposing them directly to the client.

Need help integrating this into your project?

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

Hire DigitalCodeLabs