Getting environment variables on the client side in Next.js: A step-by-step guide

How can I retrieve an environment variable in my Next.js application and pass the data into datadogRum.init?

// _app.tsx

import React from "react";
import { useEffect } from "react";
import type { AppProps } from "next/app";
import { datadogRum } from "@datadog/browser-rum";

export default function App({ Component, pageProps }: AppProps) {
  useEffect(() => {
    datadogRum.init({
      applicationId: applicationID, // unable to directly use process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID here
      ...
    });

    datadogRum.startSessionReplayRecording();
  });

  return (
    ...
  );
}

App.getInitialProps = async () => {
  return {
    applicationID: process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID,
  };
};

This setup does not allow for retrieving the value of applicationID.

Answer №1

Incorporating the environment variable in getInitialProps is not necessary. Inside the useEffect, you can directly access it, ensuring that

process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID
is defined before initializing datadogRum.init to prevent typing conflicts.

export default function App({ Component, pageProps }: AppProps) {
    useEffect(() => {
        if (typeof process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID !== "undefined")
            datadogRum.init({
                applicationId: process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID
                ...
            });

            datadogRum.startSessionReplayRecording();
        }
    });

    return (
        ...
    );
}

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

The issue of WooCommerce GraphQL API not returning a comprehensive list of product variations is causing frustration among users

I'm currently working on a project that involves WooCommerce integration with WordPress and utilizing GraphQL to retrieve product variations. One issue I've encountered is that the GraphQL API is only returning 10 out of 12 variations for a speci ...

Preventing a user from accessing the login page if they are already logged in using Reactjs

I need assistance with implementing a "Login Logout" module in Reactjs using the nextjs framework. My goal is to redirect users to the "dashboard" page if they are logged in (email set in cookie). However, I am encountering an error with the following co ...

Webclipse is having trouble locating a module, despite the fact that Angular CLI is able to

I am facing an issue with my project structure src | +--app | +--components | | | +-component.ts | +--entities | +--entity.ts In entity.ts, I have export class Entity { ... In component.ts, there is an import statement ...

What steps should I follow to update my NextJS version from v11 to v13?

I am currently working on upgrading the dependencies of my NextJS project to address security vulnerabilities using npm v9.5.1. The reason behind this task is the detection of a security issue by npm audit in my project: node-fetch <2.6.7 Severity: hi ...

Sorting an array of objects in Typescript using a dynamic property name for generics

My goal is to develop a versatile, typed function that can arrange an array of objects by a numerical value housed under a dynamically named property within each object. Here is my current progress: export const sortByNumber = <T, K extends keyof T> ...

Navigate back to the home page in Next.js and automatically scroll to the previous position you were at on the page

I'm currently working on a next.js app and I'm trying to implement a "back to start" link with specific behavior: The user starts on the main page and scrolls down. When navigating to a subpage, they should find the "back to start" link. If the ...

Avoid the import of @types definition without exports in TypeScript to prevent the error TS2306 (not a module)

I have spent a considerable amount of time trying to load a NodeJS library that has what I believe is a faulty type definition in the @types repository. The library in question is geolib and its types can be found in @types/geolib Although I am aware tha ...

Is it possible to derive a TypeScript interface from a Mongoose schema without including the 'Document' type?

Using ts-mongoose allows me to define interfaces and schemas for my data in one place. I then export them as a mongoose schema along with the actual interface. The challenge I'm facing is finding a simple way to extract that interface without includi ...

Importing CSS properties from MUI v5 - A comprehensive guide

I'm working with several components that receive styles as props, such as: import { CSSProperties } from '@material-ui/styles/withStyles' // using mui v4 import because unsure how to import from v5 paths import { styled } from '@mui/mat ...

Tips for creating a hover effect on an icon within a CSS grid

I've just started learning to code and wanted to create a component for previewing/displaying a project I'm working on. I've been attempting to add a hover effect to my links such as the GitHubIcon and LaunchIcon, but so far, it's not w ...

What could be the reason for the undefined value of my ID retrieved from the next JS router.query upon page refresh?

When using the id obtained from the next router.query to dynamically render elements, it works fine when accessing the room from next/link. However, upon refreshing the page, an error is thrown. https://i.stack.imgur.com/yEjGS.png Below is the code snipp ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

Creating a web application using Aframe and NextJs with typescript without the use of tags

I'm still trying to wrap my head around Aframe. I managed to load it, but I'm having trouble using the tags I want, such as and I can't figure out how to load a model with an Entity or make it animate. Something must be off in my approach. ...

Encountering a TypeError when trying to start the nextjs server

Every time I run my next server with npm run dev, I keep encountering the same error. After testing it on a fully functional project, I am convinced that the issue is not related to the code. I suspect that the problem may be caused by running: npm insta ...

Create generic functions that prioritize overloading with the first generic type that is not included in the parameters

I encountered an issue while utilizing generic overload functions, as demonstrated below in the playground. The generic type T1 is solely used in the return type and not the parameters. Therefore, when attempting to use overload #2, I am required to speci ...

When running Nextjs locally, Sendgrid functions seamlessly. However, when I deploy it on Vercel, Sendgrid

I've successfully tested this locally, but encountered a "Response Error: Unauthorized" when deploying on Vercel. After creating and verifying a Single Sender Verification on Sendgrid, I attempted to generate a new API key, but the issue persists. I ...

Angular Error: Unable to access property 'users' on a null value

I am working on a component that takes in data through the @Input() decorator regarding a group. My objective is to generate a new array of objects during the initialization of the component based on the data from the group array. Below is the TypeScript c ...

Difficulty encountered when saving cookies on the browser in the context of NEXTjs and Redux RTK query

Currently, I am immersed in a Django project for the backend. The XCRF token is being retrieved via API cookies, as depicted in the screenshot from Postman provided below. https://i.stack.imgur.com/zc68R.png Furthermore, access is granted through the red ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...