News & Announcements

Support for npm modules in Edge Functions

Two weeks ago, we announced a reimagined experience for Netlify Functions. It includes a brand new API based on standard Request/Response objects and the ability to configure routing within the function code.

If you’ve ever used Netlify Edge Functions, our other serverless compute product, you’re probably thinking that these features feel familiar. That’s because we took the things that developers love about Edge Functions and brought them to Functions, with the goal of creating a more unified experience across the two products.

We’re now approaching that goal from the other direction by taking one of the key features of the Functions offering and adding it to Edge Functions. Starting today, you can use npm modules in your edge functions and leverage more than two million packages in the ecosystem to build your applications.

Getting started

Before using a module, start by adding it to your project. For instance, running the following command installs lodash.

npm install lodash

We’re using the npm client in this example, but you can replace that with your favorite package manager, like Yarn, pnpm or Bun.

Just like with Functions, our build system will automatically install your packages using the right package manager according to your project setup.

Using modules

To use a module, load it into your edge function using an import declaration and access it according to its documentation.

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

import _ from "lodash"

const compiled = _.template("Hello, dear visitor from <%= country %>!")

export default async (req: Request, context: Context) => {
  const text = compiled({ country: context.geo.country.name })

  return new Response(text)
}

export const config: Config = {
  path: "/hello",
}

In this example, we’re rendering a message from a template using the geolocation data as input. If you deploy this edge function and access it, you should see a personalized message based on the country you’re accessing from.

Importing modules using full URLs is still possible and you can combine them with npm imports in the same file.

We’d love to hear from you

We’re still hard at work to make this feature capable of handling all the different packages in the vast npm ecosystem with different module formats and characteristics. Still, we wanted to get this tool in the hands of our customers as early as possible, so we’re launching it as a beta feature that we’re hoping to improve in collaboration with you. If you use the Netlify CLI to develop or deploy your functions, make sure you update to version 16.9.2 or above.

We invite you to try it and let us know about your experience through our support portal or our community forum.

Keep reading

Recent posts

How do the best dev and marketing teams work together?