Hello World on Netlify Functions, Cloudflare Workers, & Vercel Functions

Katie - Sep 8 '21 - - Dev Community

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 or https://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}`
  };
};
Enter fullscreen mode Exit fullscreen mode

Cloudflare Workers

  • Filename: n/a
  • Access URL pattern: https://hello-world.example.workers.dev/ or https://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})
}
Enter fullscreen mode Exit fullscreen mode

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 or https://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}`);
};
Enter fullscreen mode Exit fullscreen mode

See Vercel's full list of helper methods on the 2nd (response) parameter passed to module.exports (here, res).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .