Sequelize Connection String and Configuration
Configure Sequelize ORM with a connection string or object-based configuration. Covers PostgreSQL, MySQL, SQLite, and MSSQL with dialect options.
Best Practices
Detailed Explanation
Sequelize Connection Formats
Sequelize, one of the most popular Node.js ORMs, supports both URI string and object-based configuration.
URI String
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('postgresql://user:pass@localhost:5432/mydb');
Object Configuration
const sequelize = new Sequelize('mydb', 'user', 'password', {
host: 'localhost',
port: 5432,
dialect: 'postgres',
logging: false,
pool: {
max: 10,
min: 2,
acquire: 30000,
idle: 10000,
},
});
Dialect-Specific URIs
PostgreSQL
postgres://user:pass@host:5432/database
MySQL
mysql://user:pass@host:3306/database
SQLite
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: './database.sqlite',
});
SQLite in Sequelize uses storage instead of a URI.
MSSQL
mssql://user:pass@host:1433/database
SSL Configuration
Sequelize passes SSL options through dialectOptions:
const sequelize = new Sequelize('postgres://user:pass@host/db', {
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: true,
ca: fs.readFileSync('/path/to/ca.pem').toString(),
},
},
});
Connection Pool Options
| Option | Purpose | Default |
|---|---|---|
pool.max |
Maximum connections | 5 |
pool.min |
Minimum connections | 0 |
pool.acquire |
Max time (ms) to get connection | 60000 |
pool.idle |
Max time (ms) connection can be idle | 10000 |
pool.evict |
Interval (ms) to remove idle connections | 1000 |
Environment Variable Pattern
A common pattern is to use DATABASE_URL in production and explicit config in development:
const sequelize = process.env.DATABASE_URL
? new Sequelize(process.env.DATABASE_URL, {
dialectOptions: { ssl: { require: true } },
})
: new Sequelize('mydb', 'root', '', {
host: 'localhost',
dialect: 'mysql',
});
Use Case
Setting up a Sequelize-based Node.js API with connection pooling, SSL, and environment-specific database configuration for development and production.