PostgreSQL connection error when DB_SSL_MODE is omitted in AdonisJS production
0 reputation · 12 Oct 2022, 00:51 UTC
0 reputation · 12 Oct 2022, 00:51 UTC
When developing an AdonisJS application locally with SQLite, the server starts and migrations run without any additional configuration.
In production, switching the database driver to PostgreSQL by setting DB_CONNECTION=pg causes the Lucid ORM to throw a connection error during the first query or migration if DB_SSL_MODE is not explicitly defined.
The goal is to determine the correct SSL mode setting that allows the application to connect to a managed PostgreSQL service that enforces TLS, while preserving the ability to run locally with SQLite.
What DB_SSL_MODE value should be used for a hosted PostgreSQL that requires TLS? Should this variable be defined globally in .env or overridden per connection? How can the framework provide a clearer early‑warning message when SSL mode is missing?
33775 reputation · 12 Oct 2022, 06:20 UTC
When DB_SSL_MODE is omitted, the pg driver (used by Lucid via Knex) defaults to a non-TLS connection. Managed PostgreSQL services that enforce TLS will reject this connection, causing errors during the first query or migration.
Define SSL per connection in config/database.ts to avoid affecting SQLite:
// config/database.ts
export default {
connection: Env.get('DB_CONNECTION'),
connections: {
pg: {
client: 'pg',
connection: {
host: Env.get('DB_HOST'),
database: Env.get('DB_NAME'),
user: Env.get('DB_USER'),
password: Env.get('DB_PASSWORD'),
ssl: Env.get('DB_SSL') === 'true' ? { rejectUnauthorized: false } : false,
},
},
sqlite: {
client: 'sqlite3',
connection: { filename: './tmp/db.sqlite' },
useNullAsDefault: true,
},
},
}
In production .env:
DB_CONNECTION=pg
DB_SSL=true
Add validation in a service provider to fail fast:
// start/boot.ts or a service provider
if (process.env.NODE_ENV === 'production' &&
process.env.DB_CONNECTION === 'pg' &&
!process.env.DB_SSL) {
console.error('ERROR: DB_SSL must be set in production when using PostgreSQL')
process.exit(1)
}
Security: Using rejectUnauthorized: false disables certificate verification. Obtain your provider's CA certificate for production deployments.
Version: AdonisJS v5/v6 syntax may vary slightly. Verify against your installed version.
Connection Poolers: If using PgBouncer or similar, you may need to disable prepared statements to avoid conflicts.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.