Search code examples
next.jsenvironment-variablesgetstaticpaths

Environment variable doesn't work in getStaticPaths in NextJS


I would like to replace, in my getStaticProps, getStaticPaths and API routes, all mongodb connection URI strings by environment variables

From :

const client = await MongoClient.connect(
  'mongodb+srv://XXX:[email protected]/meetups?retryWrites=true&w=majority'
)

To:

const client = await MongoClient.connect(`${process.env.MONGODB_URI}`)

With MONGODB_URI coded like that in .env.local

DB_USER='XXX'
DB_PASS='XXX'
MONGODB_URI='mongodb+srv://$DB_USER:[email protected]/meetups?retryWrites=true&w=majority'

It perfectly works on getStaticProps and api routes, but not with getStaticPaths where variable is undefined...

All documentation I have read says that .env are accessible from server throught getStaticPaths as well as getStaticProps and api folder.

Notice that the app perfectly works with hard coded string

Thanks in advance


Solution

  • Done. Just have to delete the .next folder and restart my dev server.

    I didn't do it before because I had the message bellow in my terminal on each save and env variables where ok in other methods without any other actions, only in getStaticPaths.

    Info  - Loaded env from C:\...\.env.local 
    

    Strange but ok :)