Skip to content

Conversation

Oksamies
Copy link
Contributor

@Oksamies Oksamies commented Sep 4, 2025

In some cases 3rd party scripts, like ads, will try to use such generic
name as window.ENV

Summary by CodeRabbit

  • New Features
    • No user-facing features added.
  • Refactor
    • Standardized how public configuration is exposed in the browser and across the app to improve consistency and reliability across environments.
  • Chores
    • Renamed and clarified internal types and streamlined environment handling. No functional impact expected for end-users.

Copy link

coderabbitai bot commented Sep 4, 2025

Walkthrough

Refactors public environment variable exposure: renames types and global window key, flattens publicEnvVariables shape, updates loader/clientLoader return, inline script injection, and all consumers to use window.NIMBUS_PUBLIC_ENV and top-level VITE_API_URL.

Changes

Cohort / File(s) Summary
Client env exposure and consumption
apps/cyberstorm-remix/app/root.tsx
Replaces ENV wrapper with flat publicEnvVariables. Injects window.NIMBUS_PUBLIC_ENV instead of window.ENV. Updates loader/clientLoader return shape, Navigation domain, Dapper config, and Outlet context to use publicEnvVariables.VITE_API_URL. Updates Window global typing.
Public env variables utility
apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts
Renames exported type publicEnvVariablespublicEnvVariablesType. Updates function return/type usage. On browser, reads from window.NIMBUS_PUBLIC_ENV instead of window.ENV. SSR collection logic unchanged.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant B as Browser
    participant S as Remix Server
    participant U as getPublicEnvVariables
    participant L as Layout (HTML)
    participant C as Client App

    B->>S: Request /
    S->>U: getPublicEnvVariables()
    U-->>S: { VITE_* keys }
    S-->>B: HTML + data.publicEnvVariables
    Note over L: Inline script sets<br/>window.NIMBUS_PUBLIC_ENV = data.publicEnvVariables
    B->>C: Hydration starts
    C->>C: Read NIMBUS_PUBLIC_ENV.VITE_API_URL
    C-->>C: Configure Navigation/Dapper/Outlet context
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

A nimble nibble of Nimbus wind,
I flip my ears—ENV rescind!
VITE crumbs scatter, flat and neat,
In public fields where clients meet.
Hop! A URL, crisp and bright—
I bound through configs, left to right.
Carrot-shaped vars, delight! 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 09-04-rename_window.env_to_reduce_clashing_with_other_scripts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor Author

Oksamies commented Sep 4, 2025

Base automatically changed from 09-04-remove_promise.withresolvers_usage_from_package_detail_page to master September 4, 2025 19:25
In some cases 3rd party scripts, like ads, will try to use such generic
name as window.ENV
@Oksamies Oksamies force-pushed the 09-04-rename_window.env_to_reduce_clashing_with_other_scripts branch from f598020 to af1410a Compare September 4, 2025 19:30
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts (1)

47-49: Fix user-facing typo in error message

“Enviroment” → “Environment”. This surfaces to users.

Apply:

-      "Enviroment variables did not load correctly, please hard refresh page"
+      "Environment variables did not load correctly, please hard refresh the page"
apps/cyberstorm-remix/app/root.tsx (1)

124-129: Fix user-facing typo in error message

Same typo here; fix before shipping.

Apply:

-      "Enviroment variables did not load correctly, please hard refresh page"
+      "Environment variables did not load correctly, please hard refresh the page"
🧹 Nitpick comments (3)
apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts (1)

14-16: Simplify the type (avoid double-optional) and consider PascalCase for types

You can express this more cleanly as a Partial<Record<... , string>>. Also, TypeScript convention is PascalCase for type names.

Apply:

-export type publicEnvVariablesType = Partial<{
-  [key in PublicPrefix<publicEnvVariablesKeys>]: string | undefined;
-}>;
+export type publicEnvVariablesType = Partial<
+  Record<PublicPrefix<publicEnvVariablesKeys>, string>
+>;
apps/cyberstorm-remix/app/root.tsx (2)

48-52: Move global Window augmentation to a .d.ts file

Placing global typings in a dedicated .d.ts avoids reliance on this module’s import order and ensures availability project-wide.

Example (create types/global.d.ts):

import type { publicEnvVariablesType } from "cyberstorm/security/publicEnvVariables";
import type { DapperTs } from "@thunderstore/dapper-ts";

declare global {
  interface Window {
    NIMBUS_PUBLIC_ENV: publicEnvVariablesType;
    Dapper: DapperTs;
    nitroAds?: {
      createAd: (containerId: string, params: {
        demo: boolean;
        format: string;
        refreshLimit: number;
        refreshTime: number;
        renderVisibleOnly: boolean;
        refreshVisibleOnly: boolean;
        sizes: string[][];
        report: { enabled: boolean; wording: string; position: string };
        mediaQuery: string;
      }) => void;
    };
  }
}
export {};

93-101: Deduplicate env key lists to avoid drift

The loader and clientLoader repeat the same key array.

Apply this change inside both call sites:

-  const publicEnvVariables = getPublicEnvVariables([
-    "VITE_SITE_URL",
-    "VITE_BETA_SITE_URL",
-    "VITE_API_URL",
-    "VITE_COOKIE_DOMAIN",
-    "VITE_AUTH_BASE_URL",
-    "VITE_AUTH_RETURN_URL",
-    "VITE_CLIENT_SENTRY_DSN",
-  ]);
+  const publicEnvVariables = getPublicEnvVariables([...PUBLIC_ENV_KEYS]);

Add once near the imports:

import type { PublicPrefix, publicEnvVariablesKeys } from "cyberstorm/security/publicEnvVariables";

const PUBLIC_ENV_KEYS = [
  "VITE_SITE_URL",
  "VITE_BETA_SITE_URL",
  "VITE_API_URL",
  "VITE_COOKIE_DOMAIN",
  "VITE_AUTH_BASE_URL",
  "VITE_AUTH_RETURN_URL",
  "VITE_CLIENT_SENTRY_DSN",
] as const satisfies ReadonlyArray<PublicPrefix<publicEnvVariablesKeys>>;

Also applies to: 114-122

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2b18496 and af1410a.

📒 Files selected for processing (2)
  • apps/cyberstorm-remix/app/root.tsx (8 hunks)
  • apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/cyberstorm-remix/app/root.tsx (1)
apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts (1)
  • publicEnvVariablesType (14-16)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Test
  • GitHub Check: Generate visual diffs
  • GitHub Check: CodeQL
🔇 Additional comments (6)
apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts (1)

20-22: Return typing and local variable typing look consistent

The function signature and returnedVars typing now match the new alias.

apps/cyberstorm-remix/app/root.tsx (5)

41-42: Type import alignment looks good

Importing publicEnvVariablesType here keeps the window typing consistent.


107-110: Return shape change LGTM

Updated to expose publicEnvVariables at the top level.


230-231: Domain prop update LGTM

Using the flattened VITE_API_URL matches the new shape.


273-276: Dapper config source LGTM

apiHost now reads from the flattened env as intended.


283-284: Outlet context domain LGTM

Consistent with other updates.

Comment on lines +41 to 42
publicEnvVariablesType,
} from "cyberstorm/security/publicEnvVariables";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Repo-wide verification to catch stragglers after the rename

Scan for old window.ENV and nested .ENV usages; also ensure the new global is referenced where needed. This avoids runtime issues in un-touched routes/components.

Run:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Old global or nested shape
rg -n -C2 -S -P '\bwindow\.ENV\b|publicEnvVariables\.ENV\b|ENV\.(VITE_|PUBLIC_)'

# New global usage exists
rg -n -C2 -S -P '\bwindow\.NIMBUS_PUBLIC_ENV\b'

# Catch typos like "Enviroment variables"
rg -n -C1 -S 'Enviroment variables'

Length of output: 102


🏁 Script executed:

#!/bin/bash

# Search for old global or nested ENV usages; ignore exit codes to continue scanning
rg -n -C2 -S -P '\bwindow\.ENV\b|publicEnvVariables\.ENV\b|ENV\.(VITE_|PUBLIC_)' || echo "✅ no old ENV usages found"

# Verify new global usage exists
rg -n -C2 -S -P '\bwindow\.NIMBUS_PUBLIC_ENV\b' || echo "⚠️ no new NIMBUS_PUBLIC_ENV references found"

# Catch common typo "Enviroment variables"
rg -n -C1 -S 'Enviroment variables' || echo "✅ no typo matches found"

Length of output: 1739


Fix typo in error messages
Change “Enviroment variables did not load correctly…” to “Environment variables did not load correctly…” in:

  • apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts (line 48)
  • apps/cyberstorm-remix/app/root.tsx (line 128)
🤖 Prompt for AI Agents
In apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts around line
48 and apps/cyberstorm-remix/app/root.tsx around line 128, fix the typo in the
error message by replacing "Enviroment variables did not load correctly…" with
the correct spelling "Environment variables did not load correctly…" (preserve
punctuation and capitalization exactly as in the surrounding messages).

Comment on lines +220 to 222
__html: `window.NIMBUS_PUBLIC_ENV = ${JSON.stringify(
data.publicEnvVariables
)}`,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden the global: make it read-only and resilient; consider CSP

Prevent third-party scripts from mutating or overwriting the exposed env by defining it as non-writable + frozen; also don’t overwrite if already set. If you use a CSP, ensure this inline script is nonce’d or hashed.

Apply:

-            __html: `window.NIMBUS_PUBLIC_ENV = ${JSON.stringify(
-              data.publicEnvVariables
-            )}`,
+            __html: `(function(){if(!("NIMBUS_PUBLIC_ENV" in window)){Object.defineProperty(window,"NIMBUS_PUBLIC_ENV",{value:Object.freeze(${JSON.stringify(
+              data.publicEnvVariables
+            )}),writable:false,configurable:false,enumerable:true});}})();`,

Optional (CSP): add a nonce to this script tag consistent with your CSP setup.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
__html: `window.NIMBUS_PUBLIC_ENV = ${JSON.stringify(
data.publicEnvVariables
)}`,
__html: `(function(){
if (!("NIMBUS_PUBLIC_ENV" in window)) {
Object.defineProperty(window, "NIMBUS_PUBLIC_ENV", {
value: Object.freeze(${JSON.stringify(
data.publicEnvVariables
)}),
writable: false,
configurable: false,
enumerable: true
});
}
})();`,
🤖 Prompt for AI Agents
In apps/cyberstorm-remix/app/root.tsx around lines 220-222, the inline script
currently assigns window.NIMBUS_PUBLIC_ENV directly which allows mutation or
overwrite; change it to only set the value if undefined, then Object.freeze the
object and use Object.defineProperty to make the global
non-writable/configurable so third-party scripts cannot mutate it; ensure the
script generation includes any CSP nonce or hash required by your CSP setup so
the inline script is allowed.

Comment on lines 29 to 33
vars.forEach((envVar) => {
if (envVar.startsWith("VITE_") && envVar in window.ENV) {
returnedVars[envVar] = window.ENV[envVar];
if (envVar.startsWith("VITE_") && envVar in window.NIMBUS_PUBLIC_ENV) {
returnedVars[envVar] = window.NIMBUS_PUBLIC_ENV[envVar];
}
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Defensive access to window.NIMBUS_PUBLIC_ENV to prevent runtime errors

If the inline script fails to run (e.g., CSP), window.NIMBUS_PUBLIC_ENV will be undefined and in will throw. Also prefer own-property checks.

Apply:

-  } else {
-    vars.forEach((envVar) => {
-      if (envVar.startsWith("VITE_") && envVar in window.NIMBUS_PUBLIC_ENV) {
-        returnedVars[envVar] = window.NIMBUS_PUBLIC_ENV[envVar];
-      }
-    });
-  }
+  } else {
+    const publicEnv =
+      typeof window !== "undefined" && (window as any).NIMBUS_PUBLIC_ENV
+        ? ((window as any).NIMBUS_PUBLIC_ENV as Record<string, string | undefined>)
+        : {};
+    vars.forEach((envVar) => {
+      if (
+        envVar.startsWith("VITE_") &&
+        Object.prototype.hasOwnProperty.call(publicEnv, envVar)
+      ) {
+        returnedVars[envVar] = publicEnv[envVar];
+      }
+    });
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
vars.forEach((envVar) => {
if (envVar.startsWith("VITE_") && envVar in window.ENV) {
returnedVars[envVar] = window.ENV[envVar];
if (envVar.startsWith("VITE_") && envVar in window.NIMBUS_PUBLIC_ENV) {
returnedVars[envVar] = window.NIMBUS_PUBLIC_ENV[envVar];
}
});
} else {
const publicEnv =
typeof window !== "undefined" && (window as any).NIMBUS_PUBLIC_ENV
? ((window as any).NIMBUS_PUBLIC_ENV as Record<string, string | undefined>)
: {};
vars.forEach((envVar) => {
if (
envVar.startsWith("VITE_") &&
Object.prototype.hasOwnProperty.call(publicEnv, envVar)
) {
returnedVars[envVar] = publicEnv[envVar];
}
});
}
🤖 Prompt for AI Agents
In apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts around lines
29 to 33, the code uses the `in` operator against `window.NIMBUS_PUBLIC_ENV`
which will throw if that global is undefined (e.g., CSP blocked the inline
script); change the logic to first defensively check that `window` and
`window.NIMBUS_PUBLIC_ENV` are defined (truthy) before iterating, and when
checking membership use an own-property check (e.g.,
Object.prototype.hasOwnProperty.call(window.NIMBUS_PUBLIC_ENV, envVar)) so you
avoid prototype-inherited keys and runtime errors; if the global is missing,
skip adding vars or fall back to an empty object.

@Oksamies Oksamies merged commit ba1e24d into master Sep 4, 2025
23 of 24 checks passed
@Oksamies Oksamies deleted the 09-04-rename_window.env_to_reduce_clashing_with_other_scripts branch September 4, 2025 19:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant