Skip to main content
RapidDev - Software Development Agency
replit-tutorial

How to connect Replit to external databases

Connect your Replit app to external databases by storing connection strings in the Secrets tool (Tools > Secrets), installing the appropriate database client library, and using SSL for encrypted connections. Replit supports PostgreSQL, MySQL, MongoDB, Redis, and any database reachable over the internet. Store credentials as separate secrets (DB_HOST, DB_USER, DB_PASSWORD) or as a single connection URI (DATABASE_URL). Always add these same secrets to the Deployments pane for production access.

What you'll learn

  • Store database credentials securely using Replit Secrets
  • Connect to PostgreSQL, MySQL, and MongoDB from Replit
  • Configure SSL connections for encrypted data transmission
  • Handle the workspace vs deployment secrets distinction
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate9 min read20 minutesReplit Core ($25/mo) and Pro ($100/mo) plans recommended — Starter works but has resource limitsMarch 2026RapidDev Engineering Team
TL;DR

Connect your Replit app to external databases by storing connection strings in the Secrets tool (Tools > Secrets), installing the appropriate database client library, and using SSL for encrypted connections. Replit supports PostgreSQL, MySQL, MongoDB, Redis, and any database reachable over the internet. Store credentials as separate secrets (DB_HOST, DB_USER, DB_PASSWORD) or as a single connection URI (DATABASE_URL). Always add these same secrets to the Deployments pane for production access.

Securely Connect Replit to External PostgreSQL, MySQL, and MongoDB Databases

While Replit includes a built-in PostgreSQL database, many projects need to connect to external databases hosted on services like Supabase, PlanetScale, MongoDB Atlas, or AWS RDS. This tutorial shows you how to securely store connection credentials, install database client libraries, establish SSL-encrypted connections, and handle the critical difference between workspace secrets and deployment secrets. You will have a working database connection that works in both development and production.

Prerequisites

  • A Replit account (Core or Pro recommended for deployments)
  • An external database with connection credentials (host, port, user, password, database name)
  • Basic understanding of SQL or NoSQL database concepts
  • Your database must allow connections from external IPs (check firewall/allowlist settings)

Step-by-step guide

1

Store connection credentials in Secrets

Open the Secrets tool from the Tools dock in the left sidebar. Add your database credentials as individual secrets or as a connection URI. Using individual secrets gives you more flexibility, while a connection URI is simpler for most libraries. Never hardcode credentials in your source code. Secrets are AES-256 encrypted and transmitted over TLS. Remember that collaborators with edit access can see secret values, so share workspace access carefully when database credentials are involved.

Expected result: Your database credentials are stored in the Secrets tool and accessible via environment variables.

2

Allow Replit IP addresses in your database firewall

External databases typically restrict connections to known IP addresses. Since Replit runs on shared infrastructure, you may need to allow connections from all IPs (0.0.0.0/0) or use your database provider's specific configuration for cloud-hosted clients. Check your database provider's documentation for firewall or allowlist settings. On services like Supabase, PlanetScale, and MongoDB Atlas, there is usually an IP allowlist section in the dashboard where you can add 0.0.0.0/0 for development or configure more restrictive rules for production.

Expected result: Your database accepts connections from Replit's infrastructure.

3

Connect to PostgreSQL

Install the pg package for Node.js or psycopg2 for Python from the Shell. Use the connection string stored in your Secrets to establish a connection. For SSL connections, which most cloud-hosted PostgreSQL providers require, set the ssl option to reject unauthorized certificates or provide a CA certificate. Test the connection by running a simple query like SELECT NOW() to confirm it works.

typescript
1// Node.js — PostgreSQL connection
2import pg from 'pg';
3const { Pool } = pg;
4
5const pool = new Pool({
6 connectionString: process.env.DATABASE_URL,
7 ssl: {
8 rejectUnauthorized: false // Set to true with CA cert in production
9 }
10});
11
12async function testConnection() {
13 try {
14 const result = await pool.query('SELECT NOW()');
15 console.log('Connected:', result.rows[0].now);
16 } catch (error) {
17 console.error('Connection failed:', error.message);
18 }
19}
20
21testConnection();

Expected result: The console logs the current database timestamp, confirming a successful connection.

4

Connect to MySQL

Install the mysql2 package for Node.js or mysql-connector-python for Python. MySQL connections follow a similar pattern: read credentials from environment variables and establish a pool or single connection. Most cloud MySQL providers like PlanetScale require SSL. The mysql2 package supports SSL natively through the connection configuration.

typescript
1// Node.js — MySQL connection
2import mysql from 'mysql2/promise';
3
4const pool = mysql.createPool({
5 host: process.env.DB_HOST,
6 port: parseInt(process.env.DB_PORT || '3306'),
7 user: process.env.DB_USER,
8 password: process.env.DB_PASSWORD,
9 database: process.env.DB_NAME,
10 ssl: {
11 rejectUnauthorized: true
12 }
13});
14
15async function testConnection() {
16 try {
17 const [rows] = await pool.query('SELECT NOW() as now');
18 console.log('Connected:', rows[0].now);
19 } catch (error) {
20 console.error('Connection failed:', error.message);
21 }
22}
23
24testConnection();

Expected result: The MySQL connection succeeds and the current timestamp is logged.

5

Connect to MongoDB

Install the mongodb package for Node.js or pymongo for Python. MongoDB Atlas provides a connection URI that includes the cluster address, credentials, and database name. Store the full URI in Secrets as MONGODB_URI. MongoDB Atlas connections use TLS by default, so no additional SSL configuration is needed in most cases.

typescript
1// Node.js — MongoDB connection
2import { MongoClient } from 'mongodb';
3
4const uri = process.env.MONGODB_URI;
5const client = new MongoClient(uri);
6
7async function testConnection() {
8 try {
9 await client.connect();
10 const db = client.db('myapp');
11 const result = await db.command({ ping: 1 });
12 console.log('Connected to MongoDB:', result);
13 } catch (error) {
14 console.error('Connection failed:', error.message);
15 } finally {
16 await client.close();
17 }
18}
19
20testConnection();

Expected result: The MongoDB ping command returns successfully, confirming the connection.

6

Add secrets to the Deployments pane for production

This is the step most developers forget. Workspace secrets do not carry over to deployments. Open the Deployments pane from the left sidebar, find the Secrets section, and add every database credential your app needs. Use production database credentials here, which may differ from development values. If you skip this step, your deployed app will crash with errors about undefined connection strings or failed authentication.

Expected result: All database credentials are present in both the workspace Secrets and the Deployments pane Secrets.

Complete working example

db.js
1// db.js — Database connection module
2// Supports PostgreSQL, MySQL, and MongoDB
3// Connection credentials are read from Replit Secrets
4
5import pg from 'pg';
6
7const { Pool } = pg;
8
9// PostgreSQL connection pool with SSL
10const pool = new Pool({
11 connectionString: process.env.DATABASE_URL,
12 ssl: process.env.REPLIT_DEPLOYMENT
13 ? { rejectUnauthorized: true }
14 : { rejectUnauthorized: false },
15 max: 10,
16 idleTimeoutMillis: 30000,
17 connectionTimeoutMillis: 5000,
18});
19
20// Test connection on startup
21pool.on('connect', () => {
22 console.log('Database pool: new client connected');
23});
24
25pool.on('error', (err) => {
26 console.error('Database pool error:', err.message);
27});
28
29// Query helper with error handling
30export async function query(text, params) {
31 const start = Date.now();
32 try {
33 const result = await pool.query(text, params);
34 const duration = Date.now() - start;
35 console.log(`Query executed in ${duration}ms, rows: ${result.rowCount}`);
36 return result;
37 } catch (error) {
38 console.error('Query error:', error.message);
39 throw error;
40 }
41}
42
43// Health check for deployment
44export async function healthCheck() {
45 try {
46 const result = await pool.query('SELECT 1');
47 return { status: 'healthy', timestamp: new Date().toISOString() };
48 } catch (error) {
49 return { status: 'unhealthy', error: error.message };
50 }
51}
52
53// Graceful shutdown
54export async function disconnect() {
55 await pool.end();
56 console.log('Database pool closed');
57}
58
59export default { query, healthCheck, disconnect };

Common mistakes when connecting Replit to external databases

Why it's a problem: Hardcoding database credentials in source code instead of using Secrets

How to avoid: Move all credentials to Tools then Secrets. Access them via process.env.DATABASE_URL in Node.js or os.environ in Python. Never commit credentials to Git.

Why it's a problem: Forgetting to add database secrets to the Deployments pane, causing production crashes

How to avoid: Open the Deployments pane and add every database-related environment variable separately. Workspace secrets are not shared with deployments.

Why it's a problem: Database connection timing out because the database firewall blocks Replit's IP addresses

How to avoid: Add 0.0.0.0/0 to your database's IP allowlist for development. For production, use SSL-verified connections or your provider's recommended cloud access configuration.

Why it's a problem: Not using SSL, causing connection refused errors from cloud databases that require encrypted connections

How to avoid: Add ssl: { rejectUnauthorized: false } to your connection config for development. In production, use rejectUnauthorized: true with the proper CA certificate.

Why it's a problem: Creating a new database connection for every request instead of using a connection pool

How to avoid: Initialize a Pool once at startup and reuse it for all queries. Creating connections per request exhausts database connection limits and causes ETIMEDOUT errors.

Best practices

  • Store all database credentials in Replit Secrets, never in source code or configuration files committed to Git
  • Add database secrets to both workspace Secrets and Deployment Secrets — they are independent
  • Use connection pooling (Pool instead of Client) to manage multiple concurrent database queries efficiently
  • Enable SSL for all database connections, especially when connecting to cloud-hosted databases over the internet
  • Use separate database credentials for development and production to protect production data from accidental changes
  • Set connection timeout values to fail fast instead of hanging when the database is unreachable
  • Add a health check endpoint that tests the database connection for deployment monitoring
  • Close database connections gracefully on shutdown to avoid connection leaks

Still stuck?

Copy one of these prompts to get a personalized, step-by-step explanation.

ChatGPT Prompt

I am building a Node.js app on Replit that needs to connect to an external PostgreSQL database hosted on Supabase. How do I securely store the connection string, configure SSL, handle the difference between workspace and deployment secrets, and set up connection pooling? Include error handling and a health check endpoint.

Replit Prompt

Connect my app to an external PostgreSQL database. The connection string is stored in Secrets as DATABASE_URL. Set up a connection pool with SSL, add a health check endpoint at /health that tests the database connection, and make sure the connection works in both development and deployed environments.

Frequently asked questions

Yes. Replit includes a built-in PostgreSQL database accessible via the DATABASE_URL environment variable. It is free for development with 10 GB storage. For production, it runs on Replit's Helium infrastructure with usage-based billing. Use external databases when you need more storage, specific database types like MongoDB, or when you want to share the database across multiple services.

Almost always because you did not add the database secrets to the Deployments pane. Workspace secrets and deployment secrets are independent. Open the Deployments pane and add DATABASE_URL and all other database credentials there.

Most cloud database providers require SSL for connections from external clients. Even when not required, you should enable SSL because database traffic crosses the internet between Replit's servers and your database host. Add ssl: { rejectUnauthorized: false } to your connection configuration.

Not directly. Replit runs in the cloud and cannot access your local network. You would need to expose your local database through a service like ngrok or deploy it to a cloud provider. For development, consider using Replit's built-in PostgreSQL or a free-tier cloud database.

Run migration commands from the Shell using your ORM's CLI. For example, npx prisma migrate dev for Prisma or npx drizzle-kit push for Drizzle. For complex database architectures, teams can work with RapidDev to establish proper migration workflows and staging environments.

This depends on your database provider, not Replit. Most providers limit connections per tier. Use connection pooling with a reasonable max setting (10-20 connections) to avoid exhausting your limit. Replit's built-in PostgreSQL supports standard connection limits.

Yes. Collaborators with edit access can see both names and values in the Secrets tool. They can also print secret values via code. Rotate credentials if you remove a collaborator who had access.

Install the ioredis package (npm install ioredis), store your Redis connection URL in Secrets, and connect using new Redis(process.env.REDIS_URL). Most Redis cloud providers like Upstash and Redis Cloud support TLS connections.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.