a full stack enthusiast interested in Javascript / Typescript / Kotlin / Python / React / React Native / (Android & iOS) native / Cloud

0%

How to set Git branch name as environment variable in next.js

It has something to do with the next.config.js.

1. Install package

npm i current-git-branch --save-dev

2. Add the following code to your next.config.js

1
2
3
4
5
6
7
const currentGitBranchName = require("current-git-branch");

module.exports = {
env: {
GIT_BRANCH: currentGitBranchName()
}
};

3. Then print it in your code

1
console.log(process.env.GIT_BRANCH);

It works for both client side and server side, because it happens at build time and the environment variable has been injected into the code.

4. End

Hope it helps.

Thanks for reading!

Follow me (albertgao) on twitter, if you want to hear more about my interesting ideas.