How to use Lambda functions in Netlify

Image for post
Image for post

What is a lambda function?

Netlify lambda

In this tutorial, we will implement a lambda function to handle a POST call coming from your site. This call makes another call to a public API and returns the data to your website.

Go to the root folder of your project and install the following package:

npm install netlify-lambda

This package helps you to build your lambda function locally so you can make API calls and test the functionality.

Open netlify.toml file and add the folder path where is lambda function resides. It is essential to add this under the build step of your netlify file. This will ensure that the lambda function gets built every time to build and deploy your changes.

// netlify.toml
[build]
publish = "public"
command = "yarn run build"
functions = "lambda"

Now that we have the build path ready, its time to write lambda functions. Create a new folder lambda and an index.js file. Add your lambda function.

// 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) }));
}
};

The lambda functions are basically any javascript function that works on top of events. When an HTTP method is called, you determine the type of method and perform an appropriate action.

In the above lambda function, we are handling requests to two methods. OPTIONS and POST. This execution of the methods remains the same as any other asynchronous function.

Calling lambda function

Start your lambda function by using the following command:

netlify-lambda build <folder>
netlify-lambda install [folder]

Once the lambda function is running, you can call it using fetch just any other API call:

fetch(`${base_url}/.netlify/functions/index`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email": email,
"name": name
})
})

Push your changes and deploy them on netlify.

If you followed through the tutorial, then voila!!! You have a lambda function running in Netlify. If you had any difficulties in following this tutorial, please refer to my GitHub repository: https://github.com/AparnaJoshi007/explained. Please feel free to ping me if you have any doubts. Cheers!!!

Written by

CODER | BLOGGER | ARTIST | GHOST

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store