tailwind-cssvitereact-tsxtailwind-css-4

How to use enviroment variables in Tailwind v4 (react-vite)?


At my current job, we use .env variables to set the main colors of the web pages. I've been using the new TailwindCSS setup where you define everything in index.css, but I haven't found a way to use environment variables directly in there.

This works, but is not what I'm looking for.

index.css

@import "tailwindcss";
    
@theme {
  --color-main: #62297f;
  --color-secondary: #5184c9;
}

.env

VITE_PRIMARY_COLOR=#3490dc
VITE_SECONDARY_COLOR=#ffed4a
VITE_ACTION_COLOR=#e3342f

Solution

  • First, run this function during project initialization to set up these colors as the root of the document:

    // utils/applyEnvColors.ts
    export function applyEnvColors() {
      const root = document.documentElement;
    
      const colorVars = {
        primary_color: import.meta.env.VITE_PRIMARY_COLOR,
        secondary_color: import.meta.env.VITE_SECONDARY_COLOR,
        action_color: import.meta.env.VITE_ACTION_COLOR,
      };
    
      Object.entries(colorVars).forEach(([key, value]) => {
        if (value && typeof value === 'string') {
          const formattedKey = `--color-${key.replace('_color', '').replace(/_/g, '-')}`;
          root.style.setProperty(formattedKey, value);
        }
      });
    }
    

    then use it in your tailwind.css

    @theme {
      --color-primary: var(--color-primary);
      --color-secondary: var(--color-secondary);
      --color-action: var(--color-action);
    }