Having issues with the environmental value not functioning properly within the .js file for Next.js

Currently, I am in the process of testing an app that features a widget which relies on an API key within a script. This script needs to be placed within my <head> tags. My .js file is located in my public folder and is being imported into my layout.tsx like this:

<html lang="en">       
    <Script src="crm.js"/>
    <body>

To handle the API key securely, I have created an .env.local file and stored my variable there:

NEXT_PUBLIC_META_CRM_API_KEY=xxxxxxxxxxx

Within my .js file, I have referenced the variable like so:

 MetaCRMWidget.init({
    apiKey: process.env.NEXT_PUBLIC_META_CRM_API_KEY
  });

The issue I am facing is that the widget fails to load due to authorization problems when using the environment variable. However, manually entering the API key directly into the script allows it to work properly.

My current focus is on testing this setup locally.

Here are some images depicting the errors encountered when trying to use

process.env.NEXT_PUBLIC_META_CRM_API_KEY
: https://i.sstatic.net/mqD0O.png

Answer №1

The Next.js documentation states that directly reading process.env from a .js file is not possible. During build time, Next transforms process.env.NEXT_PUBLIC_META_CRM_API_KEY to its actual value. Since you are loading the script from a script tag, Next may not be transforming the value, leading to the error "process is not defined" in the console. Since the API key is not a secret and being exposed publicly, consider inputting the API key directly in the widget init code like this:

MetaCRMWidget.init({
    apiKey: "your api key"
});

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

Error in Jquery validation caused by incorrect file extension type

Within my HTML form, I have multiple inputs set up for validation purposes: <form role="form" id="addForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="userName">U ...

Verifying the presence of a popover

Utilizing bootstrap popover in my project, I am encountering an issue where the target variable may not always exist on the page. Currently, I am displaying the popover using the following code snippet - target = $('#' + currentPopoverId.data(& ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

The ReCaptcha and AJAX Integration

I am attempting to display the ReCaptcha image using its AJAX API. I have been following the instructions from this documentation and observing the behavior of this demo. Despite my efforts, I am still unable to create a functional fiddle. I have added jsf ...

Transform from a class-based component to a function-based component

Currently experimenting with AutoComplete and AutoFill features in React. My goal is to transition the code into using React hooks, as I have primarily used hooks throughout my project. I've made some progress in converting it to a hook-based struct ...

The error thrown states: "TypeError: Unable to access the property 'getFieldDecorator' of undefined in a React component."

Encountering this error: > TypeError: Cannot read property 'getFieldDecorator' of undefined > _class.render src/containers/RegisterTenant/register.js:81 78 | this.setState({ 'selectedFiles': files }); 79 | } 80 | > ...

Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this... <div ng-app="myApp"> <div ng-controller="inControl"> I enjoy sipping on {{beverage}}<br> <input my-dir ng-model="beverage"></input> </div> </div> a ...

Do not attempt to log after tests have finished. Could it be that you overlooked waiting for an asynchronous task in your test?

Currently, I am utilizing jest in conjunction with the Vue framework to create unit tests. My test example is successfully passing, however, I am encountering an issue with logging the request. How can I resolve this error? Is there a mistake in my usage o ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

Is your preference selecting made a breeze by dragging the input field?

Looking to create a form that allows users to indicate their preference between Option A and Option B by dragging a slider. I know there must be a library out there that already does this, but I can't seem to figure out what it's called to searc ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

What methods can be used to cloak JavaScript functions from the end user?

Looking to utilize jQuery AJAX calls? Here's an example: function addNewTeacher(){ $.ajax({ type: "POST", url: "/actions/dboss/newteacher.php", data: "uname=" + $("#newteacheruname").val() + "&upass=" + $("#new ...

What is the method for providing a date format choice in JSON?

I am encountering an issue in my PHP script where I use JSON to pass parameters. When I pass the date as "09-09-2015", it functions correctly. However, when I try to pass the date as $date, it does not work. How can I resolve this problem? $item1 = "test ...

Utilizing onClick to target data within a .map function

I am struggling with the code provided below: const test = (e) => { console.log('example:', e.target.item.attributes.dataIWant); } {records.map((item, index) => { return ( <> <Accordion key={index} ...

Display images with sequential animation and a delay, combining fade-in and slide-up effects

I am attempting to create a cycling image display with specific effects: There should be a one-second delay before the first image is shown. The first image will appear with a fade-in and slide-up effect. Image #1 will remain visible for 5 seconds before ...

Creating a canvas texture on tube geometry with three.js for optimal display on iPad devices

I have a 3D model of a tube geometry with 18000 coordinates on the production side. To simplify, I am selecting every 9th coordinate to plot 9000 coordinates for building the tube geometry using only the CanvasRenderer. When utilizing vertexColors: THREE. ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...

Error encountered: `next js 13.3 / Module could not be parsed: Octal number detected in strict mode

Error detected: Octal literal in strict mode. import { createProxy } from "next/dist/build/webpack/loaders/next-flight-loader/module-proxy" This issue arose following the 13.3 update when developing a client component within the app directory. ...

Setting the z-index for Bootstrap dropdown menus on containers that are generated dynamically

When using the Bootstrap 3 dropdown-menu within a dynamically generated container, I am encountering an issue where the dropdown-menu appears behind the newly created elements. Please refer to the image for visual clarification. The container item has pos ...

Childnode value getting replaced in firebase

Every time I attempt to push values to the child node, they keep getting overridden. How can I solve this issue and successfully add a new value to the child node without being overwritten? ...