How to run a function on build and then have it as an API later on

I saw that you can run a function on build by renaming it to deploy-building.js but i need to run an api endpoint function i have at build so i can fetch the data and cache it

Hi, @siliconchild. If you want an Function API endpoint to exist independent of the build, one solution is to create a separate Netlify “site” (in quotes because really it is just a wrapper site to hold the Function/API) and create the function there.

If this “API only site” is created in advance of creating or building the other Netlify site, the API endpoint will already exist when the new site build is performed.

This does mean that a separate build would be needed to update the API, but this might actually be a better workflow. API updates would not occur automatically when the other site is build occurs and, instead, only when the API site has a build triggered.

Another solution is to make the function part of the site which will use the API but this scenario creates a “bootstrap problem”. How do you do the first build if it requires the API and the API won’t exist until the first build occurs?

There are several ways to overcome this so if this solution is needed, please let us know and we can discuss those solutions in more detail. For example, you could first deploy just the API to a different site (like the first solution suggested above). Then use this API for the first build which recreates the API for the new site. After this is first build with the “other site API”, the build could be change to use newly created API on the same site going forward. The other API site could then be deleted as it has it would not longer be needed.

The only downside I see with the “same site Function” solution is that if an API update is needed for the build, two builds must be run to accomplish this. With a separate site for API, it could be updated independently from and before the update of the site itself.

​Please let us know if there are other questions about this.