next.jsgraphqlapollo-client.env

Not able to access .env variables in NextJS GraphQL


First of all, let me tell you all that I have tried all the stack overflow solutions but none are working in my case, I'm using the new version of NextJS (version 14), so I'm posting this question after going through all of the old questions so don't marks this as duplicate.

Okay coming to the main problem,

my problem is I'm using the Apollo client (GraphQL) in my NextJS application and I want to change the URI of the Apollo client depending on the (NODE_ENV) environment using the .env ( or even .env.development / .env.production / .env.local , anything that works).

But I'm not able to do this, when is do the console of process.env just getting an empty object in the browser console, but I am getting everything in my VS code console like below:

enter image description here

My .env file and .env.local file:-

enter image description here

And below is the code for my Apollo Client

import { ApolloClient, InMemoryCache } from "@apollo/client";

const CreateApolloClient = () => {
  console.log(process.env, "PROCESS");
  return new ApolloClient({
    uri: `http://localhost:4000/graphql`,
    cache: new InMemoryCache(),
  });
};

export default CreateApolloClient;

Please help me with the above issue and feel free to ask for any details that you want to know.


Solution

  • To make your environment variable available on the client, you need to prefix it with NEXT_PUBLIC_

    https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser