Netlify Lambda Functions (Webhooks)

  • Setup for Local Development

npm install netlify-lambda

netlify.toml

[build]
  command = "npm run build"
  publish = "dist"
  functions = "functions"

package.json

"scripts": {
  "start:functions": "netlify-lambda serve src/functions",
  "build:functions": "netlify-lambda build src/functions"
},

Create your functions in src/functions. They will be built into /functions, which will then be handled by Netlify.

Basic function

exports.handler = function(event, context, callback) {
	callback(null, {
	  statusCode: 200,
	  headers: {
      "Content-Type": "application/json"
    },
	  body: JSON.stringify(data_out)
  });
  .catch((err) => {
    callback(err);
  });
};

Using Axios (Can’t get jQuery to work for some reason)

const axios = require('axios');

let url = "":

axios({
	method: 'get',
	url: url,
})
.then((res) => {
	// Do something
	callback(null, {
	  statusCode: 200,
	  headers: {
      "Content-Type": "application/json"
    },
	  body: JSON.stringify(data_out)
  });
})
.catch((err) => {
  callback(err);
});

Using process.env locally

In production, simply host your environment variable safely in Netlify. However, in local development, you want an efficient way to access environment variables (like API keys) without exposing them. Here’s how.

Create src/js/env.js

process.env['API_KEY'] = "";
process.env['API_ID'] = "";

Add to .gitignore src/js/env.js

In your function, check to see if the environment variable exists. If it doesn’t, you must be in local development. Then, require env.js.