简体   繁体   中英

NextJS environment variables undefined?

I've made a script to save some static data to my filesystem which looks like this

./lib/createLinks.js

 const contentful = require('contentful') const fs = require('fs') require('dotenv').config({ path: `.env.${process.env.NODE_ENV}`, }) async function createLinks() { const client = contentful.createClient({ space: process.env.NEXT_CONTENTFUL_SPACE_ID, accessToken: process.env.NEXT_CONTENTFUL_ACCESS_TOKEN, }) const data = await client.getEntries({ content_type: 'news', }) fs.writeFile('./data/links.json', JSON.stringify(data), (err) => { if (err) throw err console.info('Global data written to file') }) } async function main() { try { await createLinks() } catch (err) { throw new Error(err) } } main()

 "create-links": "node./lib/createLinks", "dev": "yarn create-links && next dev", "build": "yarn create-links && next build",

However I can't access my environment variables which is undefined when I try to run this.

My variables are placed in the root in.env.local

Why is this happening?

I solved it by adding the following to my package.json

 "dev": "NODE_ENV=local yarn create-links && next dev", "build": "NODE_ENV=local yarn create-links && next build",

For some reason this + node_env=local helped my situation

process.env['NEXT_PUBLIC_BACKEND_URL']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM