Functions playground
Hi there! This is a playground to try out a variety of Netlify Functions. You can browse the code for these examples in our GitHub repo.
Hello, World!
The inevitable Hello World example.
exports.handler = function (event, context, callback) {
callback(null, {
statusCode: 200,
body: "Hello, World",
});
};
Try it out
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
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.
const querystring = require("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
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.
const fetch = require("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
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).
-
Create a Slack incoming webhook at https://my.slack.com/services/new/incoming-webhook/
-
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
- 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.
const querystring = require("querystring");
const fetch = require("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
Once you've made a submission you'll see a message appear in our Jamstack Slack, log in or sign up and navigate to the #netlify-functions-demo channel to see the message you triggered:
