Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share code between Netlify lambda functions

I have 3 separate functions each in their own folders. All of them make use of a Twilio client and Apollo Client for dealing with SMS and GraphQL server respectively.

Rather than having all the code to instantiate each client (get keys from env etc.) in each file, can it be put somewhere and required in?

I've tried putting the code into a .js file in the top level functions/ folder and requiring it in the function code as below and this works fine locally on netlify dev but errors with Module not found '../twilioClient' when the function is called in live environment.

/functions
  apolloClient.js
  twilioClient.js
  package.json - specifying deps used by above files
  /auth
    auth.js - require('../apolloClient')
    ...
  /trails
    trails.js - require('../twilioClient') etc.
    ...
like image 945
Jon Wyatt Avatar asked Feb 11 '20 08:02

Jon Wyatt


People also ask

How do I deploy a serverless function in Netlify?

How to add serverless functions to your project. All you need to do is add a file containing your functions to a netlify/functions folder in your project directory, and push them to your project repo. That's it.

Can we clone lambda function?

There is no provided function to copy/clone Lambda Functions and API Gateway configurations. You will need to create new a new function from scratch. If you envision having to duplicate functions in the future, it may be worthwhile to use AWS CloudFormation to create your Lambda Functions.

How do you create a function in Netlify?

To create a background function, append the function name with -background . For example, to create a background function with an endpoint name of hello-background , save the function file in one of these ways: netlify/functions/hello-background/hello-background.go. netlify/functions/hello-background/main.go.


1 Answers

I had success with this approach.

Short answer:

Create a utils file in your functions folder and require it in your function files.

Long answer:

My netlify.toml file looks like this:

[build] 
    functions = "./functions"

And functions folder:

/functions
 function-1.js
 function-2.js
 utils.js

And utils.js:

exports.helloWorld = () => {
    console.log('hello world')
}

And function-1.js:

const {helloWorld} = require('./utils')

exports.handler = async (event) => {
  helloWorld()
}

To test it:

Run netlify dev or deploy it. Your Functions logs or terminal should say 'hello world'.

My netlify site deploys from GitHub.

like image 85
nth-child Avatar answered Sep 28 '22 16:09

nth-child