-
Notifications
You must be signed in to change notification settings - Fork 381
fix(nextjs): Use nodeFsOrThrow instead of directly importing fs module in keyless-telemetry #6555
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(nextjs): Use nodeFsOrThrow instead of directly importing fs module in keyless-telemetry #6555
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughUpdates keyless-telemetry.ts to replace direct fs.promises usage with nodeFsOrThrow from ./fs/utils. Adds a canUseKeyless guard in tryMarkTelemetryEventAsFired: if canUseKeyless is false, returns false immediately; otherwise ensures the telemetry flag directory exists and attempts an atomic write (flag 'wx') of a JSON payload { firedAt, event } to the flag file. EEXIST results in false; other errors are logged and return false. detectKeylessEnvDrift remains functionally the same but now uses the filesystem abstraction. A changeset file registering the import migration was added. Estimated code review effort🎯 2 (Simple) | ⏱️ ~7 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. 📜 Recent review detailsConfiguration used: CodeRabbit UI 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (6)
packages/nextjs/src/server/keyless-telemetry.ts (6)
6-6
: Prefer dynamic import for nodeFsOrThrow to avoid pulling Node-only code into non-Node bundlesThis aligns with “Use dynamic imports for optional features” and reduces the risk of bundlers including Node-only code in edge/client targets.
Apply this diff to drop the static import:
-import { nodeFsOrThrow } from './fs/utils';
46-63
: Good fix; simplify control flow and dynamically import fs utilities inside the guarded branch
- Use early return to reduce nesting.
- Dynamically import fs utilities only when needed (further guards edge/client bundles).
- Keep atomic create with 'wx' and return semantics unchanged.
try { - if (canUseKeyless) { - const { mkdir, writeFile } = nodeFsOrThrow(); - const flagFilePath = getTelemetryFlagFilePath(); - const flagDirectory = dirname(flagFilePath); - - // Ensure the directory exists before attempting to write the file - await mkdir(flagDirectory, { recursive: true }); - - const flagData = { - firedAt: new Date().toISOString(), - event: EVENT_KEYLESS_ENV_DRIFT_DETECTED, - }; - await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx' }); - return true; - } else { - return false; - } + if (!canUseKeyless) { + return false; + } + const { nodeFsOrThrow } = await import('./fs/utils'); + const { mkdir, writeFile } = nodeFsOrThrow(); + const flagFilePath = getTelemetryFlagFilePath(); + const flagDirectory = dirname(flagFilePath); + + // Ensure the directory exists before attempting to write the file + await mkdir(flagDirectory, { recursive: true }); + + const flagData = { + firedAt: new Date().toISOString(), + event: EVENT_KEYLESS_ENV_DRIFT_DETECTED, + }; + await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx', mode: 0o600 }); + return true;
58-58
: Harden file permissions for the flag fileThe flag contents aren’t sensitive, but it’s inexpensive to set restrictive permissions on creation to avoid permissive defaults (umask-dependent).
If you don’t adopt the bigger refactor above, minimally update the write options:
- await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx' }); + await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx', mode: 0o600 });
63-69
: Tighten error typing for EEXIST checkPrefer using Node’s ErrnoException type for clearer intent and better editor support.
- } catch (error: unknown) { - if ((error as { code?: string })?.code === 'EEXIST') { + } catch (error: unknown) { + const err = error as NodeJS.ErrnoException; + if (err?.code === 'EEXIST') { return false; } console.warn('Failed to create telemetry flag file:', error); return false; }
175-178
: Avoid duplication: reuse EVENT_SAMPLING_RATE for client telemetry configYou already have EVENT_SAMPLING_RATE = 1; reuse it to keep sampling consistent and prevent drift if the constant changes later.
- telemetry: { - samplingRate: 1, - }, + telemetry: { + samplingRate: EVENT_SAMPLING_RATE, + },
44-60
: Add unit tests for the new fs abstraction and gating behaviorGiven the bugfix nature of this PR, please add tests that cover:
- returns false when canUseKeyless is false (and doesn’t attempt FS ops)
- creates directory and file when allowed, returns true on first attempt
- returns false on EEXIST without logging an error
- logs and returns false on other fs errors
I can provide Jest tests that mock ./fs/utils and the feature flag if helpful.
Would you like me to scaffold these tests with Jest + ts-jest and module mocks for nodeFsOrThrow and feature-flags?
📜 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.
📒 Files selected for processing (1)
packages/nextjs/src/server/keyless-telemetry.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/nextjs/src/server/keyless-telemetry.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/nextjs/src/server/keyless-telemetry.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/nextjs/src/server/keyless-telemetry.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/nextjs/src/server/keyless-telemetry.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/nextjs/src/server/keyless-telemetry.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/nextjs/src/server/keyless-telemetry.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/nextjs/src/server/keyless-telemetry.ts
🧬 Code Graph Analysis (1)
packages/nextjs/src/server/keyless-telemetry.ts (2)
packages/nextjs/src/utils/feature-flags.ts (1)
canUseKeyless
(12-12)packages/nextjs/src/server/fs/utils.ts (1)
nodeFsOrThrow
(33-33)
⏰ 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). (5)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/nextjs/src/server/keyless-telemetry.ts (1)
1-3
: Sanity check: top-level Node 'path' import in server codeThis file imports 'path' at module scope. It’s fine for Node runtimes, but if this module ever leaks into an edge/client bundle, it could break. Not blocking, but please verify bundling boundaries.
If needed, we can also lazily import 'path' inside tryMarkTelemetryEventAsFired (and inline join/dirname usage) to isolate Node-only deps.
Description
Fixes build error in
playground/nextjs
action (see here) by import fs methods withnodeFsOrThrow
rather than direct import.Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Chores