diff --git a/check-links.js b/check-links.js index 6d9d8fe..34a3a17 100644 --- a/check-links.js +++ b/check-links.js @@ -58,8 +58,30 @@ const checkLocalFile = (linkPath, filePath) => { return null; // not a local file }; +// Check if URL is a localhost URL +const isLocalhostUrl = (url) => { + try { + const urlObj = new URL(url); + const hostname = urlObj.hostname.toLowerCase(); + + // Check for localhost patterns + return hostname === 'localhost' || + hostname === '127.0.0.1' || + hostname === '0.0.0.0' || + hostname.endsWith('.localhost'); + } catch (error) { + return false; + } +}; + // Check external URL const checkExternalUrl = async (url) => { + // Check if it's a localhost URL and skip validation + if (isLocalhostUrl(url)) { + console.log(` ➡️ ${url} (localhost - skipped)`); + return true; + } + try { const response = await fetch(url, { method: 'HEAD', diff --git a/docs/deploystack/development/backend/environment-variables.mdx b/docs/deploystack/development/backend/environment-variables.mdx new file mode 100644 index 0000000..080fef6 --- /dev/null +++ b/docs/deploystack/development/backend/environment-variables.mdx @@ -0,0 +1,478 @@ +--- +title: Environment Variables +description: Complete guide to configuring and using environment variables in the DeployStack backend application for both development and production environments. +sidebar: Environment Variables +--- + +# Backend Environment Variables + +The DeployStack backend uses Node.js environment variables that work seamlessly across development and production environments. This system supports both local `.env` files for development and Docker environment variable injection for production deployments. + +## Overview + +The backend environment system consists of two main approaches: + +1. **Development Environment**: Uses `.env` files loaded via Node.js `--env-file` flag with nodemon +2. **Production Environment**: Uses Docker environment variables injected at container runtime + +This approach ensures that: +- Developers can work with standard `.env` files during development using `npm run dev` +- Production deployments can inject variables at runtime without rebuilding the application +- Environment variables are directly accessible via `process.env` throughout the Node.js application +- The same codebase works seamlessly in both environments + +## Environment Variable Types + +### Development Environment Variables + +During development, the backend loads environment variables from `.env` files using Node.js's built-in `--env-file` support: + +```bash +# .env +PORT=3000 +NODE_ENV=development +DEPLOYSTACK_FRONTEND_URL=http://localhost:5173 +COOKIE_SECRET=your-secure-cookie-secret-here +``` + +### Production Environment Variables + +In production Docker containers, variables are injected at runtime via Docker's environment variable system: + +```bash +# Docker run example +docker run -e PORT=3000 \ + -e NODE_ENV=production \ + -e DEPLOYSTACK_FRONTEND_URL="https://app.deploystack.com" \ + -e COOKIE_SECRET="your-production-cookie-secret" \ + deploystack/backend:latest +``` + +## Development Setup + +### Environment Files + +Create environment files in the `services/backend` directory: + +#### `.env` (Base Configuration) +```bash +# Server Configuration +PORT=3000 +NODE_ENV=development +HOST=localhost + +# Frontend Integration +DEPLOYSTACK_FRONTEND_URL=http://localhost:5173 + +# Security +COOKIE_SECRET=a-very-secret-and-strong-secret-for-cookies +DEPLOYSTACK_ENCRYPTION_SECRET=your-encryption-secret-here + +# Logging +LOG_LEVEL=debug + +# OAuth Configuration (optional for development) +GITHUB_CLIENT_ID=your-github-client-id +GITHUB_CLIENT_SECRET=your-github-client-secret +GITHUB_REDIRECT_URI=http://localhost:3000/api/auth/github/callback + +# Application +DEPLOYSTACK_BACKEND_VERSION=0.20.5 +``` + +#### `.env.local` (Local Overrides) +```bash +# Local development environment variables +# This file is gitignored and used for local customization +PORT=3001 +DEPLOYSTACK_FRONTEND_URL=http://localhost:5174 +LOG_LEVEL=info +``` + +### Environment File Priority + +Node.js with `--env-file` loads environment variables in this order: + +1. System environment variables (highest priority) +2. `.env` file variables +3. Default values in code (lowest priority) + +**Note**: Unlike some frameworks, Node.js `--env-file` doesn't support multiple env files by default. Use `.env.local` by renaming it to `.env` for local development. + +### Development Example + +```bash +# Navigate to backend directory +cd services/backend + +# Create your local environment file +cp .env .env.local + +# Edit .env.local with your local settings +echo "PORT=3001" >> .env.local +echo "LOG_LEVEL=info" >> .env.local + +# Rename for development (or modify .env directly) +mv .env.local .env + +# Start development server +npm run dev +``` + +### Nodemon Configuration + +The development server uses nodemon with the following configuration (from `nodemon.json`): + +```json +{ + "watch": ["src"], + "ext": "ts,js,json", + "ignore": ["src/**/*.test.ts", "src/**/*.spec.ts", "tests/**/*"], + "exec": "node --env-file=.env --require ts-node/register src/index.ts", + "env": { + "NODE_ENV": "development" + }, + "delay": 1000 +} +``` + +This configuration: +- Loads environment variables from `.env` using `--env-file=.env` +- Sets `NODE_ENV=development` by default +- Watches TypeScript files for changes +- Uses ts-node for TypeScript compilation + +## Production Deployment + +### Docker Environment Variables + +The production Docker container accepts environment variables at runtime: + +```bash +# Production deployment +docker run -d -p 3000:3000 \ + -e NODE_ENV=production \ + -e PORT=3000 \ + -e DEPLOYSTACK_FRONTEND_URL="https://app.deploystack.com" \ + -e COOKIE_SECRET="your-production-secret" \ + -e DEPLOYSTACK_ENCRYPTION_SECRET="your-encryption-secret" \ + deploystack/backend:latest +``` + +### Docker Compose Example + +```yaml +version: '3.8' +services: + backend: + image: deploystack/backend:latest + ports: + - "3000:3000" + environment: + - NODE_ENV=production + - PORT=3000 + - DEPLOYSTACK_FRONTEND_URL=https://app.deploystack.com + - COOKIE_SECRET=your-production-cookie-secret + - DEPLOYSTACK_ENCRYPTION_SECRET=your-encryption-secret + - GITHUB_CLIENT_ID=your-github-client-id + - GITHUB_CLIENT_SECRET=your-github-client-secret + - GITHUB_REDIRECT_URI=https://api.deploystack.com/api/auth/github/callback + volumes: + - ./data:/app/data # For SQLite database persistence +``` + +### Dockerfile Environment Handling + +The production Dockerfile creates a default `.env` file with basic settings: + +```dockerfile +# Create a default .env file +RUN echo "NODE_ENV=production" > .env && \ + echo "PORT=3000" >> .env && \ + echo "DEPLOYSTACK_BACKEND_VERSION=${DEPLOYSTACK_BACKEND_VERSION:-$(node -e "console.log(require('./package.json').version)")}" >> .env + +# Start with env file +CMD ["node", "--env-file=.env", "dist/index.js"] +``` + +Runtime environment variables will override these defaults. + +## Using Environment Variables in Code + +### Accessing Variables + +Environment variables are directly accessible via `process.env` in Node.js: + +```typescript +// Direct access +const port = process.env.PORT || '3000' +const nodeEnv = process.env.NODE_ENV || 'development' +const frontendUrl = process.env.DEPLOYSTACK_FRONTEND_URL + +// Type-safe access with validation +function getRequiredEnv(key: string): string { + const value = process.env[key] + if (!value) { + throw new Error(`Required environment variable ${key} is not set`) + } + return value +} + +const cookieSecret = getRequiredEnv('COOKIE_SECRET') +``` + +### Server Configuration Example + +```typescript +// src/server.ts +import fastify from 'fastify' + +export const createServer = async () => { + const server = fastify({ + logger: { + level: process.env.LOG_LEVEL || 'info' + } + }) + + // Cookie configuration + await server.register(fastifyCookie, { + secret: process.env.COOKIE_SECRET || 'fallback-secret', + parseOptions: {} + }) + + // CORS configuration + const frontendUrl = process.env.DEPLOYSTACK_FRONTEND_URL + if (frontendUrl) { + await server.register(fastifyCors, { + origin: frontendUrl, + credentials: true + }) + } + + return server +} +``` + +### Database Configuration Example + +```typescript +// src/db/setup.ts +const setupDatabase = () => { + const isTestEnv = process.env.NODE_ENV === 'test' + const sqliteDbFileName = isTestEnv ? 'deploystack.test.db' : 'deploystack.db' + + const dbPath = path.join(process.cwd(), 'data', sqliteDbFileName) + + return new Database(dbPath) +} +``` + +### Plugin System Configuration + +```typescript +// src/server.ts +const isDevelopment = process.env.NODE_ENV !== 'production' +const pluginManager = new PluginManager({ + paths: [ + process.env.PLUGINS_PATH || (isDevelopment + ? path.join(process.cwd(), 'src', 'plugins') + : path.join(__dirname, 'plugins')), + ], + plugins: {} +}) +``` + +## Adding New Environment Variables + +### Step 1: Add to Environment Files + +Add the new variable to your `.env` file: + +```bash +# .env +PORT=3000 +NODE_ENV=development +DEPLOYSTACK_FRONTEND_URL=http://localhost:5173 +NEW_FEATURE_ENABLED=true +NEW_API_ENDPOINT=https://api.example.com +``` + +### Step 2: Use in Code + +Access the variable in your TypeScript code: + +```typescript +// src/config/features.ts +export const isNewFeatureEnabled = (): boolean => { + const value = process.env.NEW_FEATURE_ENABLED + return value === 'true' || value === '1' +} + +export const getApiEndpoint = (): string => { + return process.env.NEW_API_ENDPOINT || 'https://api.default.com' +} +``` + +### Step 3: Update Production Configuration + +Add the variable to your production deployment configuration: + +```bash +# Docker +docker run -e NEW_FEATURE_ENABLED=true \ + -e NEW_API_ENDPOINT=https://prod-api.example.com \ + deploystack/backend:latest +``` + +```yaml +# Docker Compose +environment: + - NEW_FEATURE_ENABLED=true + - NEW_API_ENDPOINT=https://prod-api.example.com +``` + +### Step 4: Create Type-Safe Helpers (Optional) + +For better type safety and validation: + +```typescript +// src/utils/env.ts +interface EnvironmentConfig { + port: number + nodeEnv: string + frontendUrl: string + newFeatureEnabled: boolean + newApiEndpoint: string +} + +export function getEnvironmentConfig(): EnvironmentConfig { + return { + port: parseInt(process.env.PORT || '3000', 10), + nodeEnv: process.env.NODE_ENV || 'development', + frontendUrl: process.env.DEPLOYSTACK_FRONTEND_URL || 'http://localhost:5173', + newFeatureEnabled: process.env.NEW_FEATURE_ENABLED === 'true', + newApiEndpoint: process.env.NEW_API_ENDPOINT || 'https://api.default.com' + } +} + +// Usage +import { getEnvironmentConfig } from '@/utils/env' + +const config = getEnvironmentConfig() +if (config.newFeatureEnabled) { + // Use new feature +} +``` + +## Environment Variable Naming Conventions + +### Backend Environment Variables + +- Use `SCREAMING_SNAKE_CASE` format +- Be descriptive and specific +- Group related variables with prefixes + +```bash +✅ Good +PORT=3000 +NODE_ENV=development +DEPLOYSTACK_FRONTEND_URL=http://localhost:5173 +DEPLOYSTACK_ENCRYPTION_SECRET=secret +GITHUB_CLIENT_ID=client-id +GITHUB_CLIENT_SECRET=client-secret + +❌ Bad +port=3000 # Wrong case +URL=http://localhost:5173 # Not descriptive +SECRET=secret # Too generic +``` + +### Common Patterns + +```bash +# Server Configuration +PORT=3000 +HOST=localhost +NODE_ENV=development + +# Application Specific (use DEPLOYSTACK_ prefix) +DEPLOYSTACK_FRONTEND_URL=http://localhost:5173 +DEPLOYSTACK_BACKEND_VERSION=0.20.5 +DEPLOYSTACK_ENCRYPTION_SECRET=secret + +# Third-party Services (use service name prefix) +GITHUB_CLIENT_ID=client-id +GITHUB_CLIENT_SECRET=client-secret +SMTP_HOST=smtp.example.com +SMTP_PORT=587 + +# Feature Flags +ENABLE_SWAGGER_DOCS=true +ENABLE_DEBUG_MODE=false +``` + +## Debugging Environment Variables + +### Development Debugging + +```typescript +// Add to your server startup +console.log('Environment Variables:') +console.log('PORT:', process.env.PORT) +console.log('NODE_ENV:', process.env.NODE_ENV) +console.log('FRONTEND_URL:', process.env.DEPLOYSTACK_FRONTEND_URL) + +// Or create a debug endpoint (development only) +if (process.env.NODE_ENV === 'development') { + server.get('/debug/env', async (request, reply) => { + const safeEnvVars = { + PORT: process.env.PORT, + NODE_ENV: process.env.NODE_ENV, + DEPLOYSTACK_FRONTEND_URL: process.env.DEPLOYSTACK_FRONTEND_URL, + LOG_LEVEL: process.env.LOG_LEVEL, + // Don't expose secrets! + } + return safeEnvVars + }) +} +``` + +### Production Debugging + +```bash +# Check environment variables in Docker container +docker exec -it container-name env | grep DEPLOYSTACK + +# Or check specific variables +docker exec -it container-name printenv PORT +docker exec -it container-name printenv NODE_ENV +``` + +### Startup Banner + +The backend displays a startup banner with key environment information: + +```typescript +// src/utils/banner.ts +export const displayStartupBanner = (port: number): void => { + const version = process.env.DEPLOYSTACK_BACKEND_VERSION || '0.1.0' + const environment = process.env.NODE_ENV || 'development' + + console.log(` + ╔══════════════════════════════════════════════════════════════════════════════╗ + ║ 🚀 DeployStack Backend ║ + ║ ║ + ║ Running on port ${port} ║ + ║ Environment: ${environment} ║ + ║ Version: ${version} ║ + ╚══════════════════════════════════════════════════════════════════════════════╝ + `) +} +``` + +## Related Documentation + +- [Backend Development Guide](/deploystack/development/backend) - Main backend development guide +- [Database Configuration](/deploystack/development/backend/database) - Database setup and configuration +- [API Documentation](/deploystack/development/backend/api) - API development guide +- [Deploy DeployStack](/deploystack/self-hosted/docker-compose) - Deploy DeployStack with Docker Compose diff --git a/docs/deploystack/development/frontend/environment-variables.mdx b/docs/deploystack/development/frontend/environment-variables.mdx new file mode 100644 index 0000000..2ffa941 --- /dev/null +++ b/docs/deploystack/development/frontend/environment-variables.mdx @@ -0,0 +1,386 @@ +--- +title: Environment Variables +description: Complete guide to configuring and using environment variables in the DeployStack frontend application for both development and production environments. +sidebar: Environment Variables +--- + +# Frontend Environment Variables + +The DeployStack frontend uses a sophisticated environment variable system that seamlessly works across development and production environments. This system supports both Vite's build-time variables and Docker runtime variables for maximum flexibility. + +## Overview + +The frontend environment system consists of two layers: + +1. **Development Environment**: Uses Vite's built-in environment variable support with `.env` files +2. **Production Environment**: Uses Docker runtime variables that are injected at container startup + +This dual approach ensures that: +- Developers can work with standard `.env` files during development +- Production deployments can inject variables at runtime without rebuilding the application +- The same codebase works seamlessly in both environments + +## Environment Variable Types + +### Vite Environment Variables (Development) + +During development, Vite processes environment variables that start with `VITE_` prefix: + +```bash +# .env +VITE_DEPLOYSTACK_BACKEND_URL=http://localhost:3000 +VITE_APP_TITLE=DeployStack +``` + +### Runtime Environment Variables (Production) + +In production Docker containers, variables are injected at runtime via the `env-config.sh` script: + +```bash +# Docker run example +docker run -e VITE_DEPLOYSTACK_BACKEND_URL="https://api.deploystack.io" \ + -e VITE_APP_TITLE="DeployStack Production" \ + deploystack/frontend:latest +``` + +## Current Environment Variables + +### Core Application Variables + +| Variable | Description | Default Value | Required | +|----------|-------------|---------------|----------| +| `VITE_DEPLOYSTACK_BACKEND_URL` | Backend API base URL | `http://localhost:3000` | Yes | +| `VITE_APP_TITLE` | Application title displayed in UI | `DeployStack` | Yes | + +## Development Setup + +### Environment Files + +Create environment files in the `services/frontend` directory: + +#### `.env` (Base Configuration) +```bash +# Base environment variables +VITE_DEPLOYSTACK_BACKEND_URL=http://localhost:3000 +VITE_APP_TITLE=DeployStack +``` + +#### `.env.local` (Local Overrides) +```bash +# Local development environment variables +# This file is gitignored and used for local customization +VITE_DEPLOYSTACK_BACKEND_URL=http://localhost:3000 +VITE_APP_TITLE=DeployStack (Development) +``` + +### Environment File Priority + +Vite loads environment files in this order (higher priority overrides lower): + +1. `.env.local` (highest priority, gitignored) +2. `.env.development.local` +3. `.env.development` +4. `.env` (lowest priority) + +### Development Example + +```bash +# Navigate to frontend directory +cd services/frontend + +# Create your local environment file +cp .env .env.local + +# Edit .env.local with your local settings +echo "VITE_APP_TITLE=DeployStack (My Local Dev)" >> .env.local + +# Start development server +npm run dev +``` + +## Production Deployment + +### Docker Environment Variables + +The production Docker container uses the `env-config.sh` script to generate runtime environment variables: + +```bash +# Production deployment +docker run -d -p 8080:80 \ + -e VITE_DEPLOYSTACK_BACKEND_URL="https://api.deploystack.io" \ + -e VITE_APP_TITLE="DeployStack Production" \ + deploystack/frontend:latest +``` + +### Docker Compose Example + +```yaml +version: '3.8' +services: + frontend: + image: deploystack/frontend:latest + ports: + - "8080:80" + environment: + - VITE_DEPLOYSTACK_BACKEND_URL=https://api.deploystack.io + - VITE_APP_TITLE=DeployStack Production +``` + +## Using Environment Variables in Code + +### Accessing Variables + +Use the utility functions from `@/utils/env` for consistent access: + +```typescript +import { getEnv, getAllEnv } from '@/utils/env' + +// Get a specific environment variable +const backendUrl = getEnv('VITE_DEPLOYSTACK_BACKEND_URL') +const appTitle = getEnv('VITE_APP_TITLE') + +// Get all environment variables (useful for debugging) +const allEnvVars = getAllEnv() +console.log('All environment variables:', allEnvVars) +``` + +### Component Usage Example + +```vue + + + +``` + +### Service Layer Example + +```typescript +// services/apiService.ts +import { getEnv } from '@/utils/env' + +export class ApiService { + private static baseUrl = getEnv('VITE_DEPLOYSTACK_BACKEND_URL') + + static async get(endpoint: string) { + const response = await fetch(`${this.baseUrl}${endpoint}`) + return response.json() + } + + static async post(endpoint: string, data: any) { + const response = await fetch(`${this.baseUrl}${endpoint}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(data), + }) + return response.json() + } +} +``` + +## Adding New Environment Variables + +### Step 1: Update TypeScript Definitions + +Add the new variable to `env.d.ts`: + +```typescript +interface ImportMetaEnv { + readonly VITE_DEPLOYSTACK_BACKEND_URL: string + readonly VITE_APP_TITLE: string + readonly VITE_NEW_VARIABLE: string // Add your new variable +} +``` + +### Step 2: Add to Environment Files + +Add to your `.env` file: + +```bash +# .env +VITE_DEPLOYSTACK_BACKEND_URL=http://localhost:3000 +VITE_APP_TITLE=DeployStack +VITE_NEW_VARIABLE=default_value +``` + +### Step 3: Update Docker Configuration (if needed) + +For non-VITE_ prefixed variables, update `env-config.sh`: + +```bash +# Add specific non-VITE_ variables you want to expose +for var in CUSTOM_VAR OTHER_VAR NEW_CUSTOM_VAR; do + if [ ! -z "$(eval echo \$$var)" ]; then + echo " \"$var\": \"$(eval echo \$$var | sed 's/"/\\"/g')\"," >> /usr/share/nginx/html/runtime-env.js + fi +done +``` + +### Step 4: Use in Code + +```typescript +import { getEnv } from '@/utils/env' + +const newValue = getEnv('VITE_NEW_VARIABLE') +``` + +## Environment Variable Naming Conventions + +### Development (Vite) Variables + +- **Must** start with `VITE_` prefix to be accessible in the browser +- Use `SCREAMING_SNAKE_CASE` format +- Be descriptive and specific + +```bash +✅ Good +VITE_DEPLOYSTACK_BACKEND_URL=http://localhost:3000 +VITE_APP_TITLE=DeployStack +VITE_ENABLE_DEBUG_MODE=true + +❌ Bad +API_URL=http://localhost:3000 # Missing VITE_ prefix +vite_app_title=DeployStack # Wrong case +VITE_URL=http://localhost:3000 # Not descriptive +``` + +### Production Runtime Variables + +- Can include both `VITE_` prefixed and custom variables +- `VITE_` variables are automatically processed +- Custom variables need to be explicitly added to `env-config.sh` + +## Best Practices + +### Security + +1. **Never expose sensitive data** in environment variables accessible to the browser +2. **Use backend proxy** for sensitive API keys and secrets +3. **Validate environment variables** before using them + +```typescript +// Good: Validate environment variables +const backendUrl = getEnv('VITE_DEPLOYSTACK_BACKEND_URL') +if (!backendUrl) { + throw new Error('VITE_DEPLOYSTACK_BACKEND_URL is required') +} +``` + +### Performance + +1. **Cache environment variables** instead of calling `getEnv()` repeatedly +2. **Use computed properties** in Vue components for reactive environment values + +```vue + +``` + +### Development + +1. **Use `.env.local`** for personal development settings +2. **Document all environment variables** in this guide +3. **Provide sensible defaults** in `.env` file +4. **Test both development and production** environment setups + +## Troubleshooting + +### Common Issues + +#### Variable Not Accessible in Browser + +**Problem**: Environment variable is undefined in the browser + +**Solution**: Ensure the variable name starts with `VITE_` + +```bash +# ❌ Won't work +API_URL=http://localhost:3000 + +# ✅ Will work +VITE_API_URL=http://localhost:3000 +``` + +#### Variable Not Updated in Production + +**Problem**: Environment variable changes don't reflect in production + +**Solutions**: +1. Restart the Docker container +2. Check if the variable is properly passed to the container +3. Verify `env-config.sh` processes the variable correctly + +#### TypeScript Errors + +**Problem**: TypeScript complains about unknown environment variables + +**Solution**: Update `env.d.ts` with the new variable definition + +```typescript +interface ImportMetaEnv { + readonly VITE_DEPLOYSTACK_BACKEND_URL: string + readonly VITE_APP_TITLE: string + readonly VITE_YOUR_NEW_VARIABLE: string // Add this +} +``` + +#### Development vs Production Differences + +**Problem**: Different behavior between development and production + +**Solutions**: +1. Use the same variable names in both environments +2. Test with Docker locally: `docker build -t test . && docker run -e VITE_VAR=value test` +3. Use `getAllEnv()` to debug variable values + +### Validation Utility + +Create a validation utility for critical environment variables: + +```typescript +// utils/envValidation.ts +import { getEnv } from './env' + +export function validateEnvironment() { + const required = [ + 'VITE_DEPLOYSTACK_BACKEND_URL', + 'VITE_APP_TITLE' + ] + + const missing = required.filter(key => !getEnv(key)) + + if (missing.length > 0) { + throw new Error(`Missing required environment variables: ${missing.join(', ')}`) + } +} + +// Use in main.ts +import { validateEnvironment } from '@/utils/envValidation' + +validateEnvironment() +``` + +## Related Documentation + +- [Frontend Development Guide](/deploystack/development/frontend) - Main frontend development guide +- [Deploy DeployStack](/deploystack/self-hosted/docker-compose) - Deploy DeployStack with Docker Compose diff --git a/docs/deploystack/development/frontend/index.mdx b/docs/deploystack/development/frontend/index.mdx index bc78aa1..8a26c12 100644 --- a/docs/deploystack/development/frontend/index.mdx +++ b/docs/deploystack/development/frontend/index.mdx @@ -197,74 +197,33 @@ import { Mail, Lock, User, Settings, Play, Stop } from 'lucide-vue-next' ## Environment Configuration -The frontend supports environment variables for both development and production environments. +The frontend uses a sophisticated environment variable system that works seamlessly across development and production environments. For complete details on configuring and using environment variables, see the dedicated [Environment Variables Guide](/deploystack/development/frontend/environment-variables). -### Development Environment +### Quick Start -Create a `.env` file in the `services/frontend` directory: +Create environment files in the `services/frontend` directory: ```bash -VITE_API_URL=http://localhost:3000 -VITE_APP_TITLE=DeployStack (Development) -VITE_ENABLE_DEBUG=true -``` - -### Production Environment +# .env (base configuration) +VITE_DEPLOYSTACK_BACKEND_URL=http://localhost:3000 +VITE_APP_TITLE=DeployStack -Environment variables can be passed to the Docker container: - -```bash -docker run -it -p 80:80 \ - -e VITE_API_URL="https://api.deploystack.io" \ - -e VITE_APP_TITLE="DeployStack" \ - -e VITE_ENABLE_DEBUG="false" \ - deploystack/frontend:latest +# .env.local (local overrides, gitignored) +VITE_DEPLOYSTACK_BACKEND_URL=http://localhost:3000 +VITE_APP_TITLE=DeployStack (Development) ``` -### Accessing Environment Variables - -Use the `getEnv` utility function for consistent access: +### Accessing Variables in Code ```typescript -import { getEnv } from '@/utils/env' +import { getEnv, getAllEnv } from '@/utils/env' -// In your components -const apiUrl = getEnv('VITE_API_URL') +// Get specific variables +const backendUrl = getEnv('VITE_DEPLOYSTACK_BACKEND_URL') const appTitle = getEnv('VITE_APP_TITLE') -const debugMode = getEnv('VITE_ENABLE_DEBUG') === 'true' -``` - -### Adding New Environment Variables -1. **Add type definitions** in `env.d.ts`: - -```typescript -interface ImportMetaEnv { - readonly VITE_API_URL: string - readonly VITE_APP_TITLE: string - readonly VITE_ENABLE_DEBUG: string - readonly VITE_NEW_VARIABLE: string -} - -interface Window { - RUNTIME_ENV?: { - VITE_API_URL?: string - VITE_APP_TITLE?: string - VITE_ENABLE_DEBUG?: string - VITE_NEW_VARIABLE?: string - // Non-VITE variables - CUSTOM_VAR?: string - } -} -``` - -2. **For non-VITE variables** in Docker, update `env-config.sh`: - -```bash -# Add specific non-VITE_ variables you want to expose -for var in CUSTOM_VAR OTHER_VAR; do - # Script logic here -done +// Get all variables (useful for debugging) +const allEnvVars = getAllEnv() ``` ## API Integration @@ -340,6 +299,7 @@ onMounted(() => { Continue reading the detailed guides: +- [Environment Variables](/deploystack/development/frontend/environment-variables) - Complete environment configuration guide - [Global Event Bus](/deploystack/development/frontend/event-bus) - Cross-component communication system - [Internationalization (i18n)](/deploystack/development/frontend/internationalization) - Multi-language support - [Plugin System](/deploystack/development/frontend/plugins) - Extending functionality diff --git a/docs/deploystack/development/frontend/plugins.mdx b/docs/deploystack/development/frontend/plugins.mdx index ae5891a..ba8d407 100644 --- a/docs/deploystack/development/frontend/plugins.mdx +++ b/docs/deploystack/development/frontend/plugins.mdx @@ -44,8 +44,8 @@ Every plugin must implement the `Plugin` interface: ```typescript interface Plugin { meta: PluginMeta - initialize(app: App, router: Router, pinia: Pinia, pluginManager?: PluginManager): Promise - cleanup(): Promise + initialize(app: App, router: Router, pinia: Pinia): Promise | void + cleanup?(): Promise | void } interface PluginMeta { @@ -53,8 +53,7 @@ interface PluginMeta { name: string // Human-readable plugin name version: string // Plugin version (semver) description: string // Plugin description - author: string // Plugin author - dependencies?: string[] // Other plugin IDs this plugin depends on + author?: string // Plugin author (optional) } ``` @@ -65,8 +64,8 @@ interface PluginMeta { Create a new directory for your plugin: ```bash -mkdir -p src/plugins/mcp-metrics-plugin -cd src/plugins/mcp-metrics-plugin +mkdir -p src/plugins/my-custom-plugin +cd src/plugins/my-custom-plugin ``` ### 2. Create a Component @@ -74,80 +73,80 @@ cd src/plugins/mcp-metrics-plugin Start with a simple Vue component: ```vue - -