DEV Community

Nastassia Danilova
Nastassia Danilova

Posted on • Updated on

Add commit hash version to your React app


Check the current build version to be sure that everything is up-to-date. Ideally in some unnoticeable for user place on the page (if you have any reasons not to use console in this case).

Solution (Step-by-step)

  • Get the last git commit hash from the command line

git rev-parse --short HEAD

  • Execute the script above with Node.js. The best option to do this is with Node.js child_process.

child_process.execSync(git rev-parse --short HEAD)
The only thing you should know here is that execSync allows you to execute the command synchronously.

  • Create an environment variable that contains a necessary hash. By default, your variable should be starting with REACT_APP_. In other cases, it would be ignored.

There are several ways to do it actually. The first one is to replace your standard start and build project commands in package.json with this one

"start": "export REACT_APP_VERSION=$(git rev-parse HEAD) && react-scripts start",
"build": "export REACT_APP_VERSION=$(git rev-parse HEAD) && react-scripts build"

or just insert this line to your webpack.config.js
const commitHash = require('child_process').execSync('git rev-parse --short HEAD')
Calculated commit hash should be wrapped with DefinePlugin function in plugins array.

new webpack.DefinePlugin({
'COMMIT_HASH': JSON.stringify(commitHash),

That's all. Now your hash is available in the React app code process.env.REACT_APP_VERSION

Note: the environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, as described here. Alternatively, you can rebuild the app on the server anytime you change them. Create React App docs

  • It's better to store the value of such variables in any global store like Redux or just as a global variable

window.VERSION = process.env.REACT_APP_VERSION

That's it.

Happy Codding ⌨️! ❤️

Discussion (1)

achoarnold profile image
αςнο αяηοℓδ • Edited on


The default installation when I use CreateReactApp doesn't include the webpack.config.js file. Do you know how I can work around that to get this to work?

I finally found a workaround to get this to work on windows. The command looks something like this

git rev-parse HEAD >sha.txt && set /p REACT_APP_COMMIT_HASH= < sha.txt && del sha.txt && react-scripts start
Enter fullscreen mode Exit fullscreen mode