Cloud Functions as a Tiny API Layer

Sometimes the simplest cloud function use case is the best one. The friendly-words npm package from Glitch is a great example: it generates fun word pairs like “happy-elephant” or “walking-tree.” The package works fine in Node, but at roughly 200 KB it's overkill to ship to a browser just to pick two random words from its word lists.

A lightweight alternative is to wrap that package in a serverless function and expose it as a tiny API. The function handles the heavy lifting off in the cloud, and your client-side JavaScript only needs a URL. Netlify's function support makes this kind of setup particularly straightforward.

The Function

Getting started takes a single file at the project root: /functions/random.js. Inside, the code requires the friendly-words package, picks two random words, and joins them into the output that gets returned.

const friendlyWords = require("friendly-words");

exports.handler = function(event, context, callback) {
  const { predicates, objects } = friendlyWords;
  const numberOfPredicates = predicates.length;
  const numbersOfObjects = objects.length;

  const randomPredicate =
    predicates[Math.floor(Math.random() * numberOfPredicates)];
  const randomObject = objects[Math.floor(Math.random() * numbersOfObjects)];

  const output = `${randomPredicate}-${randomObject}`;

  callback(null, {
    headers: {
      "Access-Control-Allow-Origin": "*"
    },
    statusCode: 200,
    body: output
  });
};

Along with generating the response, the function sets the Access-Control-Allow-Origin header. That takes care of CORS so the endpoint can be called from any site, not just one hosted on the same domain.

Deployment Configuration

You can point Netlify to your function file through the dashboard, but it's easier to keep the configuration in version control. A netlify.toml file at the root of the project tells Netlify where to find the function build.

[build]
  command = "#"
  functions = "functions/"

If you'd rather skip the config file, the dashboard settings offer the same option:

Consuming the API

After deploying, the function is live at a public endpoint such as https://friendly-words.netlify.com/.netlify/functions/random. Visiting that URL in a browser returns the generated word pair. From your own site's JavaScript, calling the endpoint is just a matter of usingfetch — the bulky dictionary never touches the client.

Netlify's documentation includes a catalog of more function examples if this sparks ideas for other use cases. And for a variation with extra API functionality, Paul Kinlan wrote up a similar project generator that's worth a look.