Access to static site published data

This is both a “Can I” and “Should I” type question. Imagine a scenario where I’ve built a serverless function that needs to output data that my static site is using. So for example, in an Eleventy site I’ve defined a JSON data file of cats. I output this both as a set of HTML files (list of cats and unique cat page) as well as /cats.json. I want my serverless function to be able to read /cats.json. I could do it with a HTTP request, but that would mean a HTTP request to my serverless function needs to essentially do a HTTP request to my own site.

So I guess my question is, given .functions/foo/foo.js, can I do a file read on /cats.json to get data?

The idea is - my serverless function logic is written once, but the data it uses is controlled by the JSON file generated itself by data that drives the HTML of my static site.

I don’t think I did a great job explaining that so let me know what I can clarify.

I would do something like this:

  1. Have your site build and generate cats.json
  2. Copy cats.json into your functions folder
  3. Have a serverless function that references cats.json
/* file /functions/cat-api.js && next to it /functions/cat.json*/
const catsData = require('./cats.json') // <== generated at build

exports.handler = async (event, context) => {
  // do stuff with the catsData

It’s possible that the function might not re-deploy each build because the code hasn’t changed (only the JSON might have). If this is the case, you will want to hash the cats.json file or programatically insert the date as a comment to cats-api.js to ensure that its redeployed each time the site is built.

This logic can be orchestrated a number of ways including the new build plugins

To be clear though - are you saying my serverless functions can read files from my “main” site? I know it’s all one site… but I just assumed it was separate. Like my files were on a CDN and my functions on Lambda.

Only if you put the file into the functions folder and it’s required by the function. The rest of the frontend files will not be accessible from functions.

const catsData = require('./cats.json') // <= bundled with functions b/c required

exports.handler = async (event, context) => {
  // do stuff with the catsData

Ok, so it must be done via the build plugin system then. Correct? (Sorry if I’m just echoing back what you said - but want to be sure.)

Nope. You can orchestrate this however you want.

With build plugins or via pre/post NPM scripts etc

Ah ok. I need to build this in order to see it working. WIll give it a shot later this week. Thank you.