Environment Variables in Server Actions
Show the correct way to use environment variables in a server action for secure and configurable API calls.
const axios = require('axios');
// Retrieve environment variables using process.env
const API_BASE_URL = process.env.API_BASE_URL;
const API_KEY = process.env.API_KEY;
// Use the environment variables in your API call
axios.get(`${API_BASE_URL}/data`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
})
.then(response => {
console.log('Data retrieved successfully:', response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
This code retrieves API_BASE_URL and API_KEY from environment variables using process.env. It then uses axios to make a GET request to the API, including the API_KEY in the Authorization header for secure access. The response is logged on success, and errors are caught and logged.