Skip to main content
This page provides a comprehensive reference for all environment variables used in KeyBox’s backend and frontend applications.

Backend Environment Variables

Configure these variables in apps/server/.env

Required Variables

# MongoDB Connection
MONGO_URI=mongodb://localhost:27017/keyboxDB

# Server Port
PORT=5000

# JWT Secret for Token Signing
JWT_SECRET=your_jwt_secret_key_min_32_chars

# License Key Encryption Secret
LICENSE_SECRET_KEY=your_license_secret_key_min_32_chars

# Frontend URL for CORS and OAuth Redirects
FRONTEND_URL=http://localhost:3000

MongoDB Configuration

Type: String (Required)MongoDB connection string for the KeyBox database.Development:
MONGO_URI=mongodb://localhost:27017/keyboxDB
Production (MongoDB Atlas):
MONGO_URI=mongodb+srv://username:[email protected]/keyboxDB?retryWrites=true&w=majority
Docker:
MONGO_URI=mongodb://mongo:27017/keyboxDB
The database name keyboxDB can be customized to any name you prefer.
Connection Options:
  • Server selection timeout is set to 5000ms in the code
  • The application will exit if MongoDB connection fails
  • Mongoose will create collections automatically

Authentication & Security

Type: String (Required)Secret key for signing and verifying JWT tokens used for user authentication.
JWT_SECRET=your_jwt_secret_key_min_32_chars
Security Requirements:
  • Minimum 32 characters
  • Use a cryptographically secure random string
  • Never commit this to version control
  • Change immediately if compromised
  • Use different values for dev/staging/production
Generate a secure secret:
# Using Node.js
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

# Using OpenSSL
openssl rand -hex 32
Used in:
  • src/controllers/auth.controller.ts - Login token generation
  • src/middleware/jwt.ts - Token verification
  • src/routes/googleAuth.routes.ts - OAuth callback tokens
Type: String (Optional)Secret for Express session middleware (used for OAuth flows).
SESSION_SECRET=your_session_secret_key
Default: "your-session-secret"
While optional, you should set this to a unique value in production.
Used in:
  • src/app.ts - Express session configuration
Type: String (Required)Secret key used for encrypting and validating license keys.
LICENSE_SECRET_KEY=your_very_strong_secret_key_here
Critical: This key is used to generate license keys. If you change this key, all previously generated licenses will become invalid.
Security recommendations:
  • Minimum 32 characters
  • Store securely (use secret management service)
  • Backup this value before rotating
  • Use same value across all environments handling same licenses

Google OAuth Configuration

Type: String (Required for OAuth)Google OAuth 2.0 Client ID from Google Cloud Console.
GOOGLE_CLIENT_ID=123456789-abcdefghijklmnop.apps.googleusercontent.com
How to obtain:
  1. Go to Google Cloud Console
  2. Create or select a project
  3. Enable Google+ API
  4. Go to Credentials → Create Credentials → OAuth 2.0 Client ID
  5. Set application type to “Web application”
  6. Copy the Client ID
Used in:
  • src/config/googleStrategy.ts - Passport Google OAuth strategy
Type: String (Required for OAuth)Google OAuth 2.0 Client Secret from Google Cloud Console.
GOOGLE_CLIENT_SECRET=GOCSPX-abc123def456
Keep this secret secure. Never expose it in client-side code or commit to version control.
Used in:
  • src/config/googleStrategy.ts - Passport Google OAuth strategy
Type: String (Required for OAuth)Callback URL for Google OAuth redirects.
# Development
GOOGLE_CALLBACK_URL=http://localhost:5000/auth/google/callback

# Production
GOOGLE_CALLBACK_URL=https://api.yourdomain.com/auth/google/callback
This URL must be registered in Google Cloud Console under “Authorized redirect URIs”.
Used in:
  • src/config/googleStrategy.ts - OAuth callback configuration

Server Configuration

Type: Number (Optional)Port number the server listens on.
PORT=5000
Default: 8000Common values:
  • Development: 5000 or 8000
  • Production: 80 (HTTP) or 443 (HTTPS)
  • Cloud platforms often set this automatically
Used in:
  • src/server.ts - Server startup
Type: String (Required)URL of the frontend application for CORS and OAuth redirects.
# Development
FRONTEND_URL=http://localhost:3000

# Production
FRONTEND_URL=https://yourdomain.com
Used in:
  • src/routes/googleAuth.routes.ts - OAuth success redirects
  • CORS configuration (currently set to *, should be restricted in production)
In production, update src/app.ts to use this variable for CORS instead of *:
app.use(cors({
  origin: process.env.FRONTEND_URL,
  credentials: true,
}));

Redis Configuration

Type: String (Optional)Password for Redis authentication.
REDIS_PASSWORD=your_redis_password
Note: The Redis host and port are currently hardcoded in src/lib/redis.ts:
  • Host: redis-10357.c212.ap-south-1-1.ec2.cloud.redislabs.com
  • Port: 10357
To make these configurable, add environment variables:
REDIS_HOST=your-redis-host.com
REDIS_PORT=6379
REDIS_PASSWORD=your_password
Used in:
  • src/lib/redis.ts - Redis client configuration

Optional Configuration

Type: String (Optional)Environment mode for the application.
NODE_ENV=production
Values:
  • development - Development mode
  • test - Testing mode (disables certain middleware)
  • production - Production mode
Effects:
  • Controls database middleware in src/app.ts
  • Affects MongoDB transactions in src/controllers/project.controller.ts
  • Changes logging behavior
Used in:
  • src/app.ts - Conditional middleware loading
  • src/tests/setup.ts - Test environment configuration

Frontend Environment Variables

Configure these variables in apps/web/.env.local

Required Variables

Type: String (Required)Base URL of the backend API server.
# Development
NEXT_PUBLIC_API_URL=http://localhost:5000/

# Production
NEXT_PUBLIC_API_URL=https://api.yourdomain.com/
Important:
  • Must include the NEXT_PUBLIC_ prefix to be accessible in the browser
  • Must end with a trailing slash /
  • Must be set at build time (not runtime)
Used in:
  • lib/api.ts - Axios base URL configuration
  • app/api/axiosInstance.ts - Alternative Axios instance
  • OAuth redirect URLs in login/signup pages
Environment-specific setup:
# .env.local (development)
NEXT_PUBLIC_API_URL=http://localhost:5000/

# .env.production (production)
NEXT_PUBLIC_API_URL=https://api.yourdomain.com/

# .env.test (testing)
NEXT_PUBLIC_API_URL=http://localhost:5001/

Environment Files

Backend Files

apps/server/
├── .env                 # Your local configuration (gitignored)
├── .env.example         # Template with dummy values (committed)
├── .env.development     # Development-specific (optional)
├── .env.production      # Production-specific (optional)
└── .env.test            # Test environment (optional)

Frontend Files

apps/web/
├── .env.local           # Your local configuration (gitignored)
├── .env.development     # Development-specific (optional)
├── .env.production      # Production-specific (optional)
└── .env.test            # Test environment (optional)

Environment Variable Priority

Next.js loads environment variables in this order (highest priority first):
  1. .env.$(NODE_ENV).local
  2. .env.local (not loaded when NODE_ENV=test)
  3. .env.$(NODE_ENV)
  4. .env

Security Best Practices

Critical security guidelines:
  1. Never commit secrets to Git
    • Add .env to .gitignore
    • Use .env.example with dummy values
  2. Use strong, unique secrets
    • Minimum 32 characters for JWT/session secrets
    • Use cryptographically random values
  3. Rotate secrets regularly
    • Change secrets every 90 days
    • Rotate immediately if compromised
  4. Use different values per environment
    • Dev, staging, and production should have unique secrets
  5. Use secret management services
    • AWS Secrets Manager
    • HashiCorp Vault
    • Vercel Environment Variables
    • Railway/Render environment management
  6. Limit access
    • Only grant access to team members who need it
    • Use role-based access control
  7. Backup critical secrets
    • Especially LICENSE_SECRET_KEY
    • Store securely (password manager, vault)

Deployment Platform Configuration

Vercel

  1. Go to Project Settings → Environment Variables
  2. Add each variable with its value
  3. Select environments (Production, Preview, Development)
  4. Redeploy to apply changes

Railway/Render

  1. Go to your service/app settings
  2. Navigate to Environment Variables section
  3. Add variables as key-value pairs
  4. Save and redeploy

Docker

Pass environment variables via: Docker run:
docker run --env-file .env keybox-server
Docker Compose:
services:
  backend:
    image: keybox-server
    env_file:
      - .env
    environment:
      - NODE_ENV=production

Kubernetes

ConfigMap for non-sensitive data:
apiVersion: v1
kind: ConfigMap
metadata:
  name: keybox-config
data:
  PORT: "5000"
  FRONTEND_URL: "https://keybox.example.com"
Secret for sensitive data:
apiVersion: v1
kind: Secret
metadata:
  name: keybox-secrets
type: Opaque
stringData:
  JWT_SECRET: "your_jwt_secret"
  MONGO_URI: "mongodb://..."

Validation

Add runtime validation for critical environment variables:
// validate-env.ts
const requiredEnvVars = [
  'MONGO_URI',
  'JWT_SECRET',
  'LICENSE_SECRET_KEY',
  'FRONTEND_URL',
];

for (const envVar of requiredEnvVars) {
  if (!process.env[envVar]) {
    throw new Error(`Missing required environment variable: ${envVar}`);
  }
}

console.log('Environment validation passed');

Troubleshooting

Variables Not Loading

Backend:
  • Ensure dotenv is imported before other modules
  • Check file is named exactly .env
  • Verify file is in correct directory (apps/server/)
  • Restart the server after changes
Frontend:
  • Ensure variable has NEXT_PUBLIC_ prefix (for client-side)
  • Rebuild the application (pnpm build)
  • Clear Next.js cache: rm -rf .next
  • Restart dev server

OAuth Not Working

  • Verify all Google OAuth variables are set
  • Check callback URL matches Google Console
  • Ensure URLs don’t have typos or extra spaces
  • Verify Google Cloud project has OAuth consent configured

MongoDB Connection Fails

  • Test connection string with mongosh
  • Check IP whitelist (MongoDB Atlas)
  • Verify credentials are correct
  • Ensure database name is included in URI

Next Steps

Build docs developers (and LLMs) love