Skip to content

Add centralized environment variable validation during application startup#60

Merged
rishabhx29 merged 1 commit into
rishabhx29:mainfrom
om-dev007:fix/issue-54-centralized-env
Jun 29, 2026
Merged

Add centralized environment variable validation during application startup#60
rishabhx29 merged 1 commit into
rishabhx29:mainfrom
om-dev007:fix/issue-54-centralized-env

Conversation

@om-dev007

@om-dev007 om-dev007 commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

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

  • Added a dedicated config/env.ts module.
  • Defined a list of required environment variables.
  • Added startup validation to ensure all required variables are present.
  • Configured the application to fail fast with a descriptive error when a required environment variable is missing.
  • Exported validated configuration values through a centralized config object.
  • Updated application startup to use the centralized configuration instead of scattered process.env access where applicable.
  • Removed redundant environment variable validation from the server entry file.

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

  • Fails fast on missing configuration.
  • Improves deployment reliability.
  • Centralizes configuration management.
  • Reduces the risk of runtime failures caused by missing environment variables.
  • Provides a solid foundation for future enhancements such as schema validation, type checking, and default values.

Testing

  • Verified that the application starts successfully when all required environment variables are provided.
  • Verified that the application exits with a descriptive error message when a required environment variable is missing.
  • Confirmed that existing functionality remains unchanged when the required configuration is present.

closes #54

Summary by CodeRabbit

  • New Features
    • Added centralized runtime configuration loading with validation, helping the app fail fast when required settings are missing.
  • Bug Fixes
    • Updated server, authentication, chat, and migration flows to use the shared configuration source, improving consistency for sign-in, API access, and startup behavior.

@vercel

vercel Bot commented Jun 28, 2026

Copy link
Copy Markdown

@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.

@coderabbitai

coderabbitai Bot commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A new backend/src/config/env.ts module is introduced that loads .env via dotenv, validates a fixed list of required environment variables at startup, and exports a typed config object. All backend files that previously accessed process.env directly are updated to import and use this config object instead.

Changes

Centralized Environment Configuration

Layer / File(s) Summary
env.ts config module
backend/src/config/env.ts
New module that calls dotenv.config(), iterates over required var names (PORT, MONGO_URI, JWT_SECRET, GOOGLE_CLIENT_ID, CLIENT_URL, GEMINI_API_KEY), throws on any missing key, and exports a populated config object.
Consumer migration
backend/src/server.ts, backend/src/middleware/authMiddleware.ts, backend/src/controllers/authController.ts, backend/src/controllers/chatController.ts, backend/src/scripts/migrate_users.ts
Each file adds an import of config from ../config/env and replaces all process.env.* accesses with the corresponding config.* field. The removed per-file JWT_SECRET check in server.ts is now covered by the centralized validation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 No more scattered process.env hops,
One config burrow where the checking stops.
Missing keys? We throw before the run,
Fail fast, fail clear — the bunny way done.
All consumers now know where to go,
A tidy warren, top to toe! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: centralized environment validation at startup.
Linked Issues check ✅ Passed [#54] The PR adds startup-time env validation, a shared config module, fail-fast errors, and updates call sites to use validated values.
Out of Scope Changes check ✅ Passed The changes stay within environment configuration centralization and usage updates, with no clear unrelated additions.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@om-dev007

Copy link
Copy Markdown
Contributor Author

@Rishabhworkspace please review this pr

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 676d113 and 15bd201.

📒 Files selected for processing (6)
  • backend/src/config/env.ts
  • backend/src/controllers/authController.ts
  • backend/src/controllers/chatController.ts
  • backend/src/middleware/authMiddleware.ts
  • backend/src/scripts/migrate_users.ts
  • backend/src/server.ts

Comment thread backend/src/config/env.ts
Comment on lines +13 to +26
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Comment on lines +4 to +8
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

@vercel

vercel Bot commented Jun 29, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
algo-forge-2-0 Ready Ready Preview, Comment Jun 29, 2026 6:22am

@rishabhx29 rishabhx29 added enhancement New feature or request SSoC26 Medium labels Jun 29, 2026
@rishabhx29 rishabhx29 merged commit 8e41fd8 into rishabhx29:main Jun 29, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request Medium SSoC26

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Centralized Environment Variable Validation During Application Startup

2 participants