JAVASCRIPT

Secure Server-Side Proxy for External API Calls

Proxy third-party API requests securely through your Node.js backend to protect API keys, manage rate limits, and bypass CORS, enhancing client-side application security.

const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;

// Load environment variables (e.g., using dotenv)
// require('dotenv').config();

const EXTERNAL_API_BASE_URL = 'https://api.example.com';
const EXTERNAL_API_KEY = process.env.EXTERNAL_API_KEY || 'your_secret_api_key'; // USE ENVIRONMENT VARIABLE IN PRODUCTION

// Example: Proxying a GET request
app.get('/api/proxy/data', async (req, res) => {
  try {
    const response = await axios.get(`${EXTERNAL_API_BASE_URL}/data`, {
      headers: {
        'Authorization': `Bearer ${EXTERNAL_API_KEY}`,
        // Add any other necessary headers for the external API
      },
      params: req.query, // Forward query parameters from client
    });
    res.json(response.data);
  } catch (error) {
    console.error('Proxy error:', error.message);
    if (error.response) {
      res.status(error.response.status).json(error.response.data);
    } else {
      res.status(500).json({ message: 'Internal server error' });
    }
  }
});

// Example: Proxying a POST request
app.post('/api/proxy/submit', express.json(), async (req, res) => {
  try {
    const response = await axios.post(`${EXTERNAL_API_BASE_URL}/submit`, req.body, {
      headers: {
        'Authorization': `Bearer ${EXTERNAL_API_KEY}`,
        'Content-Type': 'application/json',
      },
    });
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('Proxy error:', error.message);
    if (error.response) {
      res.status(error.response.status).json(error.response.data);
    } else {
      res.status(500).json({ message: 'Internal server error' });
    }
  }
});

app.listen(port, () => {
  console.log(`Proxy server listening at http://localhost:${port}`);
});
How it works: This Node.js snippet demonstrates how to create a server-side proxy for external API calls using Express and Axios. Proxying API requests through your backend is crucial for security, as it prevents exposing sensitive API keys directly in client-side code. It also helps bypass CORS restrictions and can be used to implement rate limiting, caching, or data transformation before forwarding responses to the client. The example shows both GET and POST request forwarding, including how to pass authorization headers and client-side query parameters or request bodies.

Need help integrating this into your project?

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

Hire DigitalCodeLabs