Add Git Information to React App

Ignasius
2 min readJul 9, 2021
Yancy Min @ unsplash

Sometimes, you will need to know the build information, like the git commit hash, etc and show it on the app, like in the footer. There is many way to achieve it, but my favorite way is this.

  1. On the package.json, do something like this:
"scripts": {
...
"start": "touch .env && node scripts/start.js && react-scripts start",
"build": "touch .env && node scripts/start.js && react-scripts build",
...
},

Notice the node scripts/start.js before the react-scripts. ( Omit the … )

2. Create a new script file like scripts/start.js

const childProcess = require("child_process");
const fs = require("fs");
const readline = require("readline");
async function processLineByLine() {
const fileStream = fs.createReadStream(".env");
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
const outputs = [];for await (const line of rl) {
outputs.push(line);
}
return outputs;
}
function writeToEnv(key = "", value = "") {
const empty = key === "" && value === "";
if (empty) {
fs.writeFile(".env", "", () => {});
} else {
fs.appendFile(".env", `${key}='${value.trim()}'\n`, (err) => {
if (err) console.log(err);
});
}
}
(async () => {
const results = await processLineByLine();
writeToEnv();for (const result of results) {
if (!result.includes("REACT_APP_GIT_BRANCH")) {
if (!result.includes("REACT_APP_GIT_SHA")) {
const lineArray = result.split("=");
if (lineArray.length === 2) {
const key = lineArray[0].replace(/'/gi, "");
const value = lineArray[1].replace(/'/gi, "");
console.log({ key, value });
writeToEnv(key, value);
}
}
}
}
childProcess.exec("git rev-parse --abbrev-ref HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_BRANCH", stdout);
});
childProcess.exec("git rev-parse --short HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_SHA", stdout);
});
})();

The code will setup the environment variables, then update the .env on the root folder. For the react to acknowledge the ENV, must start with REACT_APP_ , then you can use it anywhere like you use with process.env.{ENV_NAME}

...
console.log('REACT_APP_GIT_BRANCH',process.env.REACT_APP_GIT_BRANCH)console.log('REACT_APP_GIT_SHA', process.env.REACT_APP_GIT_SHA)

References:
https://stackoverflow.com/a/62879437/4289609
https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

--

--