0

Ï keep getting this error "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2345) string | undefined" when im trying to create a new stripe object

My STRIPE_SECRET_KEY is properly declared in my .env.local file

import Stripe from 'stripe';
import { NextApiRequest, NextApiResponse } from 'next';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2020-08-27',
  // Replace with your desired Stripe API version
});

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const { email } = req.body;
  try {
    const customer = await stripe.customers.create({
      email: email,
    });
    res.status(200).json({
      code: 'customer_created',
      customer,
    });
  } catch (error) {
    console.log(error);
    res.status(400).json({
      code: 'customer_creation_failed',
      error: error,
    });
  }
};

export default handler;

enter image description here

  • install the 'dotenv' package to load let dotenv = require('dotenv'); dotenv.load(); – Mahadev Mirasdar Jun 21 '23 at 17:21
  • Looks like this is a fairly common question with environment variables. If you don't use a separate library, you could cast the environment variable as a string first: https://stackoverflow.com/a/52892398/18376867 – LauraT Jun 21 '23 at 17:30

2 Answers2

0

Verify that the string is not undefined before attempting to use it. Example:

const stripeKey = process.env.STRIPE_MODE == 'live' ? process.env.STRIPE_LIVE_KEY : process.env.STRIPE_TEST_KEY

if (typeof stripeKey !== 'string') throw new Error('Stripe key not found')

const stripe = new Stripe(stripeKey, {
  apiVersion: '2022-11-15',
})
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
-1

If you are certain that the environment variable will always be set, you can use the non-null assertion operator (!) to tell TypeScript that it is definitely a string.

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2020-08-27'
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80