Netlify Functions in Javascript with Type-Checking

JS Function with strong-typing

Shout out to Eduardo for pointing out that netlify already publishes an npm package with types (I don't need to write my own .d.ts file) 💪

Short Version

/** @type {import("@netlify/functions").Handler} */
export const handler = async (event, context) => {
  // all these properties are typed
  const { httpMethod, body, headers } = event;

  // response is typed
  return {
    statusCode: 200,
  };
};

Long Version

I really like Netlify Functions. ❤️

I really like TypeScript modern Javascript with type-checking. 👍

The appeal of Netlify Functions is how easy it is to setup: make a file, get a new api endpoint.

Writing code in .ts files makes something that was easy become not quite as easy.

Not quite as easy to get started (step 1: add a tsconfig, step 2: figure out what goes into tsconfig).

Not quite as easy to debug ("Why did the debugger just jump down there, are my source maps messed up?").

It's not too bad, but any config/build ceremony that slows down development should be scrutinized.

I find writing .js files (actually .mjs files, it's 2023, let's embrace ESM) with a combination of .d.ts declaration files and jsdoc comments to be the sweet spot of getting type-checking without any Typescript config or build steps. 🚀

Here is how I setup my Netlify Functions projects.

Step 1: Install @netlify/functions npm package

Netlify publishes an NPM package with types for their Functions, add that to your package.json.

npm i -D @netlify/functions

Step 2: JSDoc @type the handler

Now in your Function's JS file you can use a jsdoc comment to apply typing.

/** @type {import("@netlify/functions").Handler} */
export const handler = async (event, context) => {
  // all these properties are typed
  const { httpMethod, body, headers } = event;

  // response is typed
  return {
    statusCode: 200,
  };
};

That's it! 🎉

Hopefully you found this post helpful, if you have any questions you can find me on Twitter.

Enabling Emoji Shortcodes in Eleventy Markdown Files
Running Database Webhooks Locally with Supabase CLI