Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Last active June 9, 2020 23:34
Show Gist options
  • Save matiaslopezd/6464ef6181c04f0d7b15f796b1da0b30 to your computer and use it in GitHub Desktop.
Save matiaslopezd/6464ef6181c04f0d7b15f796b1da0b30 to your computer and use it in GitHub Desktop.
Submit Hubspot Form with serverless
const fetch = require('node-fetch');
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
exports.hubspot = async (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'POST');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
} else {
// Object destructing for request object
let {body, method, headers} = req;
// If is not POST return 400
if (method !== 'POST') return res.status(400).send({message: `This endpoint not allow ${method} method.`});
// Parse to JSON
const form = (typeof body === 'string') ? JSON.parse(body) : body;
// Create body
// Format read here: https://developers.hubspot.com/docs/methods/forms/submit_form
const data = {
submittedAt: new Date().getTime(),
fields: Object.entries(form).map(([name, value]) => ({name, value})), // Thanks to @hseguro
context: {
pageUri: headers.referer,
pageName: process.env.website || ''
}
};
// Set URL
const url = `https://api.hsforms.com/submissions/v3/integration/submit/${process.env.portal}/${process.env.form}?hapikey=${process.env.key}`;
// Fetch to Hubspot
const response = await fetch(url,
{
method: 'POST',
body: JSON.stringify(data),
headers: {'Content-Type': 'application/json'}
}
);
// Parse
const json = await response.json();
// Return Hubspot status code and body of response
res.status(response.status).send(json);
}
}
{
"name": "hubspot-form",
"version": "0.0.1",
"dependencies": {
"node-fetch": "^2.6.0"
}
}
@matiaslopezd
Copy link
Author

Updated with CORS and improvements on the code.

Thanks you @hseguro!

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