This answer is a blend of many already here, but works for my Next.js setup deployed on Vercel.
My company needed a way to match our deployments with user-submitted bug reports and analytics, so the simplest way I could think of is to place a hidden git hash on pages, which we can easily scrape and/or use directly during user-submissions.
Add build script in package.json
Simply add a script called git-hash
in the scripts
section of your package.json
, e.g.
"scripts": {
"commit-hash": "echo \"export const sha='$(git rev-parse HEAD)'\" > src/lib/commit-hash.js",
...
}
Then use the commit-hash
script in your other scripts, as needed, e.g.
"scripts": {
"commit-hash": "echo \"export const sha='$(git rev-parse HEAD)'\" > src/lib/commit-hash.js",
"dev": "yarn run commit-hash && NODE_OPTIONS='--inspect' next dev",
"build": "yarn run commit-hash && next build",
"start": "yarn run commit-hash && next start",
"lint": "yarn run commit-hash && next lint",
}
Replace yarn
with npm
or whatever you use...
This writes a JavaScript file to the src/lib/
directory called commit-hash.js
that contains a named export sha
.
Import file from within source code
We can use commit-hash.js
in other files with a simple import { sha } from 'path/to/src/lib/commit-hash'
statement.
As an example, I import the named export in a Next.js 14 app, e.g.
import { sha } from '@/lib/commit-hash'
export default function Page() {
return <MyComponent sha={sha} />
}
Use git hash in markup
And once used in a component, the markup generated, for example, looks like
You can clearly see that the hash 9986ada457765d4b0fcfc097f61b96b4fa688577
is now rendered in the HTML markup.