Skip to content

removed duplicate code and added zod validation for env variables#1

Open
debadithyaxd wants to merge 2 commits intosamarth3301:mainfrom
debadithyaxd:main
Open

removed duplicate code and added zod validation for env variables#1
debadithyaxd wants to merge 2 commits intosamarth3301:mainfrom
debadithyaxd:main

Conversation

@debadithyaxd
Copy link
Copy Markdown

@debadithyaxd debadithyaxd commented Mar 11, 2026

Implemented Zod environment validation, inspired by samarth3301/graphQL-boilerplate

Summary by CodeRabbit

  • Refactor
    • Configuration validation is now schema-driven: the app emits clear errors and stops startup when required environment values are missing or invalid.
    • Logging output and file/console transports use a standardized format for consistent timestamps and message structure across environments.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 11, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bb40f852-fcf0-42b0-b18c-8bb6c50f6b4d

📥 Commits

Reviewing files that changed from the base of the PR and between 392a830 and cc1899d.

📒 Files selected for processing (1)
  • src/config/index.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/config/index.ts

📝 Walkthrough

Walkthrough

Replaced dotenv-based env loading with a Zod-based configSchema that validates and supplies defaults; consolidated Winston logger formatting to a single timestamped format; changed module-side initialization to import a preload module instead of the previous alias setup.

Changes

Cohort / File(s) Summary
Configuration Validation
src/config/index.ts
Removed manual Config interface and dotenv parsing; added exported configSchema (Zod) and non-exported type Config = z.infer<typeof configSchema>; assemble rawData from process.env, safeParse, log errors and process.exit on invalid input; export default validated config.
Logger Formatting
src/config/logger.ts
Reworked logger format to a single loggerFormat using winston.format.timestamp() + printf; applied loggerFormat across console, DailyRotateFile, and dev file transports; normalized string quoting and minor formatting tweaks.
Module Initialization
src/index.ts
Replaced import that set up module aliases with an import of a preload module to change side-effect initialization at startup.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I nibble at schemas in the night,
Zod carrots keep my configs right,
Timestamps drum in logs aglow,
A preload hop, and systems go,
Hooray for tidy code—let's hop! 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly aligns with the main changes: implementing Zod validation for environment variables in src/config/index.ts and removing duplicate code across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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: 2

🧹 Nitpick comments (2)
src/config/logger.ts (1)

75-80: Consider stronger typing for addRequestId options.

The opts parameter is typed as any. A more explicit type would improve type safety and IDE support.

✨ Suggested improvement
-export const addRequestId = winston.format((info, opts: any) => {
+export const addRequestId = winston.format((info, opts: { requestId?: string }) => {
   if (opts.requestId) {
     info.requestId = opts.requestId;
   }
   return info;
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/config/logger.ts` around lines 75 - 80, The addRequestId format currently
types the opts parameter as any; replace that with a concrete interface (e.g.,
RequestIdFormatOptions { requestId?: string }) and use the proper Winston format
callback/type for the function signature so opts is typed as that interface (or
as Winston's FormatOptions generic if available); update the export of
addRequestId to accept the new typed opts to improve type safety and IDE
autocompletion while preserving the existing behavior where info.requestId is
set when opts.requestId is present.
src/config/index.ts (1)

27-30: Use structured error formatting for better debugging.

parsed.error.message provides a less readable output. Consider using parsed.error.format() or parsed.error.flatten() for clearer validation error messages.

✨ Suggested improvement
 if(!parsed.success){
   console.error("❌ Invalid or missing environment variables:");
-  console.log(parsed.error.message);
+  console.error(parsed.error.format());
   process.exit(1)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/config/index.ts` around lines 27 - 30, The environment validation branch
that checks parsed.success logs parsed.error.message which is hard to read;
update the parsed.success false branch (the block that currently calls
console.error("❌ Invalid or missing environment variables:") and
console.log(parsed.error.message)) to call parsed.error.format() or
parsed.error.flatten() and log that structured output (e.g., console.error with
the formatted/flattened result) before calling process.exit(1) so validation
errors are readable; ensure you reference the existing parsed variable and
parsed.error object in the revised logging.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/config/index.ts`:
- Line 13: Remove the insecure default JWT secret by deleting the
.default('default-secret-change-in-production') on the config schema property
named "secret" so the Zod schema requires an explicit value; update the schema
entry (the "secret" field in src/config/index.ts) to be a required
z.string().min(32) and ensure any code that reads this config handles the case
where the environment variable is missing (fail fast with a clear error) rather
than relying on a fallback.
- Around line 3-23: The configSchema currently defines nested objects (redis,
jwt, rateLimit) but you call configSchema.safeParse(process.env); transform
either the schema or the input: update configSchema to a flat schema using
env-style keys (e.g., REDIS_HOST, REDIS_PORT, JWT_SECRET, RATE_LIMIT_WINDOW_MS,
RATE_LIMIT_MAX_REQUESTS) and reference those env names in the schema, or before
calling configSchema.safeParse(map), build a nested object from process.env
(e.g., construct redis: { host: process.env.REDIS_HOST, port:
Number(process.env.REDIS_PORT), db: Number(process.env.REDIS_DB) }, jwt: {
secret: process.env.JWT_SECRET, expiresIn: process.env.JWT_EXPIRES_IN },
rateLimit: { windowMs: Number(process.env.RATE_LIMIT_WINDOW_MS), maxRequests:
Number(process.env.RATE_LIMIT_MAX_REQUESTS) }) so the parsed input matches
configSchema; adjust usages of configSchema and the parse call accordingly.

---

Nitpick comments:
In `@src/config/index.ts`:
- Around line 27-30: The environment validation branch that checks
parsed.success logs parsed.error.message which is hard to read; update the
parsed.success false branch (the block that currently calls console.error("❌
Invalid or missing environment variables:") and
console.log(parsed.error.message)) to call parsed.error.format() or
parsed.error.flatten() and log that structured output (e.g., console.error with
the formatted/flattened result) before calling process.exit(1) so validation
errors are readable; ensure you reference the existing parsed variable and
parsed.error object in the revised logging.

In `@src/config/logger.ts`:
- Around line 75-80: The addRequestId format currently types the opts parameter
as any; replace that with a concrete interface (e.g., RequestIdFormatOptions {
requestId?: string }) and use the proper Winston format callback/type for the
function signature so opts is typed as that interface (or as Winston's
FormatOptions generic if available); update the export of addRequestId to accept
the new typed opts to improve type safety and IDE autocompletion while
preserving the existing behavior where info.requestId is set when opts.requestId
is present.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 15cdf20a-f828-489a-a3d0-2de823482b5b

📥 Commits

Reviewing files that changed from the base of the PR and between f0cce5d and 392a830.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • src/config/index.ts
  • src/config/logger.ts
  • src/config/preload.ts
  • src/index.ts

@debadithyaxd debadithyaxd marked this pull request as draft March 11, 2026 19:18
@debadithyaxd debadithyaxd marked this pull request as ready for review March 12, 2026 00:40
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