Edit: Added exit code propagation to the below script to ensure a failed build stops the deploy!
Inspired by @thomas.verleye above we’re using the script below. The main difference is that the raw log output from the build script is piped through (even shows colors in Cloudflare’s logs) so you can follow the build process live.
It also adds some config at the top to map branch-names to Dato build triggers. I guess most setups have one or two long lived branches such as main
/master
and staging
that benefit from build triggers while other short lived feature branches don’t need them as they will be deployed automatically on every code change.
const { spawn } = require('child_process')
// This script notifies Dato on pages build status
// For each added build trigger on: https://syb-storefront.admin.datocms.com/project_settings/build_triggers/{projectid}/edit
// Extract the random string from the Status notifications webhook URL and add it here:
const branchToStatusNotificationSecret = {
main: '{the random string from the build notification}',
staging: '{the random string from the build notification}',
}
// Build the app
const npmRun = spawn('npm', ['run', 'cloudflare:pages'])
npmRun.stdout.setEncoding('utf8')
npmRun.stderr.setEncoding('utf8')
npmRun.stdout.on('data', (data) => {
process.stdout.write(data)
})
npmRun.stderr.on('data', (data) => {
process.stderr.write(data)
})
npmRun.on('exit', async (code) => {
console.log(
code
? `Something went wrong when running cloudflare:pages, exited with error code: ${code}`
: 'cloudflare:pages build successfully!',
)
const branch = process.env['CF_PAGES_BRANCH']
const statusNotificationSecret = branchToStatusNotificationSecret[branch]
if (!statusNotificationSecret) {
console.log(
`Will not notify of build status as no status notification secret is configured for branch: ${branch}`,
)
process.exit(code)
}
const res = await fetch(
`https://webhooks.datocms.com/${statusNotificationSecret}/deploy-results`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ status: code ? 'error' : 'success' }),
},
)
if (!res.ok) {
console.log(
`Something went wrong when sending the status to DatoCMS, got: ${res.status} ${res.statusText}`,
)
res.text().then(console.log)
} else {
console.log('DatoCMS received the status correctly')
}
process.exit(code)
})
@dthreatt To use this setup you login to Cloudflare’s dashboard, navigate to your Workers & Pages
project and then to the tab Settings
and the sub section Builds & deployments
. There you change the Build configurations
. Set the Build command
to npm run cloudflare:build
instead of the default npx @cloudflare/next-on-pages@1
.
You also need to add the scripts mentioned by @thomas.verleye to your package.json
file.