I want to set custom headers of "id", "env", and "name" based on envs in my application, they all have different values for different envs. I am having trouble figuring out the most effective way to make it work based on my code logic.
Here is how I define the env:
let host = "xxxxxxxx";
function getHost() {
var env = getEnv();
env = env ? env : process.env.REACT_APP_ENV;
switch (env) {
case "stage":
host =
"xxxxxxxxxxxxxxxxxxx";
break;
case "prod":
host =
"xxxxxxxxxxxxxxxxx";
break;
case "local":
host = "xxxxxxxxxxxxxx";
break;
case "dev":
default:
host = "xxxxxxxxxxxxxxxxxxx";
break;
}
return host;
}
export const HOST = getHost();
Here is pretty much how every "headers" is set in my app, as you can see there are only some values so far:
export function fetchRefresh(token) {
return (dispatch) => {
return fetch(API_ROOT + "/xxxxxxx/xxx/xxxxxx", {
method: "POST",
headers: {
authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
body: token,
})
.then()
// the rest
}
}
I thought about doing something like this, and adding HEADERS to headers: {} in my code, but it will only make the 3 custom headers I want to add a single object, they should all be separate values not object:
function getHeaders() {
var env = getEnv();
env = env ? env : process.env.REACT_APP_ENV;
switch (env) {
case "stage":
return {
"ID": "xxxxxxxxxxxxxx",
"ENV": "xxxxxxxxxxxx",
"NAME": "xxxxxxxx",
}
case "prod":
return {
"ID": "xxxxxxxxxxxxxx",
"ENV": "xxxxxxxxxxxx",
"NAME": "xxxxxxxx",
}
case "local":
return {
"ID": "xxxxxxxxxxxxxx",
"ENV": "xxxxxxxxxxxx",
"NAME": "xxxxxxxx",
}
case "dev":
return {
"ID": "xxxxxxxxxxxxxx",
"ENV": "xxxxxxxxxxxx",
"NAME": "xxxxxxxx",
}
}
}
export const HEADERS = getHeaders();
Can you please help? Thank you
Do you mean retriving environmental variables? You can set your own by working with the 'dotenv' package, which is very commonly used.
https://www.npmjs.com/package/dotenv
You can set your environment variables in
.envfile like this:Which can be processed by