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.
CodePudding user response:
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 (
...
);
}