Home > Blockchain >  Access environment variables from client
Access environment variables from client

Time:01-03

I'm making a lot of API calls from within my components using fetch. Everytime I had to write this logic to determine which environment I'm in So, I created a Utils class which returns the correct base url:

export default class Utils {
  static get baseUrl() {
    const inDev = process.env.NODE_ENV !== 'production';
    const { NEXT_PUBLIC_DEV_URL, NEXT_PUBLIC_PROD_URL } = process.env;
    return inDev ? NEXT_PUBLIC_DEV_URL : NEXT_PUBLIC_PROD_URL;
  }
}

But now I'm getting this error when my component loads:

ReferenceError: process is not defined

I looked around and found that I need to mark my variables as NEXT_PUBLIC so I did but the problem still persists. What's the ideal way to handle this?

CodePudding user response:

If you want to expose ENV variables to the client you can use publicRuntimeConfig inside your NextJS configuration (next.config.js). Here is how you could do it:

publicRuntimeConfig: {
  myEnvVar: process.env.MY_ENV_VAR
}

And then in the file you would like to use your ENV variable:

import getConfig from 'next/config';

const { publicRuntimeConfig } = getConfig();

const envVar = publicRuntimeConfig.myEnvVar // store in it a 'const' or do whatever you want with it,; 

CodePudding user response:

Your class can actually look like this :-

export default class Utils {
  static get baseUrl() {
    return process.env.NEXT_PUBLIC_URL;
  }
}

The NEXT_PUBLIC prefix should work well for inlining the values which are replaced at build time and sent to the browser as per docs.

In your .env.development (or whatever your dev environment file is called) file, you can have NEXT_PUBLIC_URL pointing to http://localhost:8000 and in your production you will probably have production env variables setup using a GUI (like in Netlify or Vercel), so there NEXT_PUBLIC_URL can be https://blablasite.com.

Either way, NEXT_PUBLIC prefix will ensure that at build time those values are picked up and inlined before sending the same to browser.

  • Related