Skip to content

Conversation

@maparent
Copy link
Collaborator

@maparent maparent commented Aug 31, 2025

https://linear.app/discourse-graphs/issue/ENG-813/repair-and-improvements-to-dbdotenv

Context: I noticed failure of cucumber-js to load dbDotEnv. That led to the first step below, but when testing that I found out about other issues with vercel functions.

Replace __filename with urlFromPath, as it seems to sometimes be called as ejs.
Use SUPABASE variables when defined.
(It means that the database will be used if those are defined in a .env file.)
Give warnings to the developer as appropriate.
nextjs should use dbDotEnv.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of environment configuration across local, preview, and production runs.
    • Automatically loads available environment variables before app startup to prevent missing configuration issues.
    • Better handling of hosted deployments to reduce runtime failures due to absent variables.
  • Chores

    • Standardized environment resolution to support both file-based and deployment-provided variables.
    • Modernized environment loading internals and typings for clearer, more consistent configuration behavior.

Replace __filename with urlFromPath, as it seems to sometimes be called as ejs.
Use SUPABASE variables when defined.
(It means that the database _will_ be used if those are defined in a `.env` file.)
Give warnings to the developer as appropriate.
nextjs should use dbDotEnv.
@linear
Copy link

linear bot commented Aug 31, 2025

@supabase
Copy link

supabase bot commented Aug 31, 2025

This pull request has been ignored for the connected project zytfjzqyijgagqxrzbmz because there are no changes detected in packages/database/supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@maparent
Copy link
Collaborator Author

@CodeRabbit review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 31, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 31, 2025

📝 Walkthrough

Walkthrough

Introduces database-driven environment loading. apps/website/next.config.ts imports envContents and copies non-falsy entries into process.env at module load. packages/database/src/dbDotEnv.js is refactored to ESM, expands variant detection, and adds envFilePath, envContents, and config helpers. Type declaration updates envContents return type to Record<string, string>.

Changes

Cohort / File(s) Summary
Next.js config env injection
apps/website/next.config.ts
Imports envContents from @repo/database/dbDotEnv and assigns its non-falsy key-values to process.env before exporting NextConfig. No structural changes to NextConfig.
Database dotenv utilities refactor
packages/database/src/dbDotEnv.js
Migrates to ESM, rewrites root/variant resolution, adds broader deployment handling (Vercel/GitHub Actions), introduces envFilePath, envContents, and config, and centralizes env parsing with file/process fallbacks.
Type definitions update
packages/database/types/dbDotEnv.d.ts
Changes envContents return type to Record<string, string>. Other declarations unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Node (build/start)
  participant NextCfg as apps/website/next.config.ts
  participant Env as @repo/database/dbDotEnv
  participant Proc as process.env

  Dev->>NextCfg: import next.config.ts
  NextCfg->>Env: envContents()
  Note over Env: Determine variant, load from file or process
  Env-->>NextCfg: Map<string,string>
  loop For each [k,v]
    NextCfg->>Proc: if v truthy, set Proc[k]=v
  end
  NextCfg-->>Dev: Export NextConfig
Loading
sequenceDiagram
  autonumber
  actor Runtime as Node/CI/Browser
  participant DBEnv as packages/database/src/dbDotEnv.js
  participant FS as fs
  participant Proc as process.env

  Runtime->>DBEnv: envContents()
  DBEnv->>DBEnv: getVariant()
  alt CI (Vercel/GitHub) with SUPABASE vars
    DBEnv->>DBEnv: variant = implicit
  else Missing required vars in CI
    DBEnv->>DBEnv: variant = none
  else Local/branch/production flags
    DBEnv->>DBEnv: resolve variant
  end
  DBEnv->>DBEnv: envFilePath(variant)
  alt Path exists
    DBEnv->>FS: read .env*
    DBEnv-->>Runtime: parse to map
  else No file
    DBEnv->>Proc: read existing vars
    DBEnv-->>Runtime: map from Proc
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


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

@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 (1)
packages/database/src/dbDotEnv.js (1)

64-75: Sanitize undefined values before returning to honor the d.ts (or relax the d.ts as proposed).

When no env file is present, the fallback can include undefineds. Filter to return only string values.

 export const envContents = () => {
   const path = envFilePath();
-  if (!path)
-    // Fallback to process.env when running in production environments
-    return {
-      SUPABASE_URL: process.env.SUPABASE_URL,
-      SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY,
-      NEXT_API_ROOT: process.env.NEXT_API_ROOT,
-    };
-  const data = readFileSync(path, "utf8");
-  return dotenv.parse(data);
+  if (!path) {
+    // Fallback to process.env when running in production environments
+    const raw = {
+      SUPABASE_URL: process.env.SUPABASE_URL,
+      SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY,
+      NEXT_API_ROOT: process.env.NEXT_API_ROOT,
+    };
+    return Object.fromEntries(
+      Object.entries(raw).filter(([, v]) => v != null && v !== ""),
+    );
+  }
+  const data = readFileSync(path, "utf8");
+  return dotenv.parse(data);
 };
🧹 Nitpick comments (4)
packages/database/src/dbDotEnv.js (4)

6-12: Harden root discovery to avoid infinite loop on atypical layouts.

If “database” isn’t found in the path, dirname('/') === '/' will spin forever. Guard and error out.

-const findRoot = () => {
-  let dir = fileURLToPath(import.meta.url);
-  while (basename(dir) !== "database") {
-    dir = dirname(dir);
-  }
-  return dir;
-};
+const findRoot = () => {
+  // start from the directory containing this file
+  let dir = dirname(fileURLToPath(import.meta.url));
+  while (basename(dir) !== "database") {
+    const parent = dirname(dir);
+    if (parent === dir) {
+      throw new Error('Could not locate "database" root from: ' + dir);
+    }
+    dir = parent;
+  }
+  return dir;
+};

15-23: Avoid ReferenceError in browser contexts when accessing process/argv.

The comment says this may run in browser or node. Accessing process or process.argv can crash when process is undefined. Guard it.

-  const processHasVars =
-    !!process.env["SUPABASE_URL"] && !!process.env["SUPABASE_ANON_KEY"];
-  const useDbArgPos = (process.argv || []).indexOf("--use-db");
-  let variant =
-    useDbArgPos > 0
-      ? process.argv[useDbArgPos + 1]
-      : process.env["SUPABASE_USE_DB"];
+  const env = typeof process !== "undefined" && process.env ? process.env : {};
+  const argv =
+    typeof process !== "undefined" && Array.isArray(process.argv)
+      ? process.argv
+      : [];
+  const processHasVars = !!env["SUPABASE_URL"] && !!env["SUPABASE_ANON_KEY"];
+  const useDbArgPos = argv.indexOf("--use-db");
+  let variant =
+    useDbArgPos > -1 ? argv[useDbArgPos + 1] : env["SUPABASE_USE_DB"];

57-63: Treat “all” as a non-file variant (avoid useless FS checks).

“all” is tooling-oriented; no corresponding .env file should be loaded.

-  if (variant === "implicit" || variant === "none") return null;
+  if (variant === "implicit" || variant === "none" || variant === "all")
+    return null;

79-84: Consider delegating to dotenv with explicit override behavior.

If you prefer not to clobber existing env, set override: false (explicit) to mirror Next/Dotenv expectations.

-  if (path) dotenv.config({ path });
+  if (path) dotenv.config({ path, override: false });
📜 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
  • 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 8072bca and 8b5a549.

📒 Files selected for processing (3)
  • apps/website/next.config.ts (1 hunks)
  • packages/database/src/dbDotEnv.js (1 hunks)
  • packages/database/types/dbDotEnv.d.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: maparent
PR: DiscourseGraphs/discourse-graph#0
File: :0-0
Timestamp: 2025-07-22T01:50:20.253Z
Learning: In packages/database/scripts/create_env.ts, the Vercel CLI integration uses both vercel/sdk for deployment queries and vercel CLI for environment variable pulling, with support for different variants (local, branch, production, all) and proper team/project configuration with discourse-graphs defaults.
📚 Learning: 2025-07-22T01:50:20.253Z
Learnt from: maparent
PR: DiscourseGraphs/discourse-graph#0
File: :0-0
Timestamp: 2025-07-22T01:50:20.253Z
Learning: In packages/database/scripts/create_env.ts, the Vercel CLI integration uses both vercel/sdk for deployment queries and vercel CLI for environment variable pulling, with support for different variants (local, branch, production, all) and proper team/project configuration with discourse-graphs defaults.

Applied to files:

  • packages/database/src/dbDotEnv.js

@maparent
Copy link
Collaborator Author

@CodeRabbit this will not be used in a browser environment after all, removing that comment and not implementing the suggested changes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 31, 2025

Tip

For best results, initiate chat on the files or code changes.

@maparent Understood! Thank you for the clarification. Since this code is intended for Node.js environments only, the browser compatibility considerations are indeed unnecessary. This simplifies the implementation and removes the need for browser-specific handling.


✏️ Learnings added
Learnt from: maparent
URL: https://github.com/DiscourseGraphs/discourse-graph/pull/400

Timestamp: 2025-08-31T17:38:52.730Z
Learning: The dbDotEnv functionality in packages/database/src/dbDotEnv.js is designed for Node.js environments only and will not be used in browser contexts.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@maparent maparent requested a review from mdroidian August 31, 2025 17:42
@mdroidian mdroidian merged commit 82f0e22 into main Aug 31, 2025
4 checks passed
@mdroidian mdroidian deleted the eng-813-repair-dbDotEnv branch August 31, 2025 21:45
@github-project-automation github-project-automation bot moved this to Done in General Aug 31, 2025
@@ -1,27 +1,55 @@
import { readFileSync, existsSync } from "node:fs";
Copy link
Contributor

Choose a reason for hiding this comment

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

@maparent turbo dev is now failing at this line

image

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Ouch. Works for me, and in deployment so really puzzled. Let's review your setup first thing tomorrow.

@mdroidian
Copy link
Contributor

Context: I noticed failure of cucumber-js to load dbDotEnv.

Is this planned to be fixed in another ticket then? It is still erroring for me.
image

@mdroidian
Copy link
Contributor

mdroidian commented Aug 31, 2025

That led to the first step below, but when testing that I found out about other issues with vercel functions.

What "other issues with vercel funcions" did you find out about? Could you give some examples?

@maparent
Copy link
Collaborator Author

maparent commented Sep 1, 2025

Issues with vercel functions: They could not connect to the database when expected to do so. This was just not exercised much, so we did not notice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants