Next.js Discord

Discord Forum

Why can't Next.js load env variables defined in top scope, when file is outside app folder?

Unanswered
West African Crocodile posted this in #help-forum
Open in Discord
West African CrocodileOP
This leads to undefined:
import Stripe from 'stripe'

const { STRIPE_SECRET_KEY } = process.env

const stripeClient = new Stripe(STRIPE_SECRET_KEY!, {
  typescript: true,
  apiVersion: '2024-06-20'
})


This works:
const stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  typescript: true,
  apiVersion: '2024-06-20'
})


The file is located in root one level up from app dir.

4 Replies

West African CrocodileOP
And a follow up question, is there any option to make it work?
African Slender-snouted Crocodile
My understanding is that env variables are replaces at build time with a hard coded value (ie the next compiler sees
Stripe(process.env.STRIPE_SECRET_KEY!, {
  typescript: true,
  apiVersion: '2024-06-20'
})
and replaces that with
Stripe('your_api_key', {
  typescript: true,
  apiVersion: '2024-06-20'
})
So because of that, you can't destructure or use a non literal accessor to get env vars
Actually ignore what I said -- I missed that yours are not public env vars