Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Server side version of the auto-translate hook integration for ButterCMS and Google Translate
const READ_TOKEN = "your-read-api-key"
const WRITE_TOKEN = 'your-write-api-key'
const express = require("express")
const butter = require("buttercms")(READ_TOKEN) //read
const request = require("request")
const bodyParser = require("body-parser")
const {Translate} = require('@google-cloud/translate');
const app = express();
// The target language
const TARGET_LANG = 'es';
async function translate(text, target) {
let projectId = 'page-translation-example'
// Imports the Google Cloud client library
// Instantiates a client
const translate = new Translate({projectId});
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
return translation
}'/webhook1', async function (req, res) {
let pageSlug =
let pageType =
//get the original English version of the page, pageSlug, {locale: 'en'}).then( async (page) => {
let fields = Object.keys(
//Setup the structure and default values for the tranlsated payload
let tPage = {
fields: {
stauts: "draft", //we're going with a draft for the time being, just to make sure it works
let translations = []
for(let i = 0; i < fields.length; i++) { //perform the actual translation
let v = await translate([fields[i]], TARGET_LANG)
tPage.fields["es"][fields[i]] = v //update the default values to turn them into spanish
let patchUrl = '*/' + + "/"
request.patch({ //perform the page Patch
url: patchUrl,
headers: {
"Authorization": "Token " + WRITE_TOKEN
json: true,
body: tPage,
}, (err, resp) => { //We're done!
if(err) {
console.log("There was an error: ", err)
return res.json(err)
console.log("Done, patch finished")
}).catch(err => {
console.log("There was an error: ", err)
app.listen(3000, function () {
console.log('Example app listening on port 3000!');

This comment has been minimized.

Copy link

@jakelumetta jakelumetta commented Jul 3, 2019

  • async function translate(text) should accept target parameter so people can specify which language they want to translate to. Right now it's hardcoded.
  • L52 per above comment, should be something like await translate.translate(text, target) with the target locale passed in
  • L25 Why does this say Russian? es is Spanish

This comment has been minimized.

Copy link
Owner Author

@deleteman deleteman commented Jul 3, 2019

Updated the code. Moved the target language outside as a constant. The whole example is about translating content into spanish, that's why it's hardcoded. That being said, now it's more clear where to change things in order to make it dynamic.
As for the russian comment, removed. It was a copy&past mishap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment