Reputation: 115
I am working on a node, express and React app. I'm using some external API data but API token is expiring every 24 hours.First I had this saved in the .env file but I can't just update the value and use it to resend my request with a new token. Is there a good way for me to update this secret programmatically (every time my request fails with a specific error message), use it right away without restarting the server and continue using it for the next 24 hours until I have to repeat this process? If this is not possible what is the best way to go about this?
This is how I was trying to update it
module.exports = async function (req, res, next) {
const config = {
headers: {
"Accept": "application/json",
"api-token": process.env.GEO_API_KEY,
"user-email": process.env.GEO_API_EMAIL
}
}
try {
const { data } = await axios.get('url', config);
if (data.auth_token) {
process.env['GEO_API_AUTH_TOKEN'] = data.auth_token;
}
} catch (error) {
console.error(error)
}
};
but this does not update the value in .env file
Upvotes: 2
Views: 347
Reputation: 704
You can always use a bash command in your node code. This is an example using sed. This will work on most *nix machines.
const { exec } = require('child_process');
module.exports = async function (req, res, next) {
const config = {
headers: {
"Accept": "application/json",
"api-token": process.env.GEO_API_KEY,
"user-email": process.env.GEO_API_EMAIL
}
}
try {
const { data } = await axios.get('url', config);
if (data.auth_token) {
exec(`sed -i "" "s/${oldAPIkey}/${data.auth_token}/" .env`, (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
// the *entire* stdout and stderr (buffered)
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
//update them in the process so you don't have to restart your app if you want.
process.env['GEO_API_AUTH_TOKEN'] = data.auth_token;
});
}
} catch (error) {
console.error(error)
}
};
Upvotes: 1
Reputation: 863
You can try having some auxiliary variable. This var when the server starts it will set to the process.env.GEO_API_KEY
, and then you can set it new values over time:
let apiToken = process.env.GEO_API_KEY;
module.exports = async function (req, res, next) {
const config = {
headers: {
"Accept": "application/json",
"api-token": apiToken,
"user-email": process.env.GEO_API_EMAIL
}
}
try {
const { data } = await axios.get('url', config);
if (data.auth_token) {
apiToken = data.auth_token;
}
} catch (error) {
console.error(error)
}
};
Upvotes: 0