Skip to main content

Overview

Esix follows a zero-configuration philosophy. It works out of the box with sensible defaults, requiring only a MongoDB connection string to get started. All configuration is done through environment variables.

Environment Variables

Esix supports three environment variables for configuration:

DB_URL

DB_URL
string
required
MongoDB connection string. This is the only required configuration.
export DB_URL="mongodb://localhost:27017/myapp"
Supported formats:
# Local MongoDB
DB_URL="mongodb://localhost:27017/myapp"

# MongoDB with authentication
DB_URL="mongodb://username:password@localhost:27017/myapp"

# MongoDB Atlas
DB_URL="mongodb+srv://username:password@cluster.mongodb.net/myapp"

# MongoDB with replica set
DB_URL="mongodb://host1:27017,host2:27017,host3:27017/myapp?replicaSet=myReplicaSet"
The connection string should include the database name. If not provided, you must set DB_DATABASE separately.

DB_DATABASE

DB_DATABASE
string
Database name. Optional if included in the connection string.
export DB_DATABASE="myapp"
Use this when you want to override the database name specified in the connection string or when your connection string doesn’t include a database:
# Connection string without database
export DB_URL="mongodb://localhost:27017"
export DB_DATABASE="myapp"

DB_ADAPTER

DB_ADAPTER
string
default:"default"
Database adapter to use. Set to 'mock' for testing.
export DB_ADAPTER="mock"
Available adapters:
AdapterDescriptionUse Case
defaultStandard MongoDB driverProduction and development
mockIn-memory mock databaseUnit tests and CI/CD
Use the mock adapter in your test environment to avoid connecting to a real database during tests.

DB_MAX_POOL_SIZE

DB_MAX_POOL_SIZE
string
default:"10"
Maximum number of connections in the connection pool.
export DB_MAX_POOL_SIZE="25"
Adjust this based on your application’s concurrency needs:
  • Low traffic: 5-10 connections
  • Medium traffic: 10-25 connections
  • High traffic: 25-100 connections
Setting this too high can overwhelm your MongoDB server. MongoDB Atlas has connection limits based on your cluster tier.

DB_POOL_SIZE (Deprecated)

DB_POOL_SIZE
string
deprecated
Legacy alias for DB_MAX_POOL_SIZE. Use DB_MAX_POOL_SIZE instead.

Configuration Examples

Development Environment

Create a .env file in your project root:
.env
DB_URL=mongodb://localhost:27017/myapp-dev
DB_MAX_POOL_SIZE=5
Load it using a package like dotenv:
import 'dotenv/config'
import { BaseModel } from 'esix'

// Your models are now configured
class User extends BaseModel {
  public name = ''
}

Production Environment

Set environment variables in your deployment platform:
DB_URL=mongodb+srv://user:pass@cluster.mongodb.net/myapp-prod
DB_MAX_POOL_SIZE=25

Testing Environment

Use the mock adapter for fast, isolated tests:
// test/setup.ts
import { beforeEach } from 'vitest'

beforeEach(() => {
  process.env.DB_ADAPTER = 'mock'
  process.env.DB_DATABASE = 'test-db'
})
// your-model.test.ts
import { describe, it, expect } from 'vitest'
import { User } from './models/user'

describe('User', () => {
  it('creates a user', async () => {
    const user = await User.create({
      name: 'Test User',
      email: 'test@example.com'
    })

    expect(user.name).toBe('Test User')
    expect(user.id).toBeDefined()
  })
})

Multiple Databases

Esix uses a global connection handler. To work with multiple databases, you can dynamically switch the DB_DATABASE environment variable:
import { connectionHandler } from 'esix'

// Close existing connection
await connectionHandler.closeConnections()

// Switch database
process.env.DB_DATABASE = 'other-database'

// New queries will use the new database
const users = await User.all()
This pattern is useful for multi-tenant applications where each tenant has a separate database.

Connection Pooling

Esix automatically manages connection pooling for optimal performance:
  • Connections are created on-demand when first needed
  • Connections are reused across queries
  • The pool size is controlled by DB_MAX_POOL_SIZE
  • Connections remain open for the lifetime of your application

Manual Connection Management

For graceful shutdowns, close connections manually:
import { connectionHandler } from 'esix'

process.on('SIGTERM', async () => {
  console.log('Closing database connections...')
  await connectionHandler.closeConnections()
  process.exit(0)
})

Connection String Options

You can pass MongoDB connection options via the connection string:
# Connection timeout
DB_URL="mongodb://localhost:27017/myapp?connectTimeoutMS=5000"

# Write concern
DB_URL="mongodb://localhost:27017/myapp?w=majority"

# Read preference
DB_URL="mongodb://localhost:27017/myapp?readPreference=secondary"

# Multiple options
DB_URL="mongodb://localhost:27017/myapp?retryWrites=true&w=majority"
See MongoDB Connection String Options for all available options.

Security Best Practices

Never Commit Secrets

Keep .env files out of version control. Add them to .gitignore.

Use Strong Credentials

Use strong passwords for database users and rotate them regularly.

Limit Permissions

Create database users with only the permissions they need.

Use TLS/SSL

Enable TLS for production databases. MongoDB Atlas enables this by default.

Troubleshooting

Connection Fails

Verify the connection string format and credentials:
import { connectionHandler } from 'esix'

try {
  await connectionHandler.getConnection()
  console.log('Connected successfully')
} catch (error) {
  console.error('Connection failed:', error.message)
}
Ensure your MongoDB server is accessible:
  • Check firewall rules
  • Verify IP whitelist (MongoDB Atlas)
  • Test with mongosh or MongoDB Compass
Verify username and password are correct and the user has access to the database.

Invalid Adapter Error

If you see an error like mysql is not a valid adapter name:
// ❌ Invalid
process.env.DB_ADAPTER = 'mysql'

// ✅ Valid
process.env.DB_ADAPTER = 'default' // or 'mock'
Esix only supports MongoDB. Valid adapters are 'default' and 'mock'.

Environment-Specific Configuration

Use different .env files for each environment:
# .env.development
DB_URL=mongodb://localhost:27017/myapp-dev
DB_MAX_POOL_SIZE=5

# .env.test
DB_ADAPTER=mock
DB_DATABASE=test-db

# .env.production
DB_URL=mongodb+srv://user:pass@cluster.mongodb.net/myapp
DB_MAX_POOL_SIZE=25
Load the appropriate file based on NODE_ENV:
import { config } from 'dotenv'

const envFile = `.env.${process.env.NODE_ENV || 'development'}`
config({ path: envFile })

Next Steps