External Database - Replov Docs
Skip to main content

External Database

Connect to managed databases from Supabase, Neon, PlanetScale, and more

External Database services let you connect your Replov applications to managed database providers. No need to manage database infrastructure yourself.

Supported Providers

Supabase

PostgreSQL with built-in auth, storage, and real-time subscriptions

supabase.com →

Neon

Serverless PostgreSQL with instant branching and autoscaling

neon.tech →

PlanetScale

Serverless MySQL with branching and schema management

planetscale.com →

MongoDB Atlas

Managed MongoDB with global clusters and search

mongodb.com/atlas →

Why Use External Databases?

  • Managed Infrastructure: No database maintenance required
  • Provider Backups: Most managed database providers offer backups and point-in-time recovery; check what your provider's plan includes
  • Scalability: Scale storage and compute independently
  • High Availability: Built-in redundancy and failover
  • Free Tiers: Most providers offer generous free tiers

Example: Connecting to Supabase

1. Create Supabase Project

Sign up at supabase.com and create a new project. Note your connection string from Settings → Database.

2. Add Environment Variable

In your Replov service, add the database URL as an environment variable:

DATABASE_URL=postgresql://postgres:[password]@db.xxx.supabase.co:5432/postgres

3. Connect from Your App

db.jsjavascript
const { Pool } = require('pg');
// Create connection pool
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false // Required for Supabase
},
max: 20, // Maximum connections
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
});
// Test connection
pool.query('SELECT NOW()', (err, res) => {
if (err) {
console.error('Database connection error:', err);
} else {
console.log('Database connected:', res.rows[0].now);
}
});
module.exports = pool;

4. Use in Your Application

app.jsjavascript
const express = require('express');
const pool = require('./db');
const app = express();
app.use(express.json());
// Query example
app.get('/api/users', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM users LIMIT 10');
res.json({ users: result.rows });
} catch (error) {
console.error('Query error:', error);
res.status(500).json({ error: 'Database query failed' });
}
});
// Insert example
app.post('/api/users', async (req, res) => {
const { name, email } = req.body;
try {
const result = await pool.query(
'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',
[name, email]
);
res.status(201).json({ user: result.rows[0] });
} catch (error) {
console.error('Insert error:', error);
res.status(500).json({ error: 'Failed to create user' });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Connection Pooling
Always use connection pooling (pg.Pool) instead of creating new connections for each query. This improves performance and prevents connection exhaustion.

Example: Connecting to Neon

Neon provides serverless PostgreSQL with instant branching:

neon-db.jsjavascript
const { Pool, neonConfig } = require('@neondatabase/serverless');
const ws = require('ws');
// Configure WebSocket for serverless
neonConfig.webSocketConstructor = ws;
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
// Query with automatic connection management
async function query(text, params) {
const client = await pool.connect();
try {
const result = await client.query(text, params);
return result.rows;
} finally {
client.release();
}
}
module.exports = { query };

Example: Connecting to MongoDB Atlas

mongodb.jsjavascript
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.MONGODB_URI, {
maxPoolSize: 10,
minPoolSize: 2,
serverSelectionTimeoutMS: 5000
});
let db;
async function connectDB() {
try {
await client.connect();
db = client.db('myapp');
console.log('MongoDB connected');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
}
function getDB() {
if (!db) {
throw new Error('Database not initialized');
}
return db;
}
// Usage in routes
app.get('/api/products', async (req, res) => {
try {
const db = getDB();
const products = await db.collection('products')
.find({})
.limit(20)
.toArray();
res.json({ products });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = { connectDB, getDB };

Security Best Practices

  • Environment Variables: Never hardcode database credentials
  • SSL/TLS: Always use encrypted connections
  • Least Privilege: Use database users with minimal required permissions
  • IP Allowlisting: Restrict database access to your Replov services
  • Prepared Statements: Use parameterized queries to prevent SQL injection
Connection Strings
Store database connection strings as environment variables in Replov. Never commit them to your repository.

Performance Optimization

Connection Pooling

Reuse database connections instead of creating new ones for each request. Set appropriate pool sizes based on your traffic.

Query Optimization

Use indexes, limit result sets, and avoid N+1 queries. Monitor slow queries using your database provider's tools.

Caching

Cache frequently accessed data using Redis to reduce database load.

Read Replicas

Use read replicas for read-heavy workloads (available on most managed providers).

Monitoring & Debugging

db-monitoring.jsjavascript
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
// Monitor pool events
pool.on('connect', () => {
console.log('New database connection established');
});
pool.on('error', (err) => {
console.error('Unexpected database error:', err);
});
// Log slow queries
const originalQuery = pool.query.bind(pool);
pool.query = function(...args) {
const start = Date.now();
return originalQuery(...args).then(result => {
const duration = Date.now() - start;
if (duration > 1000) {
console.warn(`Slow query (${duration}ms):`, args[0]);
}
return result;
});
};

Pricing

External Database services on Replov are free - you only pay your database provider:

  • • Supabase: Free tier: 500MB database, 1GB file storage
  • • Neon: Free tier: 3GB storage, 1 project
  • • PlanetScale: Free tier: 5GB storage, 1 billion row reads/month
  • • MongoDB Atlas: Free tier: 512MB storage, shared cluster
Most providers offer generous free tiers perfect for development and small production apps.

Database Migrations

Use migration tools to manage your database schema:

package.jsonbash
{
"scripts": {
"migrate": "node-pg-migrate up",
"migrate:down": "node-pg-migrate down",
"migrate:create": "node-pg-migrate create"
},
"dependencies": {
"node-pg-migrate": "^6.2.2"
}
}
Migration Tools
Popular migration tools: node-pg-migrate (PostgreSQL), Prisma Migrate, Knex.js, TypeORM, Sequelize