JAVASCRIPT

Node.js Express API Proxy for CORS & Key Hiding

Create a simple Node.js Express proxy server to securely route client-side API requests, bypass CORS restrictions, and protect sensitive API keys from public exposure.

const express = require('express');
const axios = require('axios'); // Or use node-fetch for modern fetch API
const cors = require('cors'); // For handling CORS on the proxy itself
require('dotenv').config(); // For loading environment variables from .env

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

// --- Configuration ---
const TARGET_API_BASE_URL = process.env.TARGET_API_BASE_URL || 'https://api.example.com/v1';
const TARGET_API_KEY = process.env.TARGET_API_KEY; // Sensitive key, keep it in .env

if (!TARGET_API_KEY) {
  console.error('TARGET_API_KEY is not defined. Please set it in your .env file.');
  process.exit(1);
}
// -------------------

// Use CORS middleware to allow requests from your frontend origin
// For production, replace '*' with your specific frontend domain(s)
app.use(cors({ origin: '*' }));

// Middleware to parse JSON request bodies
app.use(express.json());

// Proxy endpoint
// Example: Frontend calls /api/data, proxy forwards to TARGET_API_BASE_URL/data
app.all('/api/*', async (req, res) => {
  const apiPath = req.params[0]; // Gets the part after /api/
  const targetUrl = `${TARGET_API_BASE_URL}/${apiPath}`;

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

  try {
    const axiosConfig = {
      method: req.method,
      url: targetUrl,
      headers: {
        'Authorization': `Bearer ${TARGET_API_KEY}`, // Add your API key securely
        'Content-Type': req.headers['content-type'] || 'application/json',
        // Forward other relevant headers, but filter out sensitive ones if any
      },
      params: req.query, // Forward query parameters
      data: req.body,    // Forward request body for POST/PUT/PATCH
    };

    const apiResponse = await axios(axiosConfig);

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

  } catch (error) {
    console.error('Proxy error:', error.message);
    if (error.response) {
      // The API responded with a status code that falls out of the range of 2xx
      console.error('Target API responded with error:', error.response.status, error.response.data);
      res.status(error.response.status).send(error.response.data);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('No response received from target API:', error.request);
      res.status(500).send({ message: 'No response from target API.' });
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error('Error setting up proxy request:', error.message);
      res.status(500).send({ message: 'Proxy configuration error.' });
    }
  }
});

app.get('/', (req, res) => {
  res.send('API Proxy is running. Use /api/your_endpoint to proxy requests.');
});

app.listen(port, () => {
  console.log(`API Proxy listening at http://localhost:${port}`);
  console.log(`Proxying requests to: ${TARGET_API_BASE_URL}`);
});

// To run this:
// 1. npm init -y
// 2. npm install express axios cors dotenv
// 3. Create a .env file:
//    TARGET_API_BASE_URL=https://some-third-party-api.com/v1
//    TARGET_API_KEY=YOUR_SECRET_API_KEY
// 4. node your_proxy_file.js
How it works: This Node.js Express snippet creates a simple server that acts as an API proxy. It routes requests from a client (e.g., a frontend application) to a third-party API. This setup is crucial for two main reasons: it bypasses CORS restrictions that might prevent direct client-side calls to external APIs, and it securely hides sensitive API keys on the server, preventing their exposure in client-side code. The proxy forwards the request method, body, query parameters, and essential headers, then returns the third-party API's response to the original client.

Need help integrating this into your project?

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

Hire DigitalCodeLabs