Search code examples
javascriptreactjsnext.jsfrontend

Why does process.env.BACKEND_URL log undefined in the console but display correctly in a button in my Next.js app?


I am working on a Next.js project and I have encountered an issue with environment variables. In my Home component, I am trying to log the value of process.env.BACKEND_URL to the console and also display it inside a button.

'use client'
import Appbar from "./Components/Appbar";
import { Button } from "@/components/ui/button";

export default function Home() {

  const show = () => {
    console.log("ASHHHHHHHH");
    console.log(process.env.BACKEND_URL);  // Access the environment variable here
  }

  return (
    <main >
      <Appbar />
      <Button onClick={show}>
        {process.env.BACKEND_URL}
      </Button>
    </main>
  );
}

When I run this, the console logs undefined for process.env.BACKEND_URL, but the button correctly displays http://localhost:4000. (https://i.sstatic.net/zO3ZSlK5.jpg)

To debug, I created a utils.ts file:

export const backend_url = process.env.BACKEND_URL;

However, logging backend_url still gives undefined.

Can someone explain why this is happening and how to fix it so that the environment variable is correctly logged in the console?

Thank you!


Solution

  • Environment variables without prefix NEXT_PUBLIC_ are only available on server side, try updating your .env and add NEXT_PUBLIC_BACKEND_URL so that it can accessed on both server and client.