For those using Gatsby.js, here’s a “functions cache busting” implementation which generates and appends a different content hash to your function name each time the function changes, which you can then query in your pages with useStaticQuery
:
// In your gatsby-node.js
const fs = require(`fs`)
exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }) => {
const { createNode } = actions
const functions = {}
fs.existsSync('functions') || fs.mkdirSync('functions')
fs.readdirSync('src/functions').forEach(filename => {
const basename = filename.split('.').slice(0, -1).join('.')
const digest = createContentDigest(fs.readFileSync(`src/functions/${filename}`)).slice(0, 7)
fs.copyFileSync(`src/functions/${filename}`, `functions/${basename}-${digest}.js`)
functions[basename] = `${process.env.URL}/.netlify/functions/${basename}-${digest}`
})
createNode({
...functions,
id: createNodeId(`functions`),
parent: null,
children: [],
internal: {
type: `Functions`,
contentDigest: createContentDigest(functions)
}
})
}
On build time, a GraphQL functions
node appears, which consists of the name of each function as keys and the function endpoint as values, e.g. https://example.com/.netlify/functions/myfunction-7e23bfc
. You can utilise it in your page/components as follows:
// In any component/page.js
import React from "react"
import { graphql, useStaticQuery } from "gatsby"
const MyPage = () => {
const { myfunction, myfunction2 } = useStaticQuery(
graphql`
query {
functions {
myfunction
myfunction2
}
}
`
).functions
async function queryEndpoint() {
const response = await fetch(myfunction)
const response2 = await fetch(myfunction2)
console.log(response)
console.log(response2)
}
export default MyPage
Put your Netlify Functions .js
files in src/functions
and see them automatically appear in functions
with an appended hash suffix on build time. Remember to update your netlify.toml
to use the latter directory:
// In your netlify.toml
[build]
functions = "functions/"