Skip to content

Data Source ​

This page explains how the library finds your TypeORM data source, how environment variables change its options, and how you keep several data sources side by side.

Discovery ​

The CLI and useDataSource() look for a file that exports a TypeORM DataSource (or one of the other accepted shapes):

typescript
// src/database/data-source.ts
import { DataSource } from 'typeorm';
import type { DataSourceOptions } from 'typeorm';
import type { SeederOptions } from 'typeorm-extension';

const options: DataSourceOptions & SeederOptions = {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'app',
    password: 'secret',
    database: 'app',
    entities: ['src/database/entities/**/*{.ts,.js}'],
    migrations: ['src/database/migrations/**/*{.ts,.js}'],
    seeds: ['src/database/seeds/**/*{.ts,.js}'],
    factories: ['src/database/factories/**/*{.ts,.js}'],
};

export const dataSource = new DataSource(options);

Without -d, these paths are tried in order, each with the extensions .js, .cjs, .mjs, .ts, .cts and .mts:

  1. data-source
  2. src/data-source
  3. src/db/data-source and src/database/data-source
  • The paths are relative to the current working directory and to the directory of the -d file (without -d: --root, which defaults to the current working directory).
  • -d (--dataSource) names another file, e.g. -d src/config/orm.ts. The path is relative to --root. The named file is tried first, and the paths above stay the fallback.
  • Unless the process runs under tsx or ts-node, the library assumes compiled code: src in these paths becomes the outDir of your tsconfig (default dist), and .ts becomes .js. The same rewrite applies to string paths in entities, migrations, subscribers, seeds and factories. When the rewritten path matches nothing but the original one does (e.g. Node's type stripping without a build), the original is used. A .ts original only qualifies when TypeScript support is detected (tsx, ts-node, or Node's type stripping; not with --no-experimental-strip-types, and see the tip below for decorators). Pass --preserveFilePaths to turn the rewrite off.
  • Every export of the file is checked, the default export included (see accepted export shapes). If a file has none of them, the next path is tried.
  • The library only reads the options of that DataSource. useDataSource() creates and initializes a new instance from them, so the exported instance stays uninitialized.

Accepted export shapes ​

Within one file the first match wins, in this order:

  1. A DataSource, or a promise that resolves to one (e.g. export default (async () => new DataSource(...))()).
  2. A default export function without parameters (sync or async) that returns a DataSource. It is called once, with no arguments. "Without parameters" means Function.length is 0, so a function whose parameters all have defaults ((name = 'app') => ...) or a rest parameter is called too. Named exports are never called, nor are classes or functions with a required parameter, and a result that is not a DataSource is ignored.
  3. A DataSourceOptions object (an object with a string type), default or named. The library reads the options directly; only findDataSource() wraps them in new DataSource(options).

The factory should return an uninitialized DataSource. The library only reads its options and creates its own instance, so an initialized one keeps an open connection the library never closes.

typescript
// a factory, e.g. to read a secret first
export default async function createDataSource() {
    return new DataSource({ type: 'postgres', password: await readSecret('db-password') });
}
typescript
// only the options
export const options: DataSourceOptions = { type: 'postgres', database: 'app' };

A file which exports a DataSource next to its options or a factory keeps working as before: the DataSource wins.

Import types with import type

When Node loads a .ts file itself (type stripping, behind --experimental-strip-types on older Node 22 releases and on by default since Node 22.18), it removes type annotations but keeps every import. import { DataSource, DataSourceOptions } from 'typeorm' then fails with does not provide an export named 'DataSourceOptions'. Write import type { DataSourceOptions } from 'typeorm'. Node's type stripping also does not support decorators, so files with entities need tsx or a build.

In code, buildDataSourceOptions() runs the same lookup, findDataSource() returns the DataSource it finds and findDataSourceOptions() returns only its options.

Environment variables ​

Data source options can also come from environment variables. Each variable has a DB_* name and a TYPEORM_* alias. When both are set, the DB_* name wins.

sh
DB_TYPE=postgres
DB_HOST=localhost
DB_USERNAME=app
DB_PASSWORD=secret
DB_DATABASE=app
DB_ENTITIES=dist/database/entities/*.js
VariableAliasSetsFormat
DB_TYPETYPEORM_CONNECTIONtypestring
DB_URLTYPEORM_URLurl, and type from its scheme if DB_TYPE is unsetstring
DB_HOSTTYPEORM_HOSThoststring
DB_PORTTYPEORM_PORTportint
DB_USERNAMETYPEORM_USERNAMEusernamestring
DB_PASSWORDTYPEORM_PASSWORDpasswordstring
DB_DATABASETYPEORM_DATABASEdatabase (better-sqlite3 default: db.sqlite)string
DB_SIDTYPEORM_SIDsid (oracle)string
DB_SCHEMATYPEORM_SCHEMAschema (postgres, cockroachdb, mssql)string
DB_UUID_EXTENSIONTYPEORM_UUID_EXTENSIONuuidExtension (postgres)string
DB_DRIVER_EXTRATYPEORM_DRIVER_EXTRAextraJSON
DB_SYNCHRONIZETYPEORM_SYNCHRONIZEsynchronizebool
DB_DROP_SCHEMATYPEORM_DROP_SCHEMAdropSchemabool
DB_MIGRATIONS_RUNTYPEORM_MIGRATIONS_RUNmigrationsRunbool
DB_ENTITIESTYPEORM_ENTITIESentitieslist
DB_MIGRATIONSTYPEORM_MIGRATIONSmigrationslist
DB_SUBSCRIBERSTYPEORM_SUBSCRIBERSsubscriberslist
DB_MIGRATIONS_TABLE_NAMETYPEORM_MIGRATIONS_TABLE_NAMEmigrationsTableNamestring
DB_METADATA_TABLE_NAMETYPEORM_METADATA_TABLE_NAMEmetadataTableNamestring
DB_ENTITY_PREFIXTYPEORM_ENTITY_PREFIXentityPrefixstring
DB_LOGGINGTYPEORM_LOGGINGloggingbool, all or list
DB_LOGGERTYPEORM_LOGGERloggerstring
DB_MAX_QUERY_EXECUTION_TIMETYPEORM_MAX_QUERY_EXECUTION_TIMEmaxQueryExecutionTimeint
DB_CACHETYPEORM_CACHEcachebool, redis, ioredis, ioredis/cluster or database
DB_CACHE_OPTIONSTYPEORM_CACHE_OPTIONScache.options (with a cache type)JSON
DB_CACHE_ALWAYS_ENABLEDTYPEORM_CACHE_ALWAYS_ENABLEDcache.alwaysEnabled (with a cache type)bool
DB_CACHE_DURATIONTYPEORM_CACHE_DURATIONcache.duration (with a cache type)int
DB_PIN_TIMEZONETYPEORM_PIN_TIMEZONEpins the session timezone, see pinTimezoneUTC only
DB_SEEDSTYPEORM_SEEDING_SEEDSseedslist
DB_FACTORIESTYPEORM_SEEDING_FACTORIESfactorieslist
DB_DEBUGTYPEORM_DEBUGuseEnv('debug') only, reserved and currently unusedstring
NODE_ENVuseEnv('env') only (default development)string

A list is comma separated. A comma inside a brace group or a character class ([,]) belongs to its glob pattern, so DB_SEEDS=src/database/seeds/**/*{.ts,.js} is one entry. An escaped brace (\{) is a literal character. A bool is true, t or 1, or false, f or 0; any other value counts as unset. A JSON value that does not parse throws when the environment is read.

How the environment combines with the data source file:

  • The environment adds data source options only when it names a driver: DB_TYPE, or a DB_URL with a scheme. Connection settings without a driver are ignored; assertEnvDataSourceOptions() throws for that case. DB_PIN_TIMEZONE applies in either case.
  • No file found: the options come from the environment alone. Neither a file nor a driver: OptionsError.
  • File and environment name the same driver: a set variable wins over the file, and the file fills the rest. An unset variable (DB_LOGGING included) leaves the file's value alone. extra and cache are merged key by key. entities, migrations and subscribers are joined, the environment's entries first.
  • File and environment name different drivers: the environment's options are used and the file is ignored.
  • When the environment names a driver, its defaults apply last, only to an option that the environment does not set and, if the file names the same driver, the file does not set either: database: 'db.sqlite' for better-sqlite3 and timeTravelQueries: true for cockroachdb. Options from a file alone get no defaults.
  • DB_SEEDS and DB_FACTORIES are the fallback: seeds or factories set in the data source options or passed in code win.

The library does not load .env files. Load one with Node (node --env-file=.env ...) or tsx (tsx --env-file=.env ...), or let your shell or process manager set the variables.

useEnv() reads the variables once and caches the result. If you change process.env afterwards (e.g. in tests), call resetEnv():

typescript
import { resetEnv, useEnv } from 'typeorm-extension';

process.env.DB_DATABASE = 'test';
resetEnv();

const database = useEnv('database'); // 'test'

Multiple instances ​

The library keeps data sources in a registry under an alias. Without an alias, the alias is default.

typescript
import { DataSource } from 'typeorm';
import {
    hasDataSource,
    setDataSource,
    setDataSourceOptions,
    unsetDataSource,
    useDataSource,
} from 'typeorm-extension';

// 1. a DataSource instance, initialized on first use
setDataSource(new DataSource({
    type: 'postgres',
    host: 'localhost',
    database: 'app',
}));

// 2. only options: the DataSource is created on first use
setDataSourceOptions({
    type: 'better-sqlite3',
    database: 'reports.sqlite',
}, 'reports');

const app = await useDataSource(); // alias 'default'
const reports = await useDataSource('reports');

hasDataSource('reports'); // true

await reports.destroy();
unsetDataSource('reports');
  • useDataSource(alias) returns the registered instance and initializes it if needed. With only options registered, it creates the DataSource from them.

  • With nothing registered for the alias, useDataSource() runs the discovery above, combined with the environment.

  • Concurrent useDataSource() calls for one alias share one build, so only one DataSource is created and initialized. A failed build is not cached; the next call tries again.

  • hasDataSource(alias) is true once an instance is registered or built. Registered options alone do not count.

  • unsetDataSource(alias) removes the instance from the registry. It does not destroy it, and registered options stay, so the next useDataSource(alias) builds a new instance from them.

  • setDataSource

  • useDataSource

  • setDataSourceOptions

  • useDataSourceOptions