How to use Lambda functions in Netlify

What is a lambda function?

Netlify lambda

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

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