Environment variable per branch for lambda functions

Hi,

I’m trying to set environment variables in my netlify functions based on the deploy context. For example, I want to use an env var named PRODUCTION_ACCESS_TOKEN on the master branch, and SANDBOX_ACCESS_TOKEN on my dev branch. I’ve tried many solutions to this problem, described below, but have been unsuccessful so far.

I’ve seen a solution about checking $CONTEXT in the netlify function posted by @fool multiple times, but I have yet to get anything like it to work. I have tried accessing process.env.CONTEXT from my vue app build, but it’s undefined when running locally with netlify dev, and also after it’s deployed on netlify. I’ve also tried accessing process.env.CONTEXT from my netlify functions. It’s undefined there too, both when I’m running locally with netlify dev, and also after deploy.

Here’s my function code:

exports.handler = async (event, context) => {
  try {
    return {
      statusCode: 200,
      body: JSON.stringify({
        context: process.env.CONTEXT,  // undefined
      }),
    };
  } catch (err) {
    return { statusCode: 500, body: err.toString() };
  }
};

This post in netlify guides and tutorials, which describes how to build a plugin very similar to netlify-plugin-contextual-env, seems to imply that accessing process.env.CONTEXT should be possible in netlify functions, but it doesn’t work for me as described.

Using a combination of netlify-plugin-contextual-env and netlify-plugin-inline-functions-env, as described by @edamame, works locally if I run netlify build and then netlify dev, but not when using netlify dev alone, which is what I need. If I run the netlify build command first, my functions are re-written locally with my environment variables inlined (as intended by netlify-plugin-inline-functions-env), but I can’t commit these re-written functions to source control because the environment variables that I’ve defined in the netlify UI contain secrets.

My takeaway is that these plugin solutions are not very reliable, and I would love to see this functionality added to netlify natively.