JAVASCRIPT
Serverless Function as an API Proxy for Authentication
Use a Node.js serverless function to proxy requests to a third-party API, securely injecting API keys and masking credentials from the frontend.
// This code snippet is for a serverless environment (e.g., AWS Lambda, Vercel, Netlify Functions)
// It demonstrates a Node.js function acting as an API proxy.
// Example using Vercel's API route structure (express-like)
// File: api/proxy-data.js
// You would typically load this from environment variables
const THIRD_PARTY_API_BASE_URL = process.env.THIRD_PARTY_API_BASE_URL || 'https://api.example.com';
const THIRD_PARTY_API_KEY = process.env.THIRD_PARTY_API_KEY || 'your_super_secret_api_key';
module.exports = async (req, res) => {
// Ensure only GET requests are allowed for this example
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method Not Allowed' });
}
// Extract query parameters from the client request
const { resource, id, ...queryParams } = req.query;
if (!resource) {
return res.status(400).json({ error: 'Resource parameter is required' });
}
// Construct the target URL for the third-party API
let targetUrl = `${THIRD_PARTY_API_BASE_URL}/${resource}`;
if (id) {
targetUrl += `/${id}`;
}
// Add remaining query parameters
const queryString = new URLSearchParams(queryParams).toString();
if (queryString) {
targetUrl += `?${queryString}`;
}
try {
// Make the request to the third-party API, injecting the secret API key
const apiResponse = await fetch(targetUrl, {
method: 'GET', // Or req.method if you want to proxy all methods
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${THIRD_PARTY_API_KEY}`, // Securely inject API key
// Potentially forward other headers from the client if needed
},
});
if (!apiResponse.ok) {
// Forward the error status and message from the third-party API
const errorData = await apiResponse.json().catch(() => ({ message: apiResponse.statusText }));
return res.status(apiResponse.status).json({
error: 'Third-party API request failed',
details: errorData
});
}
const data = await apiResponse.json();
// Return the data to the client
res.status(200).json(data);
} catch (error) {
console.error('Serverless proxy error:', error);
res.status(500).json({ error: 'Internal Server Error', details: error.message });
}
};
How it works: This Node.js serverless function acts as a secure API proxy. It receives requests from a frontend client, constructs a target URL for a third-party API, and crucially, injects a sensitive API key from environment variables before forwarding the request. This approach prevents exposing API keys directly in the frontend code, enhances security, and allows for potential request modification or data transformation before reaching the client.