Skip to main content

Prerequisites

Before installing CONFOR, ensure your system meets these requirements:

Required Software

  • Node.js 20 or higher (Download)
  • Docker and Docker Compose (recommended) or standalone PostgreSQL 15+
  • Git for cloning the repository
  • RAM: 4GB minimum, 8GB recommended
  • CPU: 2 cores minimum, 4 cores recommended
  • Storage: 10GB minimum (more for geospatial data)
  • OS: Linux, macOS, or Windows with WSL2
CONFOR requires PostgreSQL with PostGIS extension for geospatial features. The Docker setup includes this automatically.

Installation Methods

Choose your preferred installation method:
1

Clone the Repository

Clone the CONFOR repository to your local machine:
git clone https://github.com/your-org/confor.git
cd confor
2

Install Dependencies

Install Node.js packages:
npm install
The project uses pnpm by default, but npm and yarn are also supported.
3

Start Docker Services

Launch PostgreSQL and Redis containers:
docker compose up -d
This starts:
  • PostgreSQL 15 on port 5432
  • Redis 7 on port 6379 (optional, for caching)
Verify containers are running:
docker compose ps
Expected output:
NAME                SERVICE    STATUS
confor-postgres-1   postgres   running
confor-redis-1      redis      running
4

Configure Environment Variables

Create a .env file in the project root:
touch .env
Add the following configuration:
.env
# Database
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/app_dev?schema=public"

# NextAuth
NEXTAUTH_SECRET="your-secret-key-here-min-32-chars"
NEXTAUTH_URL="http://localhost:3000"

# Redis (optional)
REDIS_URL="redis://localhost:6379"

# Geo Worker Configuration (optional)
GEO_WORKER_INTERVAL_MS=4000
GEO_IMPORT_BATCH_SIZE=5
GEO_RECALC_BATCH_SIZE=10

# Email (optional, for notifications)
SMTP_HOST="smtp.example.com"
SMTP_PORT=587
SMTP_USER="[email protected]"
SMTP_PASS="your-password"
SMTP_FROM="[email protected]"
Generate a secure NEXTAUTH_SECRET with:
openssl rand -base64 32
5

Generate Prisma Client

Generate the Prisma database client:
npm run db:generate
This reads prisma/schema.prisma and generates type-safe database models.
6

Run Database Migrations

Apply database migrations to create tables:
npm run db:migrate
The first migration includes PostGIS extension activation and table partitioning setup for audit logs.
Expected output:
Prisma Migrate applied the following migration(s):

migrations/
  └─ 0001_extensions_partitioning/
     └─ migration.sql
  └─ 0002_initial_schema/
     └─ migration.sql
7

Seed Initial Data

Load default data including admin user, roles, and modules:
npm run db:seed
This creates:
  • Default admin user:
  • System roles: ADMIN, USER, VIEWER
  • Module permissions: Dashboard, Users, Patrimony, etc.
  • Default organization: “Por defecto”
Change the default admin password immediately after first login in production environments.
8

Start Development Server

Launch the Next.js development server:
npm run dev
The application will be available at:
http://localhost:3000
The dev server includes hot module replacement (HMR) for rapid development.
9

Start Geo Worker (Optional)

In a separate terminal, start the geospatial processing worker:
npm run worker:geo
The worker processes:
  • Shapefile imports - Extracting, validating, and storing geometries
  • Area recalculations - Updating Level 2/3 totals from Level 4 changes
Worker configuration:
// Default settings
{
  intervalMs: 4000,           // Poll every 4 seconds
  importBatchSize: 5,         // Process 5 imports per cycle
  recalcBatchSize: 10         // Process 10 recalcs per cycle
}
For testing, run a single cycle with:
pnpm worker:geo:once

Method 2: Manual Setup (Without Docker)

1

Install PostgreSQL

Install PostgreSQL 15+ with PostGIS:Ubuntu/Debian:
sudo apt update
sudo apt install postgresql-15 postgresql-15-postgis-3
macOS (Homebrew):
brew install postgresql@15 postgis
brew services start postgresql@15
Windows: Download from PostgreSQL.org and install PostGIS via Stack Builder.
2

Create Database

Create the application database:
psql -U postgres
CREATE DATABASE app_dev;
\c app_dev
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
\q
3

Install Redis (Optional)

Ubuntu/Debian:
sudo apt install redis-server
sudo systemctl start redis
macOS:
brew install redis
brew services start redis
4

Configure Environment

Update your .env with the correct database connection:
DATABASE_URL="postgresql://postgres:your-password@localhost:5432/app_dev?schema=public"
5

Continue with Standard Setup

Follow steps 2-8 from the Docker installation method above (Install Dependencies through Start Geo Worker).

Method 3: PM2 Production Deployment

For production deployments on Windows or Linux servers:
1

Install PM2 Globally

npm install -g pm2
2

Build for Production

npm run build
This creates an optimized production build in .next/.
3

Configure PM2 Ecosystem

The project includes ecosystem.config.cjs:
ecosystem.config.cjs
module.exports = {
  apps: [
    {
      name: 'confor-web',
      script: 'node_modules/next/dist/bin/next',
      args: 'start',
      env: {
        NODE_ENV: 'production',
        PORT: 3000
      },
      instances: 1,
      exec_mode: 'cluster',
      max_memory_restart: '1G'
    },
    {
      name: 'confor-geo-worker',
      script: 'node_modules/tsx/dist/cli.mjs',
      args: 'src/workers/geo-worker-scheduler.ts',
      env: {
        NODE_ENV: 'production'
      },
      instances: 1,
      exec_mode: 'fork'
    }
  ]
};
4

Start with PM2

pm2 start ecosystem.config.cjs
Monitor processes:
pm2 status
pm2 logs confor-web
pm2 logs confor-geo-worker
5

Enable Auto-Restart on Boot

Linux:
pm2 startup systemd
pm2 save
Windows:
pm2 startup
# Follow the generated command
pm2 save
6

Manage PM2 Processes

# Restart
pm2 restart confor-web
pm2 restart confor-geo-worker

# Stop
pm2 stop all

# Delete
pm2 delete all

# Monitor
pm2 monit

Database Schema Overview

CONFOR uses a comprehensive PostgreSQL schema with 40+ tables:

Core Authentication Tables

  • User - User accounts with organization membership
  • Role - Custom roles per organization
  • Permission - Granular module-level permissions
  • Session - Active user sessions
  • AuditLog - Partitioned audit trail (monthly partitions)

Forest Patrimony Tables

  • ForestPatrimonyLevel2 - Top-level properties (Finca/Predio)
  • ForestPatrimonyLevel3 - Compartments (Lote)
  • ForestPatrimonyLevel4 - Stands (Rodal)
  • ForestPatrimonyLevel5 - Plots (Subunidad)
  • ForestBiologicalAssetLevel6 - Biological assets and inventory

Geospatial Tables

  • ForestGeometryN4 - Polygon geometries (MultiPolygon, EPSG:4326)
  • GeoImportJob - Shapefile import job tracking
  • GeoImportJobItem - Individual feature import status
  • ForestGeometryRecalcJob - Area recalculation queue

Variation Tracking

  • LandPatrimonialVariation - Land use changes and valuation
  • GeoLandVariationJob - Split/merge geometric operations

Environment Variables Reference

Required Variables

# Database connection (required)
DATABASE_URL="postgresql://user:password@host:5432/database?schema=public"

# Authentication secret (required, min 32 chars)
NEXTAUTH_SECRET="generated-secret-key"

# Application URL (required)
NEXTAUTH_URL="http://localhost:3000"

Optional Variables

# Redis for caching and sessions
REDIS_URL="redis://localhost:6379"

# Geo Worker Performance
GEO_WORKER_INTERVAL_MS=4000        # Polling interval (milliseconds)
GEO_IMPORT_BATCH_SIZE=5            # Import jobs per cycle
GEO_RECALC_BATCH_SIZE=10           # Recalc jobs per cycle
GEO_WORKER_RUN_ONCE=false          # Set to 'true' for single run

# Email Configuration (for notifications)
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER="[email protected]"
SMTP_PASS="your-app-password"
SMTP_FROM="CONFOR <[email protected]>"

# Logging
LOG_LEVEL="info"                   # debug | info | warn | error

Post-Installation Steps

1

Verify Installation

Check that all services are running:
# Database
psql -U postgres -c "SELECT version();"

# Redis (if using)
redis-cli ping

# Application
curl http://localhost:3000/api/health
2

Login as Admin

Navigate to http://localhost:3000 and login:
Immediately change this password in production!
3

Create Your Organization

Navigate to Organizaciones and create your first organization:
{
  name: "Your Company Name",
  slug: "your-company",         // URL-friendly identifier
  description: "Company description",
  website: "https://yourcompany.com",
  isActive: true
}
4

Configure Roles and Permissions

Navigate to Roles to customize permissions for your organization.Default roles:
  • ADMIN - Full system access
  • USER - Standard user with read/write
  • VIEWER - Read-only access
5

Set Up Audit Log Partitions

For production, create monthly partitions:
npm run db:partition -- --year 2026 --month 4
This runs scripts/create-audit-partition.ts to create a partition for April 2026.
Schedule this monthly with cron or a system scheduler.

Troubleshooting

Database Connection Fails

Error: Error: P1001: Can't reach database server Solutions:
  1. Verify PostgreSQL is running: docker compose ps or systemctl status postgresql
  2. Check DATABASE_URL format in .env
  3. Ensure firewall allows port 5432
  4. Test connection: psql -U postgres -h localhost

PostGIS Extension Not Found

Error: ERROR: could not open extension control file Solution:
-- Connect to database
\c app_dev

-- Install extension
CREATE EXTENSION IF NOT EXISTS postgis;

-- Verify
SELECT PostGIS_version();

Prisma Migration Fails

Error: Migration failed to apply Solution:
  1. Reset database (development only):
    npm run db:push -- --force-reset
    
  2. Manually apply migrations:
    psql -U postgres -d app_dev -f prisma/migrations/0001_extensions_partitioning/migration.sql
    

Port Already in Use

Error: EADDRINUSE: address already in use :::3000 Solutions:
  1. Kill existing process:
    # Linux/Mac
    lsof -ti:3000 | xargs kill -9
    
    # Windows
    netstat -ano | findstr :3000
    taskkill /PID <PID> /F
    
  2. Use different port:
    PORT=3001 npm run dev
    

Geo Worker Not Processing Jobs

Symptoms: Shapefile imports stuck in PENDING status Solutions:
  1. Verify worker is running:
    pm2 logs confor-geo-worker
    
  2. Check job queue:
    SELECT id, status, file_name, error_message 
    FROM geo_import_jobs 
    WHERE status = 'PENDING' 
    ORDER BY created_at DESC;
    
  3. Manually trigger processing:
    GEO_WORKER_RUN_ONCE=true npm run worker:geo
    

Next Steps

Quick Start Guide

Create your first forest patrimony structure

User Management

Add team members and configure access control

Shapefile Import

Upload geospatial data for your forest stands

API Reference

Integrate CONFOR with external systems

Getting Help

For additional support:
  • GitHub Issues: Report bugs or request features
  • Documentation: Comprehensive guides for all features
  • Community: Join discussions with other CONFOR users
  • Support: Contact your system administrator or vendor

Build docs developers (and LLMs) love