Edge Functions types now available as an npm module

You can now import the TypeScript types for the Edge Functions API from the @netlify/edge-functions specifier, which is available both in Deno and in Node.js.

import { Config, Context } from "@netlify/edge-functions"

export default async (req: Request, context: Context) => {
  if (context.cookies.get("chocolate")) {
    return new Response("Sorry, no more cookies for you.")
  }

  context.cookies.set("chocolate", "yummy")

  return new Response("Here's a chocolate cookie! 🍪")
}

export const config: Config = {
  path: "/cookies"
}

But why does this even matter? Read on.

Runtimes and IDEs

If you use a text editor with intelligent code completion (like VS Code), it will try to make sense of your code and offer suggestions about variable types, function arguments, return values, etc. This applies to your own code and to any third-party dependencies you import.

When you deploy an edge function, the JavaScript or TypeScript code runs on Deno, which has a lot of things in common with the more widely used Node.js, but they’re ultimately different runtimes with different features.

The editor needs to know which runtime you’re using in order to suggest the right things. For example, remote URL imports, like the https://edge.netlify.com specifier used to load the Netlify Edge Functions types, are supported in Deno but not in Node.js.

This is why we recommend that you configure your editor with the correct runtime — and even offer to do this for you when we detect that you’re running the Netlify CLI in VS Code.

But some people may not be aware of this, may choose not to do it, or may be using an editor with no support for Deno. In these cases, the editor will not be able to correctly process the import statement and will give you an error message (and the dreaded squiggly red lines).

A cross-runtime specifier

We’ve introduced a replacement for https://edge.netlify.com that works across both runtimes: @netlify/edge-functions is understood by Deno, but it also published as an npm module that works in Node.js.

You can add it to your project in the same way you install any other npm module:

npm install --save-dev @netlify/edge-functions

Importing from @netlify/edge-functions will always give you the right types for the Edge Functions API, regardless of the runtime configured in your editor.

While we recommend that you use this specifier on any new edge functions you write, we’ll continue to support https://edge.netlify.com for backwards-compatibility.

To use the new specifier on edge functions that are developed or deployed using the Netlify CLI, you should update to version version 16.3.1 or above.

1 Like