Sending Data to n8n from Google Forms

Thanks so much for creating this.

I used it as the basis for some work today, and extended it to build a json object from the form fields. This way if you add new fields in the form, they appear in the n8n webhook payload.

function onFormSubmit(e) {
  const url = "N8N_WEBHOOK_URL"; //n8n WebHook URL

  // get our form details
  const form = FormApp.openById("FORM_ID"); // Copy the Form ID from the URL
  const formResponses = form.getResponses();  
  const fields = form.getItems()
  const fieldNames = fields.map( (item) => item.getTitle() )
  
  // list of field name like ["title", "message", "name", etc]
  console.log( {fieldNames} ) 

  // now, fetch the latest submission
  const formResponse = formResponses[formResponses.length - 1];
  const itemResponses = formResponse.getItemResponses();
  const formSubmission = itemResponses.map( (field) => field.getResponse() )

  // build our payload to send to n8n
  let index = 0
  let payload = {}

  for (const field of fieldNames) {
    payload[field] =  formSubmission[index]
    index++
  }

  console.log({formSubmission})
  console.log({payload})

  // finally send along our request as a POST request to the n8n endpoint
  const options = {
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    payload: JSON.stringify(payload),
  };
  const response = UrlFetchApp.fetch(url, options);
}
3 Likes