Admin Tools
Admin Tools
This section documents all administrative tools available in the YouTube Analyzer application, with a focus on the Prompt Management System. It consolidates all technical details, UI, API, backend logic, and workflow for prompt management and other admin features.
Overview
Admin tools provide advanced management capabilities for system administrators, including prompt template management, versioning, and other backend controls. These tools are accessible only to users with admin privileges.
Prompt Management System
The Prompt Management System in YouTube Analyzer is a comprehensive solution for managing the LLM prompt templates used in video analysis. It features a versioned approach to prompt templates with careful tracking of changes and active versions.
1. Admin UI
Location: /app/(protected)/dashboard/admin/prompts/PromptsAdmin/
- Tabbed interface for managing different prompt types (e.g., "Standard Summary", "Channel Deep Dive").
- View, edit, and create new prompt versions.
- Version history with editor and timestamp.
- All changes are made via API calls (no direct DB access).
Key Components
| Component | Purpose | Functionality |
|---|---|---|
index.tsx | Main container | Manages global state, API fetching, version selection, and overall layout |
PromptEditor.tsx | Template editor | Text editor for prompt templates with variable insertion |
VersionDropdown.tsx | Version selector | Displays and selects between different prompt versions |
SaveAsModal.tsx | Version creation | Modal for creating new prompt versions with descriptions |
TestResults.tsx | Test display | Shows results from testing prompt templates |
VariablesList.tsx | Template variables | Shows available variables that can be inserted into templates |
AnalysisRecordDropdown.tsx | Test selection | Selects analysis records for testing prompts |
UI Workflow
- Tab Navigation: Admin selects a prompt type (e.g., "Standard Summary", "Executive Summary").
- Version Selection: Admin selects a version from the dropdown to view or edit.
- Editing: Admin modifies the template in the text editor.
- Variable Insertion: Admin can insert template variables using the variables list.
- Version Creation: Admin saves changes as a new version with an optional description.
- Version Activation: Admin can set any version as the active one for production use.
- Testing: Admin can test the prompt against real data before activating.
2. Database Schema
Tables:
-
PromptModel:id: Unique identifier (CUID)name: Display name of the promptdescription: Optional descriptionanalysisTypeKey: Key that maps to analysis types in config (e.g., "standard-summary")createdById: User ID of creator (audit trail)createdAt: Creation timestampupdatedAt: Last update timestampstatus: ACTIVE or ARCHIVED
-
PromptVersionModel:id: Unique identifier (CUID)promptId: Foreign key to parent promptcontent: The actual prompt template textvariables: JSON field for variable metadataversion: Integer version number (auto-incrementing)createdById: User ID of creator (audit trail)createdAt: Creation timestampisActive: Boolean flag for active version
Relationships:
- One
Prompthas manyPromptVersions (one-to-many) - Only one
PromptVersionperPromptcan be active (isActive = true)
Important Constraints:
- Each prompt-version pair must be unique (
@@unique([promptId, version])) - Foreign key relationships ensure data integrity
3. API Endpoints
Location: /app/api/prompts/
Main Endpoints
-
GET /api/prompts/: List all prompt types and latest versions.- Optional filter by
analysisTypeKey - Returns prompts with their most recent version
- Admin authentication required
- Optional filter by
-
POST /api/prompts/: Create a new prompt type with initial version.- Required fields:
name,analysisTypeKey,content - Optional fields:
description,variables - Creates both the prompt and its first version in one transaction
- Admin authentication required
- Required fields:
ID-based Operations (/api/prompts/[id])
-
GET /api/prompts/[id]: Get a single prompt with all its versions.- Returns prompt with all versions sorted by version number (descending)
- Admin authentication required
-
PATCH /api/prompts/[id]: Three different operations:- Update prompt metadata (
name,description,status) - Add a new version (
newVersionobject withcontentandvariables) - Set active version (
setActiveVersionwith version ID)
- Each operation can be performed independently
- Admin authentication required
- Update prompt metadata (
-
DELETE /api/prompts/[id]: Soft delete (archive) a prompt.- Updates status to ARCHIVED instead of removing from database
- Admin authentication required
Testing Endpoint
POST /api/prompts/test: Test a prompt version against an analysis.- Takes
promptId,versionnumber, andanalysisId - Returns rendered HTML result
- Provides a safe testing environment without affecting production data
- Aids in verifying prompt effectiveness before activation
- Admin authentication required
- Implementation details:
- Fetches the specified prompt version from the database
- Retrieves the complete analysis record with all video data
- Processes templates using the same core logic as production
- Returns test results immediately without storing to database
- Catches and reports detailed error information for debugging
- Testing workflow:
- Admin selects a prompt version to test
- Admin chooses an analysis record for test data
- System runs the prompt against the analysis data
- Results are displayed but not saved as a new analysis
- Takes
Support Endpoints for Testing
-
GET /api/prompts/sample-analyses: Returns a list of recent analyses for prompt testing.- Returns simplified analysis data including ID, channel name, video count, transcript length, and a preview of the analysis summary
- Processes and formats data to be immediately usable in the testing UI
- Used by the prompt testing UI to select real data for test runs
- Admin authentication required
- Internally queries the Analysis and Video tables, limiting to 20 recent analyses
- Returns data normalized with consistent structure for prompt variable substitution
-
GET /api/prompts/sample-transcripts: Returns sample video transcripts for prompt testing.- Returns up to 10 recent video transcripts with metadata (id, title, language, content)
- Used for testing template variables with real content
- Admin authentication required
- Provides raw transcripts that can be used to simulate the analysis process
- Used by the transcript selection modal in the prompt testing interface
-
GET /api/prompts/env: Exposes limited environment configuration for testing.- Returns only the streaming server URL (without any API keys or sensitive data)
- Used to configure the test environment in the prompt admin UI
- Admin authentication required
- Security note: This endpoint only exposes the
STREAMING_SERVER_URLenvironment variable - Current implementation strips any endpoint paths (like
/analyze-channel) to ensure only the base URL is exposed - Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
- Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
- Better approaches include:
- Injecting necessary configurations at build time using Next.js environment variables
- Using secure server-side configuration with appropriate access controls
- Moving the configuration into a dedicated configuration service with proper authentication
- Using feature flags or a dedicated config management system
4. Shared Backend Logic
Location: /lib/prompts.ts
Key Functions
-
loadPromptTemplate: Loads prompt files from the filesystem.- Reads from file paths like
prompts/${analysisType}.txt - Falls back to default type if specified one isn't found
- Reads from file paths like
-
fillPromptTemplate: Template engine for replacing variables.- Replaces
{{variableName}}placeholders with actual values - Handles missing variables by replacing with empty string
- Replaces
-
buildPrompt: Constructs complete prompts for analysis.- Combines template with data for LLM processing
- Formats complex data structures like arrays and objects
- Converts structured data to strings for template insertion
Integration with Analysis Workflow
- LLM analysis code uses these functions to get the current active prompt
- Variables from video/channel data are injected into templates
- Results are processed and stored in analysis records
5. Version Management Workflow
Version States
- Draft: New version being edited (not saved)
- Saved: Version that exists in the database but is not active
- Active: The current production version used for analysis (only one active version per prompt type)
Version Creation Process
- Admin selects an existing prompt version to use as starting point
- Admin edits the template content
- Admin clicks "Save as New Version"
- Admin provides an optional description
- System:
- Determines the next version number (latest + 1)
- Creates a new record in PromptVersion
- Sets
isActive = falseby default - Returns updated prompt with all versions
Version Activation Process
- Admin selects the desired version
- Admin clicks "Make Active"
- System:
- Updates all versions for that prompt to
isActive = false - Sets the selected version to
isActive = true - Frontend optimistically updates UI
- All new analyses will use this version
- Updates all versions for that prompt to
6. Prompt Template Format
Template Structure
Prompt templates use a simple {{variable}} syntax for dynamic content:
Create a comprehensive summary for the YouTube channel {{channelName}}.
This channel has {{videoCount}} videos analyzed.
Video data:
{{videoLinksWithData}}
Performance metrics:
{{performanceData}}
Combined transcript data:
{{combinedTranscripts}}
Chart data:
{{chartData}}
Available Variables
channelName: Name of the YouTube channelvideoCount: Number of videos analyzedperformanceData: Channel statistics and metricscombinedTranscripts: Processed transcript textvideoLinksWithData: Video metadata and linksvideosString: Simplified video listchartData: Structured data for visualizationsvideos: Raw video data array (JSON)
7. Testing Workflow
Test Process
- Admin selects a prompt version to test
- Admin selects an existing analysis record as test data
- Admin clicks "Run Test"
- System:
- Renders the prompt with the selected analysis data
- Sends to LLM for processing
- Returns the generated HTML result
- Displays side-by-side comparison of prompt and result
Test Data Sources
- Real analysis records from the database
- Sample data for new prompt types
- Admin can select different analyses to test edge cases
8. Error Handling and Validation
- Form Validation: Required fields are checked before submission
- API Validation: Additional validation at API level with clear error messages
- Version Conflicts: System prevents duplicate version numbers
- Permission Checks: All endpoints verify admin role
9. Security Considerations
- Authentication: All prompt management endpoints require admin authentication
- No Direct DB Access: All changes go through validated API endpoints
- Limited Environment Variable Exposure:
- The
/api/prompts/envendpoint exposes only the streaming server URL but no API keys or other sensitive data - Current implementation strips any endpoint paths (like
/analyze-channel) to ensure only the base URL is exposed - Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
- Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
- Better approaches include:
- Injecting necessary configurations at build time using Next.js environment variables
- Using secure server-side configuration with appropriate access controls
- Moving the configuration into a dedicated configuration service with proper authentication
- Using feature flags or a dedicated config management system
- The
- Validation: Input validation at both client and server levels
- Audit Trail: Version history provides an audit trail of prompt changes
- No Raw SQL: All database access uses Prisma ORM with parameterized queries
Beta Mode Invite Code Management System
The Beta Mode Invite Code Management System allows administrators to control registration during beta periods by requiring valid invite codes for new user signups.
1. Overview
When BETA_MODE=true is set in environment variables, the application requires invite codes for new user registration. Administrators can create, manage, and track invite codes through a dedicated admin interface.
2. Admin UI
Location: /app/(protected)/dashboard/admin/invite-codes/
Features
- Create invite codes: Generate unique codes with custom descriptions and usage limits
- Track usage: Monitor how many times each code has been used
- Manage status: Activate/deactivate codes as needed
- Usage analytics: View which email addresses used specific codes
- Bulk management: Create codes for different purposes (sponsors, early access, etc.)
UI Components
| Component | Purpose | Functionality |
|---|---|---|
InviteCodeManager | Main management interface | Create, list, and manage all invite codes |
| Code creation dialog | Generate new codes | Form for description and usage limits |
| Usage tracking table | Monitor code usage | Display usage stats and user emails |
| Status toggle | Activate/deactivate codes | Control code availability |
3. Database Schema
InviteCode Model:
model InviteCode {
id String @id @default(cuid())
code String @unique // Generated unique code
description String? // Optional description for tracking
createdAt DateTime @default(now())
createdById String? // Admin who created it
usedAt DateTime? // When it was used
usedByEmail String? // Email of user who used it
isActive Boolean @default(true)
maxUses Int @default(1) // How many times it can be used
currentUses Int @default(0) // How many times it's been used
createdBy User? @relation(fields: [createdById], references: [id])
}Key Features:
- Unique codes: Each invite code is automatically generated using
nanoid - Usage tracking: Tracks both maximum allowed uses and current usage count
- Audit trail: Records who created the code and who used it
- Flexible limits: Supports single-use or multi-use codes
4. API Endpoints
Location: /app/api/admin/invite-codes/
Main Endpoints
-
GET /api/admin/invite-codes: List all invite codes with usage statistics- Returns array of invite codes with creator information
- Sorted by creation date (newest first)
- Admin authentication required
-
POST /api/admin/invite-codes: Create a new invite code- Required: Admin authentication
- Optional fields:
description,maxUses(defaults to 1) - Automatically generates unique code using
nanoid(10).toUpperCase() - Returns created code with all metadata
Individual Code Management
-
PATCH /api/admin/invite-codes/[id]: Update invite code status- Toggle
isActivestatus to enable/disable codes - Used for temporarily deactivating codes without deletion
- Admin authentication required
- Toggle
-
DELETE /api/admin/invite-codes/[id]: Permanently delete invite code- Hard delete from database
- Admin authentication required
- Use with caution as this removes audit trail
5. Beta Mode Integration
Environment Configuration
# Enable beta mode
BETA_MODE=trueWhen beta mode is enabled:
- Registration form shows invite code field
/api/auth/validate-invite-codeendpoint validates codes before registration/api/auth/use-invite-codeendpoint consumes codes during registration- Invalid or exhausted codes prevent registration
Registration Flow
- User visits registration page: Form includes invite code field when beta mode is active
- Client-side validation: Code is validated before form submission
- Server-side processing: Code usage is tracked and incremented
- Registration completion: User account is created and code usage is recorded
Validation Logic
// Code validation checks:
- Code exists in database
- Code is active (isActive = true)
- Code has remaining uses (currentUses < maxUses)
- Code usage is incremented atomically6. Command Line Tools
Create Invite Codes via Script
Location: scripts/create-invite-code.js
# Create single-use code with description
node scripts/create-invite-code.js "For podcast sponsors" 1
# Create multi-use code
node scripts/create-invite-code.js "Early access users" 5
# Create code with default settings
node scripts/create-invite-code.jsFeatures:
- Generates unique codes automatically
- Supports custom descriptions and usage limits
- Provides immediate feedback with code details
- Checks beta mode status and provides guidance
7. Security Considerations
- Admin-only access: All invite code management requires
ADMINrole - Atomic operations: Code usage updates use database transactions
- Usage limits: Strict enforcement of usage quotas prevents abuse
- Audit trail: Complete tracking of code creation and usage
- Unique constraints: Database ensures no duplicate codes
8. Monitoring and Analytics
Usage Tracking
- Track which codes are most popular
- Monitor usage patterns over time
- Identify unused or expired codes
- Analyze registration conversion rates
Admin Dashboard Features
- Real-time usage statistics
- Code performance metrics
- User registration tracking
- Bulk code management tools
Additional Admin Tools
This section can be expanded as new admin features are added.
Recommended Config API Alternative
We've created a more secure alternative to the current /api/prompts/env endpoint approach. The new endpoint (/api/prompts/config) implements these security best practices:
import { NextResponse } from 'next/server';
import { auth } from '@/auth';
export async function GET() {
// Require admin authentication
const session = await auth();
if (!session || session.user.role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Get base streaming URL (without exposing the full environment variable)
let streamingUrl = process.env.STREAMING_SERVER_URL || '';
if (streamingUrl.endsWith('/analyze-channel')) {
streamingUrl = streamingUrl.replace(/\/analyze-channel$/, '');
}
// Return a configuration object with only the necessary non-sensitive settings
return NextResponse.json({
promptTesting: {
streamingServiceUrl: streamingUrl,
defaultTimeout: 120000, // 2 minutes
maxResponseTokens: 4000,
},
// Add feature flags or other configuration categories as needed
});
}Advantages:
- Explicit admin authentication check
- Returns a structured configuration object instead of direct environment variables
- Makes it clear what configuration is being exposed (no accidental exposure)
- Can be extended with feature flags and other settings
- Provides a more consistent API structure
Implementation steps:
- Create the new endpoint at
/api/prompts/config/route.ts - Update the PromptEditor component to use this new endpoint
- Deprecate and eventually remove the old
/api/prompts/envendpoint
Prompt Management System
The Prompt Management System in YouTube Analyzer is a comprehensive solution for managing the LLM prompt templates used in video analysis. It features a versioned approach to prompt templates with careful tracking of changes and active versions.
1. Admin UI
Location: /app/(protected)/dashboard/admin/prompts/PromptsAdmin/
- Tabbed interface for managing different prompt types (e.g., "Standard Summary", "Channel Deep Dive").
- View, edit, and create new prompt versions.
- Version history with editor and timestamp.
- All changes are made via API calls (no direct DB access).
Key Components
| Component | Purpose | Functionality |
|---|---|---|
index.tsx | Main container | Manages global state, API fetching, version selection, and overall layout |
PromptEditor.tsx | Template editor | Text editor for prompt templates with variable insertion |
VersionDropdown.tsx | Version selector | Displays and selects between different prompt versions |
SaveAsModal.tsx | Version creation | Modal for creating new prompt versions with descriptions |
TestResults.tsx | Test display | Shows results from testing prompt templates |
VariablesList.tsx | Template variables | Shows available variables that can be inserted into templates |
AnalysisRecordDropdown.tsx | Test selection | Selects analysis records for testing prompts |
UI Workflow
- Tab Navigation: Admin selects a prompt type (e.g., "Standard Summary", "Executive Summary").
- Version Selection: Admin selects a version from the dropdown to view or edit.
- Editing: Admin modifies the template in the text editor.
- Variable Insertion: Admin can insert template variables using the variables list.
- Version Creation: Admin saves changes as a new version with an optional description.
- Version Activation: Admin can set any version as the active one for production use.
- Testing: Admin can test the prompt against real data before activating.
2. Database Schema
Tables:
-
PromptModel:id: Unique identifier (CUID)name: Display name of the promptdescription: Optional descriptionanalysisTypeKey: Key that maps to analysis types in config (e.g., "standard-summary")createdById: User ID of creator (audit trail)createdAt: Creation timestampupdatedAt: Last update timestampstatus: ACTIVE or ARCHIVED
-
PromptVersionModel:id: Unique identifier (CUID)promptId: Foreign key to parent promptcontent: The actual prompt template textvariables: JSON field for variable metadataversion: Integer version number (auto-incrementing)createdById: User ID of creator (audit trail)createdAt: Creation timestampisActive: Boolean flag for active version
Relationships:
- One
Prompthas manyPromptVersions (one-to-many) - Only one
PromptVersionperPromptcan be active (isActive = true)
Important Constraints:
- Each prompt-version pair must be unique (
@@unique([promptId, version])) - Foreign key relationships ensure data integrity
3. API Endpoints
Location: /app/api/prompts/
Main Endpoints
-
GET /api/prompts/: List all prompt types and latest versions.- Optional filter by
analysisTypeKey - Returns prompts with their most recent version
- Admin authentication required
- Optional filter by
-
POST /api/prompts/: Create a new prompt type with initial version.- Required fields:
name,analysisTypeKey,content - Optional fields:
description,variables - Creates both the prompt and its first version in one transaction
- Admin authentication required
- Required fields:
ID-based Operations (/api/prompts/[id])
-
GET /api/prompts/[id]: Get a single prompt with all its versions.- Returns prompt with all versions sorted by version number (descending)
- Admin authentication required
-
PATCH /api/prompts/[id]: Three different operations:- Update prompt metadata (
name,description,status) - Add a new version (
newVersionobject withcontentandvariables) - Set active version (
setActiveVersionwith version ID)
- Each operation can be performed independently
- Admin authentication required
- Update prompt metadata (
-
DELETE /api/prompts/[id]: Soft delete (archive) a prompt.- Updates status to ARCHIVED instead of removing from database
- Admin authentication required
Testing Endpoint
POST /api/prompts/test: Test a prompt version against an analysis.- Takes
promptId,versionnumber, andanalysisId - Returns rendered HTML result
- Provides a safe testing environment without affecting production data
- Aids in verifying prompt effectiveness before activation
- Admin authentication required
- Implementation details:
- Fetches the specified prompt version from the database
- Retrieves the complete analysis record with all video data
- Processes templates using the same core logic as production
- Returns test results immediately without storing to database
- Catches and reports detailed error information for debugging
- Testing workflow:
- Admin selects a prompt version to test
- Admin chooses an analysis record for test data
- System runs the prompt against the analysis data
- Results are displayed but not saved as a new analysis
- Takes
Support Endpoints for Testing
-
GET /api/prompts/sample-analyses: Returns a list of recent analyses for prompt testing.- Returns simplified analysis data including ID, channel name, video count, transcript length, and a preview of the analysis summary
- Processes and formats data to be immediately usable in the testing UI
- Used by the prompt testing UI to select real data for test runs
- Admin authentication required
- Internally queries the Analysis and Video tables, limiting to 20 recent analyses
- Returns data normalized with consistent structure for prompt variable substitution
-
GET /api/prompts/sample-transcripts: Returns sample video transcripts for prompt testing.- Returns up to 10 recent video transcripts with metadata (id, title, language, content)
- Used for testing template variables with real content
- Admin authentication required
- Provides raw transcripts that can be used to simulate the analysis process
- Used by the transcript selection modal in the prompt testing interface
-
GET /api/prompts/env: Exposes limited environment configuration for testing.- Returns only the streaming server URL (without any API keys or sensitive data)
- Used to configure the test environment in the prompt admin UI
- Admin authentication required
- Security note: This endpoint only exposes the
STREAMING_SERVER_URLenvironment variable - Current implementation strips any endpoint paths (like
/analyze-channel) to ensure only the base URL is exposed - Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
- Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
- Better approaches include:
- Injecting necessary configurations at build time using Next.js environment variables
- Using secure server-side configuration with appropriate access controls
- Moving the configuration into a dedicated configuration service with proper authentication
- Using feature flags or a dedicated config management system
4. Shared Backend Logic
Location: /lib/prompts.ts
Key Functions
-
loadPromptTemplate: Loads prompt files from the filesystem.- Reads from file paths like
prompts/${analysisType}.txt - Falls back to default type if specified one isn't found
- Reads from file paths like
-
fillPromptTemplate: Template engine for replacing variables.- Replaces
{{variableName}}placeholders with actual values - Handles missing variables by replacing with empty string
- Replaces
-
buildPrompt: Constructs complete prompts for analysis.- Combines template with data for LLM processing
- Formats complex data structures like arrays and objects
- Converts structured data to strings for template insertion
Integration with Analysis Workflow
- LLM analysis code uses these functions to get the current active prompt
- Variables from video/channel data are injected into templates
- Results are processed and stored in analysis records
5. Version Management Workflow
Version States
- Draft: New version being edited (not saved)
- Saved: Version that exists in the database but is not active
- Active: The current production version used for analysis (only one active version per prompt type)
Version Creation Process
- Admin selects an existing prompt version to use as starting point
- Admin edits the template content
- Admin clicks "Save as New Version"
- Admin provides an optional description
- System:
- Determines the next version number (latest + 1)
- Creates a new record in PromptVersion
- Sets
isActive = falseby default - Returns updated prompt with all versions
Version Activation Process
- Admin selects the desired version
- Admin clicks "Make Active"
- System:
- Updates all versions for that prompt to
isActive = false - Sets the selected version to
isActive = true - Frontend optimistically updates UI
- All new analyses will use this version
- Updates all versions for that prompt to
6. Prompt Template Format
Template Structure
Prompt templates use a simple {{variable}} syntax for dynamic content:
Create a comprehensive summary for the YouTube channel {{channelName}}.
This channel has {{videoCount}} videos analyzed.
Video data:
{{videoLinksWithData}}
Performance metrics:
{{performanceData}}
Combined transcript data:
{{combinedTranscripts}}
Chart data:
{{chartData}}
Available Variables
channelName: Name of the YouTube channelvideoCount: Number of videos analyzedperformanceData: Channel statistics and metricscombinedTranscripts: Processed transcript textvideoLinksWithData: Video metadata and linksvideosString: Simplified video listchartData: Structured data for visualizationsvideos: Raw video data array (JSON)
7. Testing Workflow
Test Process
- Admin selects a prompt version to test
- Admin selects an existing analysis record as test data
- Admin clicks "Run Test"
- System:
- Renders the prompt with the selected analysis data
- Sends to LLM for processing
- Returns the generated HTML result
- Displays side-by-side comparison of prompt and result
Test Data Sources
- Real analysis records from the database
- Sample data for new prompt types
- Admin can select different analyses to test edge cases
8. Error Handling and Validation
- Form Validation: Required fields are checked before submission
- API Validation: Additional validation at API level with clear error messages
- Version Conflicts: System prevents duplicate version numbers
- Permission Checks: All endpoints verify admin role
9. Security Considerations
- Authentication: All prompt management endpoints require admin authentication
- No Direct DB Access: All changes go through validated API endpoints
- Limited Environment Variable Exposure:
- The
/api/prompts/envendpoint exposes only the streaming server URL but no API keys or other sensitive data - Current implementation strips any endpoint paths (like
/analyze-channel) to ensure only the base URL is exposed - Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
- Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
- Better approaches include:
- Injecting necessary configurations at build time using Next.js environment variables
- Using secure server-side configuration with appropriate access controls
- Moving the configuration into a dedicated configuration service with proper authentication
- Using feature flags or a dedicated config management system
- The
- Validation: Input validation at both client and server levels
- Audit Trail: Version history provides an audit trail of prompt changes
- No Raw SQL: All database access uses Prisma ORM with parameterized queries
Beta Mode Invite Code Management System
The Beta Mode Invite Code Management System allows administrators to control registration during beta periods by requiring valid invite codes for new user signups.
1. Overview
When BETA_MODE=true is set in environment variables, the application requires invite codes for new user registration. Administrators can create, manage, and track invite codes through a dedicated admin interface.
2. Admin UI
Location: /app/(protected)/dashboard/admin/invite-codes/
Features
- Create invite codes: Generate unique codes with custom descriptions and usage limits
- Track usage: Monitor how many times each code has been used
- Manage status: Activate/deactivate codes as needed
- Usage analytics: View which email addresses used specific codes
- Bulk management: Create codes for different purposes (sponsors, early access, etc.)
UI Components
| Component | Purpose | Functionality |
|---|---|---|
InviteCodeManager | Main management interface | Create, list, and manage all invite codes |
| Code creation dialog | Generate new codes | Form for description and usage limits |
| Usage tracking table | Monitor code usage | Display usage stats and user emails |
| Status toggle | Activate/deactivate codes | Control code availability |
3. Database Schema
InviteCode Model:
model InviteCode {
id String @id @default(cuid())
code String @unique // Generated unique code
description String? // Optional description for tracking
createdAt DateTime @default(now())
createdById String? // Admin who created it
usedAt DateTime? // When it was used
usedByEmail String? // Email of user who used it
isActive Boolean @default(true)
maxUses Int @default(1) // How many times it can be used
currentUses Int @default(0) // How many times it's been used
createdBy User? @relation(fields: [createdById], references: [id])
}Key Features:
- Unique codes: Each invite code is automatically generated using
nanoid - Usage tracking: Tracks both maximum allowed uses and current usage count
- Audit trail: Records who created the code and who used it
- Flexible limits: Supports single-use or multi-use codes
4. API Endpoints
Location: /app/api/admin/invite-codes/
Main Endpoints
-
GET /api/admin/invite-codes: List all invite codes with usage statistics- Returns array of invite codes with creator information
- Sorted by creation date (newest first)
- Admin authentication required
-
POST /api/admin/invite-codes: Create a new invite code- Required: Admin authentication
- Optional fields:
description,maxUses(defaults to 1) - Automatically generates unique code using
nanoid(10).toUpperCase() - Returns created code with all metadata
Individual Code Management
-
PATCH /api/admin/invite-codes/[id]: Update invite code status- Toggle
isActivestatus to enable/disable codes - Used for temporarily deactivating codes without deletion
- Admin authentication required
- Toggle
-
DELETE /api/admin/invite-codes/[id]: Permanently delete invite code- Hard delete from database
- Admin authentication required
- Use with caution as this removes audit trail
5. Beta Mode Integration
Environment Configuration
# Enable beta mode
BETA_MODE=trueWhen beta mode is enabled:
- Registration form shows invite code field
/api/auth/validate-invite-codeendpoint validates codes before registration/api/auth/use-invite-codeendpoint consumes codes during registration- Invalid or exhausted codes prevent registration
Registration Flow
- User visits registration page: Form includes invite code field when beta mode is active
- Client-side validation: Code is validated before form submission
- Server-side processing: Code usage is tracked and incremented
- Registration completion: User account is created and code usage is recorded
Validation Logic
// Code validation checks:
- Code exists in database
- Code is active (isActive = true)
- Code has remaining uses (currentUses < maxUses)
- Code usage is incremented atomically6. Command Line Tools
Create Invite Codes via Script
Location: scripts/create-invite-code.js
# Create single-use code with description
node scripts/create-invite-code.js "For podcast sponsors" 1
# Create multi-use code
node scripts/create-invite-code.js "Early access users" 5
# Create code with default settings
node scripts/create-invite-code.jsFeatures:
- Generates unique codes automatically
- Supports custom descriptions and usage limits
- Provides immediate feedback with code details
- Checks beta mode status and provides guidance
7. Security Considerations
- Admin-only access: All invite code management requires
ADMINrole - Atomic operations: Code usage updates use database transactions
- Usage limits: Strict enforcement of usage quotas prevents abuse
- Audit trail: Complete tracking of code creation and usage
- Unique constraints: Database ensures no duplicate codes
8. Monitoring and Analytics
Usage Tracking
- Track which codes are most popular
- Monitor usage patterns over time
- Identify unused or expired codes
- Analyze registration conversion rates
Admin Dashboard Features
- Real-time usage statistics
- Code performance metrics
- User registration tracking
- Bulk code management tools