Add centralized environment variable validation during application startup#60
Conversation
… across controllers and middleware
|
@om-dev007 is attempting to deploy a commit to the rishabhjtripathi2903-3434's projects Team on Vercel. A member of the Team first needs to authorize it. |
📝 WalkthroughWalkthroughA new ChangesCentralized Environment Configuration
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
@Rishabhworkspace please review this pr |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@backend/src/config/env.ts`:
- Around line 13-26: The env validation in config env.ts only checks truthiness,
so whitespace-only values can still slip through and the exported config is
rebuilt from raw process.env afterward. Update the requiredEnv validation flow
to validate each value once with a helper that rejects empty or trim-only
strings, then have config export those validated/materialized values instead of
re-reading process.env. Keep the fix centered around requiredEnv and the config
object so the fail-fast behavior is enforced consistently.
In `@backend/src/scripts/migrate_users.ts`:
- Around line 4-8: The script initializes dotenv after importing config, so
MONGO_URI is validated before the .env file is loaded. In migrate_users.ts, move
the dotenv bootstrap that uses path.join(__dirname, '../../.env') ahead of the
config import, or rely on env.ts to load the correct file itself. Make sure the
import order in migrate_users.ts allows config.MONGO_URI to be resolved only
after environment variables are available.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 8e6759a0-107d-4119-addb-d18946f6f594
📒 Files selected for processing (6)
backend/src/config/env.tsbackend/src/controllers/authController.tsbackend/src/controllers/chatController.tsbackend/src/middleware/authMiddleware.tsbackend/src/scripts/migrate_users.tsbackend/src/server.ts
| requiredEnv.forEach((key) => { | ||
| if(!process.env[key]) { | ||
| throw new Error(`Missing required environment variable: ${key}`); | ||
| } | ||
| }) | ||
|
|
||
| export const config = { | ||
| PORT: process.env.PORT, | ||
| MONGO_URI: process.env.MONGO_URI, | ||
| JWT_SECRET: process.env.JWT_SECRET, | ||
| GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID, | ||
| CLIENT_URL: process.env.CLIENT_URL, | ||
| GEMINI_API_KEY: process.env.GEMINI_API_KEY | ||
| } No newline at end of file |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Materialize validated values instead of re-reading raw process.env.
This only checks truthiness, so whitespace-only values still pass startup, and config is rebuilt from raw env strings afterward. That misses the “misconfigured” part of the fail-fast contract. Validate each value once with a helper (for example, reject value.trim() === '') and export those validated results from config.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@backend/src/config/env.ts` around lines 13 - 26, The env validation in config
env.ts only checks truthiness, so whitespace-only values can still slip through
and the exported config is rebuilt from raw process.env afterward. Update the
requiredEnv validation flow to validate each value once with a helper that
rejects empty or trim-only strings, then have config export those
validated/materialized values instead of re-reading process.env. Keep the fix
centered around requiredEnv and the config object so the fail-fast behavior is
enforced consistently.
| import { config } from '../config/env'; | ||
|
|
||
| dotenv.config({ path: path.join(__dirname, '../../.env') }); | ||
|
|
||
| const uri = process.env.MONGO_URI as string; | ||
| const uri = config.MONGO_URI as string; |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== file list ==\n'
git ls-files backend/src/scripts/migrate_users.ts backend/src/config/env.ts
printf '\n== outlines ==\n'
ast-grep outline backend/src/scripts/migrate_users.ts --view expanded || true
ast-grep outline backend/src/config/env.ts --view expanded || true
printf '\n== migrate_users.ts ==\n'
cat -n backend/src/scripts/migrate_users.ts | sed -n '1,120p'
printf '\n== env.ts ==\n'
cat -n backend/src/config/env.ts | sed -n '1,220p'Repository: Rishabhworkspace/AlgoForge
Length of output: 7399
Load dotenv before importing config.
backend/src/config/env.ts calls dotenv.config() and validates process.env at import time, so the dotenv.config({ path: path.join(__dirname, '../../.env') }) here runs too late to affect config.MONGO_URI. If this script depends on ../../.env, it can fail during module initialization; move dotenv bootstrapping above the config import or let the config module own the path resolution.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@backend/src/scripts/migrate_users.ts` around lines 4 - 8, The script
initializes dotenv after importing config, so MONGO_URI is validated before the
.env file is loaded. In migrate_users.ts, move the dotenv bootstrap that uses
path.join(__dirname, '../../.env') ahead of the config import, or rely on env.ts
to load the correct file itself. Make sure the import order in migrate_users.ts
allows config.MONGO_URI to be resolved only after environment variables are
available.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Description
Summary
This PR introduces a centralized environment configuration module that validates required environment variables during application startup and exports validated configuration values for use throughout the application.
Changes Made
config/env.tsmodule.configobject.process.envaccess where applicable.Why
Previously, environment variables were accessed directly throughout the application without validating their existence during startup. Missing or misconfigured variables could lead to runtime failures that were difficult to diagnose.
Centralizing validation ensures configuration issues are detected immediately, making deployments more reliable and easier to debug.
Benefits
Testing
closes #54
Summary by CodeRabbit