Skip to content

Environment Variable Initialization Race Condition in Monorepo #645

@NiloCK

Description

@NiloCK

Problem:
When StudySession component was moved from platform-ui to common-ui, we encountered CORS errors due to environment variables not being properly initialized. Investigation revealed that the ENVIRONMENT_VARS.ts module was being loaded twice in different contexts - once with proper environment values and once without. This is a module duplication issue caused by how different packages in our monorepo access the same module in different contexts (Vue SFC vs. regular TS files).

Solution Implemented:

  • Added a global singleton approach using window.__SKUILDER_ENV__ to ensure all instances of the module use the same environment values
  • Implemented a blocking retry mechanism to handle race conditions during initialization
  • Added fallback default values to ensure the application works even if environment variables fail to load

Remaining TODOs for Future Robustness:

  1. Non-blocking initialization:

    • Replace the current blocking retry with a non-blocking mechanism
    • Add an event system to notify components when environment variables are properly loaded
    • Add isReady flag and onReady callback registration
  2. Build system improvements:

    • Configure Vite/webpack to treat common package as an external dependency to prevent duplication
    • Set up proper environment variable sharing between packages in the monorepo
    • Add a plugin to ensure environment variables are consistently available to all packages
  3. Architecture improvements:

    • Create a proper dependency injection system for configuration values
    • Implement a service locator pattern for database services that depend on environment variables
    • Refactor database access to be more resilient to configuration changes
  4. Testing:

    • Add tests specifically for environment variable initialization
    • Test behavior under various race conditions
    • Document the proper usage pattern for modules that depend on environment variables

This solution provides a reliable way to handle environment variables in our monorepo, but a more comprehensive approach will be needed as the application grows.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions