PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] How to get environment variables on client side with Next.js?

 August 19, 2022     datadog, environment-variables, next.js, typescript     No comments   

Issue

I want to read environment variable into Next.js, how to pass 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, // can't use process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID directly here
      ...
    });

    datadogRum.startSessionReplayRecording();
  });

  return (
    ...
  );
}

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

This way can't get the applicationID value.


Solution

You don't need to pass the environment variable from getInitialProps. You can access it directly inside the useEffect, you just need to make sure process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID is defined before initialising datadogRum.init to avoid typings 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 (
        ...
    );
}


Answered By - juliomalves
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing