Skip to content
Latchkey

TypeORM "DataSource is not initialized" in CI

TypeORM requires AppDataSource.initialize() to resolve before any query or migration runs. If code touches the DataSource first, or initialize threw, TypeORM reports that the connection is not established.

What this error means

A migration or seed step fails with "Connection is not established with ... database" or "DataSource is not initialized", typically right after startup in CI.

typeorm output
Error: Connection is not established with postgres database
    at DataSource.query (.../DataSource.js)

Common causes

Querying before initialize() completes

Code calls a repository or query before awaiting AppDataSource.initialize(), so there is no live connection yet.

initialize() failed silently earlier

The connection attempt threw (bad credentials, unreachable host) but the rejection was not awaited, so a later call reports the connection as not established.

How to fix it

Await initialize() before using the DataSource

Make sure initialization is awaited and any error surfaces before queries run.

migrate.ts
await AppDataSource.initialize();
await AppDataSource.runMigrations();

Check the initialize error first

  1. Wrap initialize() in try/catch and log the real cause.
  2. Confirm host, port, and credentials reach the CI database service.
  3. Only run migrations after initialize resolves successfully.

How to prevent it

  • Always await initialize() and handle its rejection.
  • Verify connection settings against the CI database service.
  • Run migrations only inside the initialized DataSource lifecycle.

Frequently asked questions

What causes "TypeORM "Connection ... not established""?
Code calls a repository or query before awaiting AppDataSource.initialize(), so there is no live connection yet.
How do I fix TypeORM "Connection ... not established"?
Make sure initialization is awaited and any error surfaces before queries run.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card