vitereact-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 Tailwind setup where you define everything in index.css, but I haven’t found a way to use environment variables directly in there.

My index.css, this WORKS, but is not what im looking for

@import "tailwindcss";

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

My .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)';
    }