NODE_ENV and CONTEXT environment variables are `undefined` in my functions

Hello Everyone.

I am currently having some logic to load some secrets which i based on the NODE_ENV but process.env.NODE_ENV inside the function was giving me undefined I have went and tried process.env.CONTEXT and got the same result.

my logic is simple

const STRIPE_SK = process.env.CONTEXT === 'production' ? process.env.STRIPE_SK_PROD : process.env.STRIPE_SK_DEV
// or
const STRIPE_SK = process.env.NODE_ENV === 'production' ? process.env.STRIPE_SK_PROD : process.env.STRIPE_SK_DEV

i am not sure if this is an expected behaviour for netlify functions as NODE_ENV works fine at the website level but not at the function level

I would appreciate any help

Hey @gimyboya

Where have you defined the STRIPE_SK_DEV and STRIPE_SK_PROD environment variables? Only variables defined in the UI are available to functions at runtime as described here.

Hi @coelmay. Thanks for your reply.

The STRIPE_SK_DEV and STRIPE_SK_PROD are well defined in the UI and they are not the problem in my case as they load properly. my question is regarding the NODE_ENV and/or the CONTEXT variable which are supposed to be defined by default. and without any of the two i can’t switch between stripe variables.

Thought also of mentioning that I do use dotenv package at the top of my function like so
require('dotenv').config()

I can confirm that the process.env inside the function doesn’t have any env variable that helps me catch the running context production or development etc… so my question is then what is the way of doing that with netlify functions?

Setting NODE_ENV in the UI to production results in the body returning production in the following function

exports.handler = async (event) => {
  return {
    statusCode: 200,
    body: process.env.NODE_ENV,
  };
};

I appreciate your reply. However setting NODE_ENV to production in the UI will break the build step as yarn/npm won’t install dev dependencies which some are used in the generate step of Nuxt.

I have found the solution to the problem by using a build plugin referenced in other threads in the forum.

2 Likes

Thanks for coming back and letting us know, @gimyboya. Happy building :rocket: