Netlify Functions Examples

Hi there! This is a playground to test out Netlify’s Lambda Functions.

You can browse the code for this site on GitHub, or play around with the code yourself deploying a copy to Netlify.

Hello, World!

The inevitable Hello World example.

exports.handler = function(event, context, callback) {
  callback(null, {
    statusCode: 200,
    body: "Hello, World"
  });
};

Try it out

Say hello!

Hello, World! (async version)

The Hello World example can get sweeter with some async syntactic sugar. With async, we can return the response instead of dealing with callbacks.

exports.handler = async (event, context) => {
  return {
    statusCode: 200,
    body: "Hello, World"
  };
};

Try it out

Say hello!

Hello, {name}

Customize the greeting calling the Lambda endpoint with an optional name parameter.

exports.handler = async (event, context) => {
  const name = event.queryStringParameters.name || "World";

  return {
    statusCode: 200,
    body: `Hello, ${name}`
  };
};

Try it out

Hello, {name} (POST version)

Let’s make sure we only process POST requests for our customized greeting.

import querystring from "querystring";

exports.handler = async (event, context) => {
  // Only allow POST
  if (event.httpMethod !== "POST") {
    return { statusCode: 405, body: "Method Not Allowed" };
  }

  // When the method is POST, the name will no longer be in the event’s
  // queryStringParameters – it’ll be in the event body encoded as a query string
  const params = querystring.parse(event.body);
  const name = params.name || "World";

  return {
    statusCode: 200,
    body: `Hello, ${name}`
  };
};

Try it out

Show me the error

Read environment variables

Storing secrets like API tokens can be tricky in web apps. Lambdas and environment variables to the rescue!

For this example, I’m using dotenv to define environment variables locally (in a real project, I wouldn’t commit that file to the repository!), and defining those same variables in the Netlify site dashboard under Settings > Build & deploy > Build environment variables, for production.

Note: environment variables get baked into your function at deploy time, so you need to trigger a new deploy after you change them.

const { GREETING } = process.env;

exports.handler = async (event, context) => {
  return {
    statusCode: 200,
    body: GREETING
  };
};

Try it out

Show me the environment variable

Fetch

I see you like APIs! I’ll put an API in your API so you can API while you API.

import fetch from "node-fetch";

const API_ENDPOINT = "https://icanhazdadjoke.com/";

exports.handler = async (event, context) => {
  return fetch(API_ENDPOINT, { headers: { "Accept": "application/json" } })
    .then(response => response.json())
    .then(data => ({
      statusCode: 200,
      body: data.joke
    }))
    .catch(error => ({ statusCode: 422, body: String(error) }));
};

Try it out

Tell me a joke!

Send a Slack message

Putting it all together: send a message to a Slack channel.

You’ll need a Slack account to replicate this example on your own site (if you don’t already have a Slack account, you can create one for free).

  1. Create a Slack incoming webhook at https://my.slack.com/services/new/incoming-webhook/

  2. To test the function locally, add the Slack webhook URL to the .env file in the root folder of your repository.

    SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXXXXXXXXX
  3. To test the function in your deployed site, sign in to your Netlify dashboard, add the environment variable to your site’s Settings > Build & Deploy > Build environment variables, and trigger a new deploy.

import querystring from "querystring";
import fetch from "node-fetch";

exports.handler = async (event, context) => {
  // Only allow POST
  if (event.httpMethod !== "POST") {
    return { statusCode: 405, body: "Method Not Allowed" };
  }

  // When the method is POST, the name will no longer be in the event’s
  // queryStringParameters – it’ll be in the event body encoded as a queryString
  const params = querystring.parse(event.body);
  const name = params.name || "World";

  // Send greeting to Slack
  return fetch(process.env.SLACK_WEBHOOK_URL, {
    headers: {
      "content-type": "application/json"
    },
    method: "POST",
    body: JSON.stringify({ text: `${name} says hello!` })
  })
    .then(() => ({
      statusCode: 200,
      body: `Hello, ${name}! Your greeting has been sent to Slack 👋`
    }))
    .catch(error => ({
      statusCode: 422,
      body: `Oops! Something went wrong. ${error}`
    }));
};

Try it out