JAVASCRIPT

Build a Node.js API Proxy for Secure External API Access

Create a secure Node.js backend proxy to call external APIs, solving CORS issues and safely protecting sensitive API keys from client-side exposure.

const express = require('express');
const fetch = require('node-fetch'); // For making HTTP requests from Node.js
const cors = require('cors');
require('dotenv').config(); // For managing environment variables

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

// Enable CORS for client-side applications (adjust origin as needed)
app.use(cors({ origin: 'http://localhost:8080' })); 

// Route to proxy requests to an external API
app.get('/api/proxy/external-service', async (req, res) => {
  const EXTERNAL_API_URL = process.env.EXTERNAL_API_BASE_URL + '/data'; // External API endpoint
  const EXTERNAL_API_KEY = process.env.EXTERNAL_API_KEY; // Stored securely in .env

  if (!EXTERNAL_API_URL || !EXTERNAL_API_KEY) {
    return res.status(500).json({ error: 'External API configuration missing.' });
  }

  try {
    // Make the request to the external API from the Node.js server
    const apiResponse = await fetch(EXTERNAL_API_URL, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${EXTERNAL_API_KEY}`, // API key used on server-side
        'Content-Type': 'application/json'
      }
    });

    if (!apiResponse.ok) {
      const errorData = await apiResponse.json().catch(() => ({ message: apiResponse.statusText }));
      return res.status(apiResponse.status).json({ error: errorData.message || 'External API error' });
    }

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

app.listen(PORT, () => {
  console.log(`Proxy server running on port ${PORT}`);
  console.log('Access via: http://localhost:3000/api/proxy/external-service');
});
How it works: This Node.js snippet demonstrates how to create a simple API proxy using Express.js. A backend proxy is invaluable for API integrations because it allows you to: 1. **Hide API Keys:** Sensitive API keys or credentials are never exposed to the client-side browser, residing securely on your server. 2. **Bypass CORS:** The client application makes a request to your same-origin Node.js server, which then fetches data from the external API, circumventing Cross-Origin Resource Sharing (CORS) restrictions. 3. **Modify Requests/Responses:** You can inject custom headers, filter data, or transform responses before sending them to the client. This example sets up an Express route (`/api/proxy/external-service`) that receives client requests, fetches data from an external API using `node-fetch`, includes a securely stored API key (`process.env.EXTERNAL_API_KEY`), and then forwards the external API's response back 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