JAVASCRIPT

Simple API Proxy with Node.js/Express to Hide API Keys

Create a secure Node.js/Express API proxy to forward requests, preventing sensitive API keys from being exposed in client-side code.

// server.js (Node.js/Express)
const express = require('express');
const axios = require('axios');
const cors = require('cors'); // Required for cross-origin requests from frontend
require('dotenv').config(); // For loading environment variables

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

// Use CORS middleware if your frontend is on a different origin
app.use(cors());
app.use(express.json()); // For parsing application/json

// Example proxy for a third-party API that requires an API key
app.post('/api/external-data', async (req, res) => {
  const EXTERNAL_API_URL = 'https://external.api.com/data';
  const EXTERNAL_API_KEY = process.env.EXTERNAL_API_KEY; // Keep this secret!

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

  try {
    // Forward the request to the external API
    const externalApiResponse = await axios.post(EXTERNAL_API_URL, req.body, {
      headers: {
        'Authorization': `Bearer ${EXTERNAL_API_KEY}`, // Or 'x-api-key', etc.
        'Content-Type': 'application/json',
      },
    });
    res.status(externalApiResponse.status).json(externalApiResponse.data);
  } catch (error) {
    console.error('Proxy error:', error.response?.data || error.message);
    res.status(error.response?.status || 500).json({
      error: 'Failed to fetch data from external API',
      details: error.response?.data,
    });
  }
});

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

// To run this:
// 1. npm init -y
// 2. npm install express axios cors dotenv
// 3. Create a .env file: EXTERNAL_API_KEY=your_actual_secret_key
// 4. node server.js

// Frontend (example using fetch):
// async function fetchDataFromProxy() {
//   try {
//     const response = await fetch('http://localhost:3001/api/external-data', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/json',
//       },
//       body: JSON.stringify({ query: 'example' })
//     });
//     const data = await response.json();
//     console.log('Data from external API via proxy:', data);
//   } catch (error) {
//     console.error('Error fetching from proxy:', error);
//   }
// }
// fetchDataFromProxy();
How it works: This Node.js/Express snippet creates a simple API proxy server. Its main purpose is to act as an intermediary between a client-side application and a third-party API that requires a sensitive API key. By making the client request `your-own-server/api/external-data` instead of directly to `external.api.com`, the sensitive `EXTERNAL_API_KEY` can be stored securely on the server (e.g., in environment variables) and is never exposed in the client-side code or network requests. The proxy forwards the client's request, adds the API key, and returns the external API's response.

Need help integrating this into your project?

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

Hire DigitalCodeLabs