Hello World on Netlify Functions, Cloudflare Workers, & Vercel Functions
09 Dec 2020
Table of Contents
Here’s my code for a quick “hello world” serverless function on Netlify Functions, Cloudflare Workers, and Vercel Functions. Here, a “serverless function” is a URL on the web that responds to HTTPs requests, doing some computation in the background before deciding exactly what the response should be, but for which I don’t have to write a lot of code about how the underlying web server works.
Netlify Functions
- Filename:
/functions/helloWorld.js
- Access URL pattern:
https://example.netlify.app/.netlify/functions/helloWorld
orhttps://example.netlify.app/.netlify/functions/helloWorld?name=Katie
- Setting up the base URL name
example
in Netlify: Web-based user interface - Deployment to Netlify: Deploy the Git-tracked folder structure containing this file to a connected cloud Git repository such as GitHub
exports.handler = async (event, context) => {
const name = event.queryStringParameters.name || "World";
return {
statusCode: 200,
body: `Hello, ${name}`
};
};
Cloudflare Workers
- Filename: n/a
- Access URL pattern:
https://hello-world.example.workers.dev/
orhttps://hello-world.example.workers.dev/?name=Katie
- Setting up the base URL name
example
in Cloudflare: Web-based user interface - Setting up the base URL name
hello-world
in Cloudflare: Web-based user interface - Deployment to Cloudflare: Edit code in the web-based user interface
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const name = new URL(request.url).searchParams.get('name') || "World";
return new Response(`Hello, ${name}`, {status: 200})
}
Note: Harris Geo went into a little more depth about deploying a serverless function to Cloudflare Workers the way an experienced programmer might prefer to do.
Vercel Functions
- Filename:
/api/helloWorld.js
- Access URL pattern:
https://example.vercel.app/api/helloWorld
orhttps://example.vercel.app/api/helloWorld?name=Katie
- Setting up the base URL name
example
in Vercel: Web-based user interface - Deployment to Vercel: Deploy the Git-tracked folder structure containing this file to a connected cloud Git repository such as GitHub
module.exports = (req, res) => {
const name = req.query.name || "World";
res.status(200).send(`Hello, ${name}`);
};
See Vercel’s full list of helper methods on the 2nd (response) parameter passed to module.exports
(here, res
).