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
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:
3. Connect from Your App
const { Pool } = require('pg');// Create connection poolconst pool = new Pool({connectionString: process.env.DATABASE_URL,ssl: {rejectUnauthorized: false // Required for Supabase},max: 20, // Maximum connectionsidleTimeoutMillis: 30000,connectionTimeoutMillis: 2000});// Test connectionpool.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
const express = require('express');const pool = require('./db');const app = express();app.use(express.json());// Query exampleapp.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 exampleapp.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');});
Example: Connecting to Neon
Neon provides serverless PostgreSQL with instant branching:
const { Pool, neonConfig } = require('@neondatabase/serverless');const ws = require('ws');// Configure WebSocket for serverlessneonConfig.webSocketConstructor = ws;const pool = new Pool({connectionString: process.env.DATABASE_URL});// Query with automatic connection managementasync 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
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 routesapp.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
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
const pool = new Pool({connectionString: process.env.DATABASE_URL});// Monitor pool eventspool.on('connect', () => {console.log('New database connection established');});pool.on('error', (err) => {console.error('Unexpected database error:', err);});// Log slow queriesconst 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
Database Migrations
Use migration tools to manage your database schema:
{"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"}}