I am using Nextjs, and want to call process.env
from within a page. I overrode the default Document with _document.js and wrote this:
export default function Document() {
return (
<Html>
<Head>
<Script>{`console.log(process.env.NEXT_PUBLIC_ENV)`}</Script>
</Head>
</Html>
This causes a "Uncaught ReferenceError: process is not defined" error in console. My ultimate intent is to load a GA4 script in production environment and not development. I know how to do that part, but where I am confused is why process
is undefined. It works outside the function, but not inside it.
Why?
This is happening because process
object is not available inside an inline script. It is only accessible to the function and not html elements and/or browser. instead, create a variable in the function as -
export default function Document() {
const publicEnv= process.env.NEXT_PUBLIC_ENV;
return (
<Html>
<Head>
<Script>{`console.log(publicEnv)}</Script>
</Head>
</Html>
)
}