We’re pleased to announce support for npm modules in Edge Functions, allowing you to leverage the more than two-million packages in the npm ecosystem when building on Netlify Edge Functions.
Using a module
The experience of using npm modules in Edge Functions in very similar to the one in Netlify Functions. To load a module, start by installing it in your site’s base directory.
npm install --save lodash
We’re using the npm client in this example, but you can replace that with your favorite package manager, like Yarn or pnpm.
Next, import the module into your edge function and use it as per its documentation.
import _ from "lodash";
const compiled = _.template("Hello, dear visitor from <%= country %>!");
export default async (req, context) => {
const text = compiled({ country: context.geo.country.name });
return new Response(text);
};
export const config = {
path: "/hello",
};
In this example, we’re using Lodash to compile a template and render it in response of a request. If you deploy this edge function and access /hello
, you should see a personalized message based on the country you’re accessing from.
Beta support
We wanted to get support for npm modules in the hands of our customers as early as possible, because it was one of the most requested features of Edge Functions. We’re launching it as an experimental feature because we’re still actively working on improving it and addressing some caveats that you should be aware of before using it in your production workflows.
Under the hood, our build system will traverse the entire module tree and bundle together the code in your edge functions, any npm modules they import, any dependencies of those modules, and so on.
This means that any files that aren’t directly loaded using an import
or require
statements will not be discovered in this process and will not be available at runtime. For example, if a module uses a filesystem method to dynamically read a text file at runtime (like cowsay
), or expects a native addon to exist in a specific location (like prisma
), the package may not work correctly.
We want to hear from you
We’re hard at work making this feature work for you, and we’d love to hear how it goes. If you come across a package that doesn’t work as expected, or anything about the experience that doesn’t feel right, please let us know in this thread.
If you use the Netlify CLI to test or deploy your edge functions, please update to version 16.8.0 or above.
Thanks!