0
# Configuration
1
2
Sails.js provides a unified configuration system that merges settings from multiple sources, enabling flexible environment-specific configuration with runtime access and validation. The configuration system supports .sailsrc files, environment variables, command-line arguments, and programmatic overrides.
3
4
## Configuration Access
5
6
### getRc()
7
8
Load configuration from .sailsrc files, environment variables, and command-line arguments:
9
10
```javascript { .api }
11
sails.getRc(namespace?: String): Dictionary
12
```
13
14
**Parameters**:
15
- `namespace` (String, optional) - Configuration namespace (default: 'sails')
16
17
**Returns**: `Dictionary` - Merged configuration object from all sources
18
19
**Configuration Sources** (in precedence order):
20
1. Command-line arguments (parsed with `minimist`)
21
2. Environment variables with namespace prefix
22
3. Local `.sailsrc` files (current directory and upward)
23
4. Global `.sailsrc` files (home directory)
24
5. Default configuration values
25
26
**Example**:
27
```javascript
28
// Get default Sails configuration
29
const config = sails.getRc();
30
console.log('Port:', config.port);
31
console.log('Environment:', config.environment);
32
console.log('Log level:', config.log?.level);
33
34
// Get custom namespace configuration
35
const appConfig = sails.getRc('myapp');
36
console.log('Custom config:', appConfig);
37
38
// Programmatic configuration access
39
console.log('Database URL:', sails.getRc().datastores?.default?.url);
40
```
41
42
### Runtime Configuration Access
43
44
```javascript { .api }
45
sails.config // Dictionary - Complete merged configuration
46
```
47
48
**Example**:
49
```javascript
50
// Access configuration at runtime
51
console.log('Current port:', sails.config.port);
52
console.log('Environment:', sails.config.environment);
53
console.log('Database config:', sails.config.datastores);
54
55
// Check feature flags
56
if (sails.config.myapp?.featureFlags?.newUI) {
57
console.log('New UI enabled');
58
}
59
60
// Access hook configurations
61
console.log('Blueprint settings:', sails.config.blueprints);
62
console.log('Security settings:', sails.config.security);
63
```
64
65
## Configuration Sources
66
67
### Environment Variables
68
69
Environment variables with the `SAILS_` prefix are automatically parsed using `rttc.parseHuman`:
70
71
```bash
72
# Basic configuration
73
export SAILS_PORT=3000
74
export SAILS_ENVIRONMENT=production
75
76
# Nested configuration (use double underscores for nesting)
77
export SAILS_LOG__LEVEL=verbose
78
export SAILS_MODELS__MIGRATE=drop
79
export SAILS_DATASTORES__DEFAULT__URL=mysql://user:pass@host:3306/db
80
81
# Array configuration
82
export SAILS_CORS__ALLOW_ORIGINS='["https://app.com", "https://admin.com"]'
83
84
# Boolean configuration
85
export SAILS_BLUEPRINTS__REST=true
86
export SAILS_SECURITY__CSRF=false
87
```
88
89
**Environment Variable Parsing Examples**:
90
```javascript
91
// SAILS_PORT=3000 → config.port = 3000 (number)
92
// SAILS_LOG__LEVEL=verbose → config.log.level = 'verbose' (string)
93
// SAILS_MODELS__MIGRATE=drop → config.models.migrate = 'drop'
94
// SAILS_CORS__ALLOW_ORIGINS='["https://app.com"]' → config.cors.allowOrigins = ['https://app.com']
95
// SAILS_BLUEPRINTS__REST=true → config.blueprints.rest = true (boolean)
96
```
97
98
### .sailsrc Files
99
100
JSON configuration files loaded automatically:
101
102
**Local .sailsrc** (project directory):
103
```json
104
{
105
"port": 1337,
106
"environment": "development",
107
"log": {
108
"level": "verbose"
109
},
110
"models": {
111
"migrate": "alter"
112
},
113
"datastores": {
114
"default": {
115
"adapter": "sails-mysql",
116
"host": "localhost",
117
"port": 3306,
118
"user": "root",
119
"database": "myapp_dev"
120
}
121
}
122
}
123
```
124
125
**Global .sailsrc** (home directory):
126
```json
127
{
128
"generators": {
129
"modules": {}
130
},
131
"commands": {
132
"generate": {
133
"templatesDirectory": "~/.sails-templates"
134
}
135
}
136
}
137
```
138
139
### Command-Line Arguments
140
141
Configuration via command-line arguments using `minimist`:
142
143
```bash
144
# Basic arguments
145
sails lift --port=4000 --environment=staging
146
147
# Nested arguments
148
sails lift --log.level=silly --models.migrate=safe
149
150
# Boolean flags
151
sails lift --prod --verbose
152
153
# Array arguments
154
sails lift --cors.allowOrigins=https://app.com,https://admin.com
155
```
156
157
**Argument Parsing**:
158
```javascript
159
// --port=4000 → config.port = 4000
160
// --log.level=silly → config.log.level = 'silly'
161
// --prod → config.environment = 'production'
162
// --verbose → config.log.level = 'verbose'
163
```
164
165
## Configuration Files
166
167
Sails applications use configuration files in the `config/` directory:
168
169
### Core Configuration Files
170
171
**config/env/development.js**:
172
```javascript
173
module.exports = {
174
port: 1337,
175
176
models: {
177
migrate: 'alter'
178
},
179
180
datastores: {
181
default: {
182
adapter: 'sails-mysql',
183
host: 'localhost',
184
user: 'root',
185
password: '',
186
database: 'myapp_dev'
187
}
188
},
189
190
log: {
191
level: 'verbose'
192
}
193
};
194
```
195
196
**config/env/production.js**:
197
```javascript
198
module.exports = {
199
port: process.env.PORT || 80,
200
201
models: {
202
migrate: 'safe'
203
},
204
205
datastores: {
206
default: {
207
adapter: 'sails-mysql',
208
url: process.env.DATABASE_URL
209
}
210
},
211
212
log: {
213
level: 'error'
214
},
215
216
security: {
217
cors: {
218
allowOrigins: process.env.ALLOWED_ORIGINS?.split(',') || []
219
}
220
},
221
222
session: {
223
secret: process.env.SESSION_SECRET,
224
cookie: {
225
secure: true,
226
maxAge: 24 * 60 * 60 * 1000 // 24 hours
227
}
228
}
229
};
230
```
231
232
### Feature-Specific Configuration
233
234
**config/datastores.js**:
235
```javascript
236
module.exports.datastores = {
237
default: {
238
adapter: 'sails-mysql',
239
host: 'localhost',
240
port: 3306,
241
user: 'myapp',
242
password: 'secret',
243
database: 'myapp'
244
},
245
246
redis: {
247
adapter: 'sails-redis',
248
host: 'localhost',
249
port: 6379,
250
db: 0
251
},
252
253
mongodb: {
254
adapter: 'sails-mongo',
255
url: 'mongodb://localhost:27017/myapp'
256
}
257
};
258
```
259
260
**config/routes.js**:
261
```javascript
262
module.exports.routes = {
263
// Static routes
264
'GET /': 'PageController.home',
265
'GET /about': { view: 'pages/about' },
266
267
// API routes
268
'POST /api/login': 'AuthController.login',
269
'DELETE /api/logout': 'AuthController.logout',
270
271
// RESTful routes
272
'GET /api/users': 'UserController.find',
273
'POST /api/users': 'UserController.create',
274
'GET /api/users/:id': 'UserController.findOne',
275
'PUT /api/users/:id': 'UserController.update',
276
'DELETE /api/users/:id': 'UserController.destroy',
277
278
// Catch-all route
279
'/*': { view: '404', skipAssets: true }
280
};
281
```
282
283
**config/models.js**:
284
```javascript
285
module.exports.models = {
286
// Default datastore
287
datastore: 'default',
288
289
// Migration strategy
290
migrate: 'alter', // 'alter', 'drop', or 'safe'
291
292
// Model settings
293
attributes: {
294
id: { type: 'string', columnName: 'id' },
295
createdAt: { type: 'number', autoCreatedAt: true },
296
updatedAt: { type: 'number', autoUpdatedAt: true }
297
},
298
299
// Validation
300
schema: true
301
};
302
```
303
304
## Hook Configuration
305
306
### HTTP Hook Configuration
307
308
**config/http.js**:
309
```javascript
310
module.exports.http = {
311
port: process.env.PORT || 1337,
312
313
middleware: {
314
order: [
315
'cookieParser',
316
'session',
317
'bodyParser',
318
'compress',
319
'methodOverride',
320
'router',
321
'www',
322
'favicon'
323
],
324
325
// Custom middleware
326
requestLogger: (req, res, next) => {
327
console.log(`${req.method} ${req.url}`);
328
next();
329
},
330
331
// Built-in middleware configuration
332
bodyParser: {
333
urlencoded: { extended: true },
334
json: { limit: '10mb' }
335
}
336
},
337
338
// SSL configuration
339
ssl: {
340
key: require('fs').readFileSync('./ssl/private-key.pem'),
341
cert: require('fs').readFileSync('./ssl/certificate.pem')
342
},
343
344
// Trust proxy
345
trustProxy: true,
346
347
// Static file caching
348
cache: 365.25 * 24 * 60 * 60 * 1000 // 1 year
349
};
350
```
351
352
### Security Configuration
353
354
**config/security.js**:
355
```javascript
356
module.exports.security = {
357
cors: {
358
allRoutes: true,
359
allowOrigins: [
360
'http://localhost:3000',
361
'https://myapp.com',
362
'https://admin.myapp.com'
363
],
364
allowCredentials: false,
365
allowRequestMethods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
366
allowRequestHeaders: 'content-type,authorization'
367
},
368
369
csrf: {
370
grantTokenViaAjax: true,
371
origin: 'https://myapp.com',
372
routesDisabled: ['/api/webhook/*']
373
}
374
};
375
```
376
377
### Blueprints Configuration
378
379
**config/blueprints.js**:
380
```javascript
381
module.exports.blueprints = {
382
// Action routes (e.g. GET /user/find)
383
actions: false,
384
385
// RESTful routes (e.g. GET /user, POST /user)
386
rest: true,
387
388
// Shortcut routes (e.g. GET /user/create?name=John)
389
shortcuts: true,
390
391
// Route prefix
392
prefix: '/api/v1',
393
394
// Pluralize model names in URLs
395
pluralize: true,
396
397
// Auto-subscribe to model changes
398
autoWatch: true,
399
400
// Default limit for find operations
401
defaultLimit: 30
402
};
403
```
404
405
## Custom Configuration
406
407
### Application-Specific Configuration
408
409
**config/custom.js**:
410
```javascript
411
module.exports.custom = {
412
// API keys
413
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
414
sendgridApiKey: process.env.SENDGRID_API_KEY,
415
416
// Feature flags
417
featureFlags: {
418
newUserInterface: process.env.NEW_UI === 'true',
419
betaFeatures: false,
420
maintenanceMode: false
421
},
422
423
// Business logic configuration
424
pagination: {
425
defaultLimit: 25,
426
maxLimit: 100
427
},
428
429
// File upload settings
430
uploads: {
431
maxBytes: 10 * 1024 * 1024, // 10MB
432
allowedTypes: ['image/jpeg', 'image/png', 'image/gif'],
433
uploadPath: './assets/uploads'
434
},
435
436
// Email settings
437
email: {
438
from: 'noreply@myapp.com',
439
templates: {
440
welcome: 'email-welcome',
441
passwordReset: 'email-password-reset'
442
}
443
}
444
};
445
```
446
447
### Environment-Specific Overrides
448
449
**config/env/staging.js**:
450
```javascript
451
module.exports = {
452
// Inherit from production but override specific settings
453
454
log: {
455
level: 'verbose' // More verbose logging for staging
456
},
457
458
models: {
459
migrate: 'alter' // Allow schema changes in staging
460
},
461
462
custom: {
463
featureFlags: {
464
betaFeatures: true // Enable beta features in staging
465
}
466
}
467
};
468
```
469
470
## Configuration Validation
471
472
### Runtime Validation
473
474
```javascript
475
// Validate required configuration at startup
476
module.exports = {
477
// config/bootstrap.js
478
fn: async function() {
479
// Check required environment variables
480
const required = ['DATABASE_URL', 'SESSION_SECRET', 'STRIPE_SECRET_KEY'];
481
const missing = required.filter(key => !process.env[key]);
482
483
if (missing.length > 0) {
484
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
485
}
486
487
// Validate configuration values
488
if (sails.config.custom.pagination.maxLimit > 1000) {
489
throw new Error('Maximum pagination limit cannot exceed 1000');
490
}
491
}
492
};
493
```
494
495
### Configuration Schema
496
497
```javascript
498
// Define configuration schema for validation
499
const configSchema = {
500
port: { type: 'number', min: 1, max: 65535 },
501
environment: { type: 'string', isIn: ['development', 'staging', 'production'] },
502
log: {
503
type: 'dictionary',
504
properties: {
505
level: { type: 'string', isIn: ['silly', 'verbose', 'info', 'warn', 'error', 'silent'] }
506
}
507
}
508
};
509
510
// Validate configuration
511
const rttc = require('rttc');
512
try {
513
rttc.validate(configSchema, sails.config);
514
console.log('Configuration is valid');
515
} catch (err) {
516
console.error('Configuration validation failed:', err);
517
}
518
```
519
520
## Configuration Best Practices
521
522
### Development Configuration
523
524
```javascript
525
// Use local environment for development
526
module.exports = {
527
port: 1337,
528
environment: 'development',
529
530
// Detailed logging
531
log: { level: 'verbose' },
532
533
// Schema migration
534
models: { migrate: 'alter' },
535
536
// Local database
537
datastores: {
538
default: {
539
adapter: 'sails-disk' // File-based for development
540
}
541
},
542
543
// Development-friendly settings
544
blueprints: {
545
shortcuts: true,
546
rest: true
547
}
548
};
549
```
550
551
### Production Configuration
552
553
```javascript
554
// Secure production configuration
555
module.exports = {
556
port: process.env.PORT || 80,
557
environment: 'production',
558
559
// Minimal logging
560
log: { level: 'error' },
561
562
// Safe database migration
563
models: { migrate: 'safe' },
564
565
// Production database
566
datastores: {
567
default: {
568
adapter: 'sails-mysql',
569
url: process.env.DATABASE_URL,
570
ssl: true
571
}
572
},
573
574
// Security settings
575
security: {
576
cors: {
577
allowOrigins: process.env.ALLOWED_ORIGINS.split(',')
578
}
579
},
580
581
// Disable development features
582
blueprints: {
583
shortcuts: false
584
}
585
};
586
```
587
588
The Sails.js configuration system provides comprehensive flexibility for managing application settings across different environments, with multiple configuration sources, runtime access, and validation capabilities.