How to hide stripe secret key using lambda function

I am using a serverless lambda function to run Stripe payments.

In my server function i have the following…

const stripe = require(‘stripe’)(process.env.STRIPE_SECRET_KEY);

i have a .env file with the SK in there, and this works when running on localhost. But it doesnt work when i deploy.

I have added the SK in Netlify’s dashboard

But it doesnt work for me, what am i doing wrong?

Cross posted answer here on StackOverflow

More than likely, the dependency dotenv does not exist when the lambda function executes, because you did not package it into your function.

When using Netlify’s dashboard to store the private key, you won’t have a .env. This is good news, because you don’t want to store that key in your repository. This is only needed in your case for local development.

  • Remove require('dotenv').config() from your function, because it is not needed in this case on Netlify, because process.env.STRIPE_SECRET_KEY will exist on Netlify at the time the function executes.
  • Add the key during local development with a different process (maybe using cross-env at the command line instead)
1 Like

I’d suggest reading this article that goes into extensive details on best practices with environment variables:

But, TL;DR, I wouldn’t use dotenv at all - I’d be using javascript (during build!) to fetch from the env var you have set in the netlify UI. Saner to put sensitive values in our UI than in your repo (where anyone who gets access to your code can find it).