Triggering function to run on build

I have created a little function to fetch data from google analytics to display on our Hugo-based site. My problem is that the function only executes when I visit the function directly in a browser, or by sending a request. I would like it to execute during build so that Hugo can consume the generated json file.

const { google } = require("googleapis");
const fs = require("fs");
require("dotenv").config();

const PRIVATE_KEY = process.env.PRIVATE_KEY.replace(/\\n/gm, "\n");

const scopes = "https://www.googleapis.com/auth/analytics.readonly";
const jwt = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  PRIVATE_KEY,
  scopes
);

async function getData() {
  const defaults = {
    auth: jwt,
    ids: "ga:" + process.env.VIEW_ID,
  };
  const response = await jwt.authorize();

  const result = await google.analytics("v3").data.ga.get({
    ...defaults,
    "start-date": "2020-04-01",
    "end-date": "today",
    metrics: "ga:pageviews, ga:sessions"
  });

  return result;
}


 async function writeFile(data) {
  fs.writeFile("data/ga.json", JSON.stringify(data), function (err) {
    if (err) throw err;
    console.log("Saved!");
  });
}


exports.handler = (event, context, callback) => {
  getData().then((res) => {
    writeFile(res.data.totalsForAllResults)
    callback(null, {
      statusCode: 200,
      body: JSON.stringify(res.data.totalsForAllResults),
    });
  });
};

First, you could try using an event-triggered function (https://docs.netlify.com/functions/trigger-on-events/#available-triggers) so that your function gets triggered on deploy-success.

That said, I see you are trying to write a file. This won’t work since your function is not executed in the same context or path as your site. You’ll want to send that data somewhere instead. For example, you can create a new file in a github repo using their API.