How to use Lambda functions in Netlify

What is a lambda function?

By definition, lambda functions are anonymous functions that are not bound to any identifiers. These functions are usually passed as arguments to other higher-order functions. However, when it comes to Netlify or any cloud provider, lambda functions take a different meaning. Lambda functions are a great way to define a small chunk of serverless code to run on your applications’ behalf. Let’s say you have an application running purely on the client-side, and you need a small chunk of code to be executed on the server-side, bringing up a whole new server, and deploying just to perform one small task seems a bit of overhead. In such scenarios, the lambda function comes to the rescue.

Netlify lambda

Netlify is a cloud offering that also provides lambda functions, without an AWS account, and with function management handled directly within Netlify. These serverless functions are version-controlled, built, and deployed along with the rest of the Netlify site.

npm install netlify-lambda
// netlify.toml
[build]
publish = "public"
command = "yarn run build"
functions = "lambda"
// lambda/index.js

const { REVUE_KEY } = process.env;
const fetch = require("node-fetch");

const API_ENDPOINT = "https://someendpoint";

exports.handler = async (event, context) => {
const headers = {
'Access-Control-Allow-Origin': '*',
// Add any other headers as per requirement
};

if (event.httpMethod === 'OPTIONS') {
callback(null, { statusCode: '204', headers });
return;
}

if(event.httpMethod === 'POST') {
const { email } = JSON.parse(event.body) || "";
const { name } = JSON.parse(event.body) || "";

return fetch(`${API_ENDPOINT}/api/v2/subscribers`, {
method: 'POST',
headers: {
'Authorization': `Token ${ENDPOINT_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email": email,
"name": name,
"double_opt_in": true
})
})
.then(() => ({ statusCode: 201 }))
.catch(error => ({ statusCode: 422, body: String(error) }));
}
};

Calling lambda function

Once you write the lambda function, it is important to call it and ensure it works as intended. All lambda functions deployed in netlify can be accessed under the URL base_url/.netlify/functions/lambda_function_file_name. Use this URL and make a POST call to your method.

netlify-lambda build <folder>
netlify-lambda install [folder]
fetch(`${base_url}/.netlify/functions/index`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email": email,
"name": name
})
})

CODER | BLOGGER | ARTIST | GHOST