23 Feb 2025

Better way to read env variables compared to process.env.ENV_VAR?

I am using env variables like process.env.ENV_VAR and for client side access using process.env.NEXT_PUBLIC_ENV_VAR but when I forgot to add env then I am not able to identify unless my application breaks someday.

So I tried to find better way to manage env variables in nextjs and at the same time it should be secure.


I found a blog post "You are reading environment variables the wrong way in Next.js" which is guiding to create an ./config.js or ts.

below is the example with usage based on blogpost

// config.ts (define)
const getEnvironmentVariable = (environmentVariable: string): string => {
  const unvalidatedEnvironmentVariable = process.env[environmentVariable];
  if (!unvalidatedEnvironmentVariable) {
    throw new Error(
      `Couldn't find environment variable: ${environmentVariable}`
    );
  } else {
    return unvalidatedEnvironmentVariable;
  }
};

export const config = {
  apiKey: getEnvironmentVariable("API_KEY")
};
// somefile.js or .ts (usage)
import { config } from "./config"

const url = `https://www.example.com/api/blog?api_key=${config.apiKey}`

My main concern is "Is it safe to use?" for example I am using config.apiKey in sever side which is okay but, what if I accidently called this is client side like config.apiKey.

Because config.ts is on server side and it's now on config.apiKey ideally it should only be accessed in server environment but since we have stored it on variable so we can also use in client side which is not safe.

You may also like

Python 3 basics: An introduction to Python's syntax and fundamental concepts

This blog post provides an introduction to the syntax and fundamenta...

Continue reading

Using HTML semantic elements for better website structure

HTML semantic elements provide structure and meaning to website cont...

Continue reading

Python Performance Optimization: Techniques to Speed Up Your Code

Python Performance Optimization: Techniques to Speed Up Your Code ex...

Continue reading