Env in NextJS

NextJS comes with built-in support for env (environment variables). So We don’t need to install them.

Environment variables are typically used to set base urls to api endpoints, secrets like api keys or even environment dependent keys (like: google analytics key).

Create a ‘.env’ file in root folder

// .env

API_KEY = xjdhnbjzhjashdjhas                               (for using in server side)
NEXT_PUBLIC_BASE_URL = https://mywebsite.com/example/      (for using in browser)

To access environment variables in our code, we use process.env

const key = process.env.API_KEY;
const url = process.env.NEXT_PUBLIC_BASE_URL;

console.log('This is your api key', key);
console.log(`This is your base url - ${url}`);

Note: when doing in axios in Frontend:

they are useEffect, so it is request from client component, SO YOU NEED TO USE : NEXT_PUBLIC_

  useEffect(() => {
    axios.get(`${process.env.NEXT_PUBLIC_BACKEND_BASE_URL}/api/all-products`)
      .then( (response)=> {
        setProducts(response.data);
            })
      .catch((error)=> {
        console.log(error);
      });
    }, []);