Nerlify: lambda response was undefined. check your function code again Response with status 500 in 583 ms

Viewed 1480

enter image description here

I'm trying to use netlify and its lambda function feature to run a node function. Based on https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/.

Currently my netlify.toml has only the following:

[build]
  functions = "./functions"
  command = "npm run-script build"

mt submission.js:

// https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/

require('dotenv').config();
const fetch = require('node-fetch');


console.log('to here');
const { LIST } = process.env;
const { B } = process.env;


exports.handler = async event => {

  const email = JSON.parse(event.body).payload.data.EMAIL


  console.log(email);
  const asking = JSON.parse(event.body).payload.data.ASKING

  console.log(asking);
  var formData = {
    'email': email,
    'first_name': '',
    'last_name': asking,
    'lists[]': LIST
  };
  var encoded = Object.entries(formData).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");

  var endpoint = 'https://api.sendfox.com/contacts/?' + encoded;

  const data = JSON.stringify(formData);

    return fetch(endpoint, {
      method: 'POST',
      headers: {
        Authorization: B,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ formData }),
    })
      .then(response => response.json())
      .then(formData => {
        console.log(`Submitted to Buttondown:\n ${formData}`)
      })
      .catch(error => ({ statusCode: 422, body: String(error) }))
  // } 
}

result:

Submitted to Buttondown:
 [object Object]
ā—ˆ lambda response was undefined. check your function code again
Response with status 500 in 583 ms.

what am I doing wrong?

1 Answers

It's me, the author of the tutorial linked above!

Since I wrote the tutorial, node-fetch has updated with some breaking changes that make the code I wrote hard to debug.

A much more robust way to implement the same functionality in a netlify function would be to substitute the following:

  const response = await fetch(
        'https://api.buttondown.email/v1/subscribers',
        {
            method: 'POST',
            headers: {
                Authorization: `Token ${EMAIL_TOKEN}`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email }),
        }
    );
    let responseText = await response.text();
    console.log('response:', responseText);
    return {
        statusCode: response.status,
        body: responseText,
    };

This will return the proper status code, so you don't get the 'response was undefined' message. Plus, it'll properly log the response from buttondown, in case you need to do any further debugging.

Related