Experiencing issues with undefined NextJS environment variables?

I've developed a custom script to store some fixed data onto my file system. The script is located at the following path:

./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",

Unfortunately, I am facing an issue where my environment variables are undefined when attempting to execute the script.

The variables are stored in the root directory in a file named .env.local.

What could be causing this problem?

Answer №1

To resolve the issue, I included the code snippet below in my package.json file:

"start": "NODE_ENV=production yarn create-links && next start",
"compile": "NODE_ENV=development yarn create-links && next build",

Answer №2

Adding node_env=local surprisingly resolved the issue I was experiencing

process.env['NEXT_PUBLIC_BACKEND_URL']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the nest function in D3 to organize flat data with a parent key into a hierarchical structure

I'm searching for an elegant and efficient solution to transform my input data into a hierarchical structure using d3.js nest operator. Here is an example of the input data: [ {id: 1, name: "Peter"}, {id: 2, name: "Paul", manager: 1}, {id: 3, name: " ...

underscore.js does not allow data to be manipulated outside of the _.each

Struggling to get my head around utilizing the underscore loop in jQuery's $.ajax function for retrieving a JSONp file... Within the success section, I have the following code snippet: success : function(response) { var dataResp = '' ...

Utilize strings as object keys in JavaScript

Let's say I have the following variables: var myKey = "This_is_my_key" var myObj = {"This_is_my_key" : true} What is the proper way to access myObj using the key myKey? ...

Tips for updating a portion of your code using new variables in JavaScript

I'm currently working on implementing a commenting feature for my website. The goal is to display new comments above the existing comment section when users submit their feedback. However, I'm facing challenges in dynamically updating the HTML wi ...

What is the most efficient method for arranging the numbers in a whole number?

Is there a more efficient method than storing the numbers in an array and using .sort() to arrange them? ...

Endless Google Locations Instances

My database entries are being displayed in a table using input fields. I want the Location field for each entry to be automatically completed using Google's API. HTML: <input name="edit_airplane[1][location]" type="text" class="airplane_location" ...

Personalize the drop area in Filepond

Is there a way to customize the filepond droparea by adding custom HTML with placeholder images to guide users on what kind of images should be uploaded and allow multiple uploads? https://i.sstatic.net/VFGfJ.png I attempted to add placeholders in an abs ...

Ways to implement pointer event styling within a span element

Hi, I'm having trouble with styling and I can't seem to figure out how to resolve it. The style pointer-events: none doesn't seem to be working for me. Here is an example of my code: The style snippet: .noclick { cursor: default; ...

Exploring Elasticsearch: Uncovering search results in any scenario

I've been working on a project where my objective is to receive search engine results under all conditions. Even if I enter a keyword that is not included in the search data or if it is an empty string, I still want to get some kind of result. How can ...

Creating a div that functions as a scrollbar controller

I am in search of a unique way to customize the scrolling functionality on my application, resembling more of a navbar that scrolls. However, I have not been able to find any existing plugins that meet my specific requirements. My inquiry includes: Whic ...

The API endpoint returns a 404 not found error on NextJS 14 in the production environment, while it functions correctly on the local

I am in the process of creating a small website using NEXT JS 14. On my website, there is a contact us page that I have been working on. In the GetInTouch.tsx file, I have the following code: <Formik initialValues={{ ...

Unfortunately, IE8 does not support binding with underscores

In my code, I am utilizing _.bind from underscore.js but unfortunately, it is not functioning properly in IE8/9. I have come across a workaround on MDN (MDN Polyfill), however, I am uncertain if this can be implemented with the underscore library. I am al ...

The function $.fn.dataTable.render.moment does not exist in npm package

I have encountered an issue with my application that I am struggling to solve: I want to format dates in my data table using Moment.js like I have done in the following script: $().ready(function() { const FROM_PATTERN = 'YYYY-MM-DD HH:mm:ss.SSS&a ...

What is the best way to retrieve recently inserted data using Sequelize in PostgreSql?

Is there a way to retrieve updated table values after adding a user to the "WOD" table without making an additional query? Currently, when I add a third user to my WOD table, I can only return the first two users because I am unable to access the updated ...

What is preventing me from being able to import a React component from a file?

I've double-checked my code and everything seems correct, but when I view it on the port, only the app.js file is displayed. import React from 'react'; import ImgSlider from './ImgSlider'; import './App.css'; function ...

Just easy highlighting using tags in Javascript

I have come across a code snippet that seems to be functioning well: <html> <head> <title>Testing JS Highlighting</title> <script type="text/javascript"> function highlight() { var t = ...

Check through an array for any updates whenever a function is called and my react state is altered

I am currently working on a project related to playlists. My goal is to display the image attached to each song whenever that song is clicked from the playlist. Here is the code I have so far... const Component = () => { const value = useContext(DataC ...

POST request failed with a 500 Internal Server Error in NextJS version 14.0.3 and Node version 20

I'm encountering a problem when trying to save orders using the post method as it keeps resulting in a 500 Internal Server Error. I would appreciate any assistance in identifying the issue. Console POST http://localhost:3000/api/orders 500 (Internal ...

What occurs when an organization's npm has numerous versions accessible?

As someone who is just starting to version a library, I would like some clarification on how npm works. I am in the process of creating a library and want to publish it to my organization's npm registry. I currently have an alpha release available in ...

The flat function for JavaScript Arrays is not defined in React Native

I am currently developing an application using react-native and it's common knowledge that we can utilize JavaScript code in this particular project as well as any other react projects. However, whenever I attempt to use the following code snippet, t ...