Sharing helper function between lambdas

I have a util function to capture errors and send to Sentry. I have added this to a utils folder I have added to lambdas and import them into each lambda function like so;

import { initSentry, catchErrors } from "./utils/sentry";

This works as expected locally but when I try to deploy, deployment fails with this error;

: Rel: can't make lambda relative to /opt/build/repo

I assume this is because the util folder is not deployed to the same place so the relative path is failing?

What is the recommended way to share code across multiple lambdas?

Hi @barrymcgee, there’s a lot of different ways to accomplish what you need but I find making your utility functions an npm package a pretty neat solution. Let me know what you think.

Update: corrected the link as it was pointing to the wrong community post.

1 Like

Hi Dennis - thanks for the reply. I’ll be honest - creating an external dep just to share between two functions feels sub-optimal but I’ll investigate further. Thank you.

2 Likes

I’m right there with you. Creating a package seems overkill and not very scalable. I can’t imagine wanting the exact same utils between different projects

2 Likes

Right, I agree. Though, for reference, a lambda function isn’t hosted as part of a site. It has its own completely separate environment that it runs on. Each function is completely separate from other functions. Considering that, you can see how it’s not simple to share code between functions.
That said, the link I shared where someone made their utility functions into npm packages, they are not actually publishing those functions to the npm registry. It is a local package, whose scope is specific to that particular repo.

Also a correction: The link I share was not to the correct post. This is what I meant to share: Using require to include a relative module in Netlify Functions on Node. The post also share their repo which shows what they had done to accomplish the solution/workaround.

Just a very hand-wavy in-the-air idea here, but could you just make a third function that’s your “error handling” function and both of the “do stuff” functions can post their errors over to that one? You could even break that out to its own site or subdomain if you needed to. </thoughts>

Maybe that helps :slight_smile:


Jon