How to fix the Stripe SDK error: Invalid value for Stripe(): apiKey should be a string. You specified: undefined (Node.js)

 
 

So, you’re all set to run your Stripe API executable function…and then nothing happens. You think, let’s check out the console in the browser dev tools. So you pop open the console and see this error:

Invalid value for Stripe(): apiKey should be a string. You specified: undefined

So what does this mean?

What’s happening here is that you aren’t stringifying your API Key and as a result, it is coming up as undefined.

The key-value pair of your environment variable might be valid (i.e. REACT_APP_PUBLISHABLE_KEY=pk_live_43435345awf34t) but you will want to stringify it.

The issue:

  • Notice how the process.env.ELEMENT is inserted into the input of the loadStripe method of the @stripe/stripe-js SDK? This will lead to an error because the value is undefined at start.

The solution:

  • We’ll turn the environment variable into a template literal with ${ENV} to effectively stringify this value, ensure that it can’t NOT be undefined, as we load it into the loadStripe method.

  • Here, we will see that this will allow us to call the stripe API using our Stripe Publishable Key and create a session for the checkout.

Further Debugging:

✨ If you are getting further issues, double-check that your .env file has the environment variable written correctly, like this:

REACT_PUBLIC_STRIPE_TEST_PUBLISHABLEKEY=pk_live_1234567890abcdefghijklmnop

^ Notice that there are no spaces between the key (first-part) and the value (second-part) of this value.

✨ Also, if you have just created the environment variable, make sure to re-start your server. ENV’s are available at build time, but not upon re-renders. Make sure to give your server or application a good ‘ole stop and start to make sure that the environment variables can be reloaded into your build and then proceed as expected.

Let me know if you found this post helpful! And if you haven't yet, make sure to check out these free resources below:

Subscribe to the Tech Stack Playbook™️ for more content:

Listen on Spotify:

Links

Let’s Connect Online:

Get Some Cool Stuff:

*These affiliate links are commission-based