Requiring modules external to functions directory

I’ve tried requiring shared utility-type modules that live outside my functions directory and get a Error: Cannot find module '../utils' message when the function is run after being deployed. Interestingly, the error is not thrown when running the function locally using netlify dev.

I was wondering if this is expected or if it should be possible to require modules that are outside the functions directory.

hi, this isn’t allowed in netlify in production. and is a mistake in netlify dev allowing it. we will fix in due time.

Thanks for confirming.

I got around my problem by putting the shared modules in a lib folder inside the functions directory. Are there any drawbacks to or recommendations against that approach?

no i think that is fine :slight_smile:

I went a couple rounds on this issue too. Found that creating a shared folder in the root of functions is only accessible to the function if the function is not in a subfolder.

A shared js file is found if the folder structure looks like this:

/functions
--/lib
----/shared-module.js
--/my-ntl-function.js

However when the folder structure is like this it is not found:

/functions
--/lib
----/shared-module.js
--/my-ntl-function
----/my-ntl-function.js

Clarification on how to properly use shared modules across functions in the docs would be helpful.

correct. the reasoning for this is how netlify functions work under the hood - if a single js file, it works in context of the overall functions folder. if a folder, it is zipped up and deployed as a standalone function with no access to anything else.

to be honest i’m a bit lost on this. we need to document better and also provide better replication in Netlify Dev. i frankly dont have enough node-fu to figure out how to prevent requiring external files in Netlify Dev (https://github.com/netlify/netlify-dev-plugin/issues/192). and also have to think about how to document better. ideas welcome.

Great thanks for the clarification