Exposing build time information trough plugin and a file

Site: fluffy-pony-237262

I’m trying to expose build time information to include it to the web pages. To this end, I have created the following plugin:

import * as fs from 'fs'
import * as path from 'path'

export const onPreBuild = ({ constants }) => {
  const commitRef = process.env.COMMIT_REF || 'unknown'
  const branch = process.env.BRANCH || 'unknown'
  const buildTime = new Date().toISOString()

  const buildInfo = {
    commitRef,
    branch,
    buildTime
  }

  const filePath = path.join(constants.PUBLISH_DIR, 'build-info.json')
  fs.writeFileSync(filePath, JSON.stringify(buildInfo, null, 2))
  console.log(
    `Build info written to ${filePath}: buildTime=${buildTime}, commitRef=${commitRef}, branch=${branch}`
  )
}

Now the public folder has a file that contains the relevant information.

In React (Remix to be specific), I’m trying to read the content of the file directly without separate HTTP fetch call with a code snippet like this:

    const filePath = path.join(process.cwd(), 'public', 'build-info.json');
    const buildInfo = JSON.parse(fs.readFileSync(filePath, 'utf8')) as BuildInfoFile;

(The specific location for this is in root.tsx.)

I have a couple of questions relating to this:

  1. Is it a good decision in trying to avoid extra HTTP fetches when building the page?
  2. What would be to correct folder to write this kind of file?
  3. What is the correct way of referring the folder in question?

I’d rather recommend adding a string in your templates that you can find/replace with the relevant information. In my mind, that seems like an easier approach. For example, you can add a comment like:

/* build info goes here */

and then, in the plugin, you can find the file where you need this info: root.tsx and simply replace that string with th actual info.

Regarding your approach, unfortunately I am not sure if I have a good-enough answer to your questions. Like avoiding HTTP fetches… is there a particular reason why you would want to avoid it? And where were you going to make the HTTP call to? As for the folder, you can write the file anywhere, but I believe the public folder might be exposed to everyone. If you’re okay with that file getting published to the internet, that should be fine. And referring to the folder looks fine to me - especially if it works, it should be good-enough.

The problem I have is that plug-in does not seem to have an access to source files before compile time in a way that I can write changes to them. Or if I’m mistaken, could you explain how to do this?

Plugin has full disk access as a regular user. Check out this one as an example: hrishikesh-k/netlify-plugin-bundle-env: A Netlify Build Plugin to inject environment variables in Netlify Functions during Netlify Builds. (github.com)

1 Like