How to pass values between functions

I’m working on GitHub authorization and have to compare two strings (Github state and local state). A separate module (file) is used to store and retrieve states. In the first function, I put the value in an object defined in that module, in the second function I try to extract this value. The functions were running on localhost successfully, but once the app is deployed I’m not able to retrieve the string. It seems like it’s initializing a new instance of that module for each function. Maybe there are other ways for transferring data between the functions (short term storage, can be stored in RAM)?

You have a couple options, since scope is not shared between functions for reasons that might not seem obvious at first. When testing your use case locally, mimic the function scope by running them in two different terminal instances.

One way would be to use a shared storage scope (api) location for the values you need to store and compare.

Another would be to make a third function that stores the values in a global state (be careful, this solution has dragons :dragon:). The global value may be reset on function spin-up during a restart of a function.

The best solution is a combination of the two, if you have heavy traffic and speed is an issue. Create the caching function with a global state variable for the data. Whenever the state of the value is changed, store it to the offsite API storage location. If the cached value is not set, read from the API location and store in the global state variable.

2 Likes

@talves Thank you for the detailed answer. Are there any code examples I can see?

Not sure if there is an example specifically, but you can look here: Functions examples - Netlify Functions

2 Likes

I’m struggling to work out how to store a global state variable. The only thing I can think of are environment variables…Any suggestions?

It depends what you mean by “global state variable”. In my case, I was referring to a scoped variable accessed by the 3rd function outside the handler and changed when needed. If it is just a static value you are referring to, then yes, store it in an environment variable in the console and set the value outside the handler.