← Back to all snippets
JAVASCRIPT

Secure API Key Authentication for Node.js Backend Requests

Learn to securely integrate third-party APIs using API key authentication in a Node.js Express application. This snippet demonstrates how to send an API key in headers with Axios.

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

// --- IMPORTANT: Store API keys securely, not directly in code! ---
// Use environment variables (e.g., process.env.API_KEY)
const THIRD_PARTY_API_BASE_URL = 'https://api.example.com';
const THIRD_PARTY_API_KEY = 'your_super_secret_api_key'; // Replace with actual key from env

app.get('/fetch-external-data', async (req, res) => {
    try {
        const response = await axios.get(`${THIRD_PARTY_API_BASE_URL}/data`, {
            headers: {
                'Authorization': `ApiKey ${THIRD_PARTY_API_KEY}`, // Common pattern
                // Or sometimes 'x-api-key': THIRD_PARTY_API_KEY
                // Or as a query parameter: params: { api_key: THIRD_PARTY_API_KEY }
            }
        });
        res.json(response.data);
    } catch (error) {
        console.error('Error fetching external data:', error.message);
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            res.status(error.response.status).json(error.response.data);
        } else if (error.request) {
            // The request was made but no response was received
            res.status(503).json({ message: 'No response from external API' });
        } else {
            // Something happened in setting up the request that triggered an Error
            res.status(500).json({ message: 'Internal server error' });
        }
    }
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to integrate with a third-party API that requires API key authentication. It uses the popular `axios` library to make HTTP requests. The API key is securely passed in the `Authorization` header, a common practice (though some APIs might use a custom header like `x-api-key` or a query parameter). The snippet also includes robust error handling specific to `axios` responses, distinguishing between server errors, network issues, and request setup problems.

Need help integrating this into your project?

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

Hire DigitalCodeLabs