JAVASCRIPT

Node.js API Proxy for CORS & Key Hiding

Create a simple Node.js Express proxy server to securely make requests to external APIs, bypassing CORS restrictions and protecting sensitive API keys from client-side exposure.

// Install dependencies: npm install express axios dotenv
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = process.env.PORT || 3000;

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

// Proxy endpoint for an external API
app.get('/api/external/:path*', async (req, res) => {
    const externalApiBaseUrl = process.env.EXTERNAL_API_BASE_URL || 'https://api.example.com';
    const externalApiKey = process.env.EXTERNAL_API_KEY; // Keep this secure in .env

    const targetUrl = `${externalApiBaseUrl}${req.params.path}${req.url.replace(req.params.path, '')}`;
    console.log(`Proxying request to: ${targetUrl}`);

    try {
        const response = await axios.get(targetUrl, {
            headers: {
                'Authorization': `Bearer ${externalApiKey}`, // Example of adding API key
                // Forward other relevant headers from client if needed, e.g., 'User-Agent'
            },
            params: req.query, // Forward query parameters
        });
        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 during proxy request.' });
        }
    }
});

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

/*
    .env example:
    EXTERNAL_API_BASE_URL=https://api.thirdparty.com
    EXTERNAL_API_KEY=your_secret_api_key_here
*/
How it works: This Node.js Express snippet creates a basic API proxy server. It allows client-side applications to make requests to `/api/external/*` on the proxy server, which then forwards these requests to a configured `EXTERNAL_API_BASE_URL`. This setup effectively bypasses CORS restrictions and, more importantly, keeps sensitive API keys secure on the server, preventing their exposure in client-side code. It uses `axios` for external requests and `dotenv` to manage environment variables.

Need help integrating this into your project?

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

Hire DigitalCodeLabs