Build time environment variables
There are two steps:
- Run
npm i --save-dev dotenv
- In your
docusaurus.config.js
, just add:
require('dotenv').config()
- Confirm your
.env
directory contains environment variables, e.g.
ENVIRONMENT_VARIABLE_1=hello_there
Your .env
file will be loaded, and you can use process.env.ENVIRONMENT_VARIABLE_1
now.
Runtime environment variables:
To use process.env
variables in React components for example, do the builtime environment variables steps above, then use the customFields
field of the docusaurus config object:
const config = {
...
customFields: {
'ENVIRONMENT_VARIABLE_1': process.env.ENVIRONMENT_VARIABLE_1,
'ENVIRONMENT_VARIABLE_2': process.env.ENVIRONMENT_VARIABLE_2,
},
...
}
and in my typescript component, access them with:
const {siteConfig} = useDocusaurusContext();
return <div>{`${siteConfig.ENVIRONMENT_VARIABLE_1}`}</div>;
Read Custom Configurations in the docusaurus documentation for more information.
Comment
Jonny Nabors's answer (and package) was unnecessary for me and actually confused me. If you want your build process to use your environment variables, use the extremely popular npm package that has been downloaded 22 million times this week (dotenv, rather than his package (docusaurus2-dotenv), which did not work for me.
Perhaps his package is more useful if you needed to use the environment variables at runtime whilst avoiding adding it to the configuration object like I did above? However, in that case, I also found another solution, which is to use environment variables beginning with REACT_APP_
.