or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

attachments.mdbulk-queries.mdchanges-events.mddatabase-operations.mdindex.mdreplication-sync.md

replication-sync.mddocs/

0

# Replication & Synchronization

1

2

PouchDB's replication system provides comprehensive data synchronization between local and remote databases. It supports both one-way replication and bidirectional sync with extensive configuration options, conflict resolution, filtering capabilities, and robust error handling.

3

4

## Capabilities

5

6

### Static Replication Methods

7

8

#### PouchDB.replicate()

9

10

Replicates data from a source database to a target database using the static method.

11

12

```javascript { .api }

13

/**

14

* Replicate from source to target database

15

* @param source - Source database (PouchDB instance or URL string)

16

* @param target - Target database (PouchDB instance or URL string)

17

* @param options - Replication configuration options

18

* @param callback - Optional callback function (err, result) => void

19

* @returns Replication object with event emitter interface

20

*/

21

PouchDB.replicate(source, target, options, callback);

22

```

23

24

**Usage Examples:**

25

26

```javascript

27

// Basic replication

28

const replication = PouchDB.replicate('local-db', 'https://example.com/remote-db');

29

30

// Continuous replication with options

31

const replication = PouchDB.replicate(localDB, remoteDB, {

32

live: true,

33

retry: true,

34

batch_size: 100

35

});

36

37

// One-time replication with callback

38

PouchDB.replicate(sourceDB, targetDB, {

39

filter: 'myfilter/active-docs'

40

}, (err, result) => {

41

if (err) {

42

console.error('Replication failed:', err);

43

} else {

44

console.log('Replication completed:', result);

45

}

46

});

47

```

48

49

#### PouchDB.sync()

50

51

Performs bidirectional synchronization between two databases using the static method.

52

53

```javascript { .api }

54

/**

55

* Bidirectional sync between two databases

56

* @param source - First database (PouchDB instance or URL string)

57

* @param target - Second database (PouchDB instance or URL string)

58

* @param options - Sync configuration options

59

* @param callback - Optional callback function (err, result) => void

60

* @returns Sync object with event emitter interface

61

*/

62

PouchDB.sync(source, target, options, callback);

63

```

64

65

**Usage Examples:**

66

67

```javascript

68

// Basic bidirectional sync

69

const sync = PouchDB.sync(localDB, remoteDB);

70

71

// Continuous sync with custom options

72

const sync = PouchDB.sync(localDB, 'https://example.com/db', {

73

live: true,

74

retry: true,

75

push: { batch_size: 50 },

76

pull: { batch_size: 100 }

77

});

78

79

// Sync with separate push/pull configuration

80

const sync = PouchDB.sync(localDB, remoteDB, {

81

push: {

82

filter: 'myfilter/outgoing',

83

live: true

84

},

85

pull: {

86

filter: 'myfilter/incoming',

87

live: true

88

}

89

});

90

```

91

92

### Instance Replication Methods

93

94

#### db.replicate.to()

95

96

Replicates from the current database instance to a target database.

97

98

```javascript { .api }

99

/**

100

* Replicate this database to target

101

* @param target - Target database (PouchDB instance or URL string)

102

* @param options - Replication configuration options

103

* @param callback - Optional callback function (err, result) => void

104

* @returns Replication object with event emitter interface

105

*/

106

db.replicate.to(target, options, callback);

107

```

108

109

**Usage Examples:**

110

111

```javascript

112

// Push local changes to remote

113

const replication = localDB.replicate.to(remoteDB, {

114

live: true,

115

retry: true

116

});

117

118

// Filtered push replication

119

const replication = localDB.replicate.to('https://example.com/db', {

120

filter: (doc) => doc.type === 'public',

121

live: true

122

});

123

```

124

125

#### db.replicate.from()

126

127

Replicates from a source database to the current database instance.

128

129

```javascript { .api }

130

/**

131

* Replicate from source to this database

132

* @param source - Source database (PouchDB instance or URL string)

133

* @param options - Replication configuration options

134

* @param callback - Optional callback function (err, result) => void

135

* @returns Replication object with event emitter interface

136

*/

137

db.replicate.from(source, options, callback);

138

```

139

140

**Usage Examples:**

141

142

```javascript

143

// Pull remote changes to local

144

const replication = localDB.replicate.from(remoteDB, {

145

live: true,

146

retry: true

147

});

148

149

// Pull specific documents

150

const replication = localDB.replicate.from('https://example.com/db', {

151

doc_ids: ['doc1', 'doc2', 'doc3']

152

});

153

```

154

155

#### db.sync()

156

157

Performs bidirectional synchronization between the current database instance and a target database.

158

159

```javascript { .api }

160

/**

161

* Bidirectional sync with target database

162

* @param target - Target database (PouchDB instance or URL string)

163

* @param options - Sync configuration options

164

* @param callback - Optional callback function (err, result) => void

165

* @returns Sync object with event emitter interface

166

*/

167

db.sync(target, options, callback);

168

```

169

170

**Usage Examples:**

171

172

```javascript

173

// Basic sync

174

const sync = localDB.sync(remoteDB);

175

176

// Continuous sync with error handling

177

const sync = localDB.sync('https://example.com/db', {

178

live: true,

179

retry: true

180

});

181

182

sync.on('error', (err) => {

183

console.error('Sync error:', err);

184

});

185

```

186

187

## Replication Events

188

189

All replication and sync objects emit events that can be listened to for monitoring progress and handling errors.

190

191

### Event Types

192

193

```javascript { .api }

194

/**

195

* Replication change event - fired when documents are replicated

196

* @param info - Change information object

197

*/

198

replication.on('change', (info) => {

199

// info.direction: 'push' | 'pull' (for sync operations)

200

// info.change.docs: array of changed documents

201

// info.change.docs_read: number of documents read

202

// info.change.docs_written: number of documents written

203

});

204

205

/**

206

* Replication complete event - fired when replication finishes

207

* @param info - Completion information object

208

*/

209

replication.on('complete', (info) => {

210

// info.ok: boolean indicating success

211

// info.start_time: replication start timestamp

212

// info.end_time: replication end timestamp

213

// info.docs_read: total documents read

214

// info.docs_written: total documents written

215

});

216

217

/**

218

* Replication error event - fired when replication encounters an error

219

* @param err - Error object

220

*/

221

replication.on('error', (err) => {

222

// err.status: HTTP status code (if applicable)

223

// err.name: error name

224

// err.message: error message

225

});

226

227

/**

228

* Replication denied event - fired when document replication is denied

229

* @param err - Denial information

230

*/

231

replication.on('denied', (err) => {

232

// err.id: document ID that was denied

233

// err.reason: reason for denial

234

});

235

236

/**

237

* Replication active event - fired when replication becomes active

238

*/

239

replication.on('active', () => {

240

// Replication is actively transferring data

241

});

242

243

/**

244

* Replication paused event - fired when replication is paused

245

* @param err - Error that caused pause (if any)

246

*/

247

replication.on('paused', (err) => {

248

// Replication has been paused (may resume automatically with retry: true)

249

});

250

```

251

252

### Event Handling Examples

253

254

```javascript

255

const replication = PouchDB.replicate(localDB, remoteDB, {

256

live: true,

257

retry: true

258

});

259

260

// Track replication progress

261

replication.on('change', (info) => {

262

console.log(`Replicated ${info.change.docs_written} documents`);

263

info.change.docs.forEach((doc) => {

264

console.log(`Document updated: ${doc._id}`);

265

});

266

});

267

268

// Handle completion

269

replication.on('complete', (info) => {

270

console.log('Replication completed successfully');

271

console.log(`Total documents: ${info.docs_written}`);

272

});

273

274

// Handle errors

275

replication.on('error', (err) => {

276

console.error('Replication error:', err);

277

if (err.status === 401) {

278

console.error('Authentication required');

279

}

280

});

281

282

// Monitor active/paused status

283

replication.on('active', () => {

284

console.log('Replication is active');

285

});

286

287

replication.on('paused', (err) => {

288

if (err) {

289

console.log('Replication paused due to error:', err);

290

} else {

291

console.log('Replication paused');

292

}

293

});

294

```

295

296

## Replication Control

297

298

### Canceling Replication

299

300

```javascript { .api }

301

/**

302

* Cancel an ongoing replication

303

*/

304

replication.cancel();

305

```

306

307

**Usage Example:**

308

309

```javascript

310

const replication = PouchDB.replicate(localDB, remoteDB, { live: true });

311

312

// Cancel after 30 seconds

313

setTimeout(() => {

314

replication.cancel();

315

console.log('Replication canceled');

316

}, 30000);

317

```

318

319

### Replication Status

320

321

```javascript

322

// Check if replication is cancelled

323

if (replication.cancelled) {

324

console.log('Replication has been cancelled');

325

}

326

```

327

328

## Configuration Options

329

330

### Core Replication Options

331

332

```javascript { .api }

333

interface ReplicationOptions {

334

/** Enable continuous replication that stays open and listens for changes */

335

live?: boolean;

336

337

/** Automatically retry replication on failure */

338

retry?: boolean;

339

340

/** Number of documents to process in each batch */

341

batch_size?: number;

342

343

/** Maximum number of concurrent batches */

344

batches_limit?: number;

345

346

/** Use checkpoints to resume interrupted replications */

347

checkpoint?: boolean;

348

349

/** Filter function or design document filter name */

350

filter?: string | ((doc: any, params: any) => boolean);

351

352

/** Array of specific document IDs to replicate */

353

doc_ids?: string[];

354

355

/** Parameters to pass to filter functions */

356

query_params?: { [key: string]: any };

357

358

/** Include or exclude document conflicts */

359

style?: 'main_only' | 'all_docs';

360

361

/** Authentication credentials */

362

auth?: {

363

username: string;

364

password: string;

365

};

366

367

/** Custom headers for HTTP requests */

368

headers?: { [key: string]: string };

369

370

/** HTTP timeout in milliseconds */

371

timeout?: number;

372

373

/** Heartbeat interval for continuous replication */

374

heartbeat?: number;

375

}

376

```

377

378

### Sync-Specific Options

379

380

```javascript { .api }

381

interface SyncOptions extends ReplicationOptions {

382

/** Separate options for push replication */

383

push?: ReplicationOptions;

384

385

/** Separate options for pull replication */

386

pull?: ReplicationOptions;

387

}

388

```

389

390

### Advanced Configuration Examples

391

392

```javascript

393

// Filtered replication with custom function

394

const replication = PouchDB.replicate(localDB, remoteDB, {

395

live: true,

396

filter: (doc) => {

397

// Only replicate documents modified in last 24 hours

398

const dayAgo = Date.now() - (24 * 60 * 60 * 1000);

399

return new Date(doc.modified).getTime() > dayAgo;

400

}

401

});

402

403

// Replication with authentication and custom headers

404

const replication = PouchDB.replicate(localDB, 'https://example.com/db', {

405

auth: {

406

username: 'myuser',

407

password: 'mypassword'

408

},

409

headers: {

410

'Custom-Header': 'custom-value'

411

},

412

timeout: 30000,

413

batch_size: 50

414

});

415

416

// Asymmetric sync with different push/pull settings

417

const sync = PouchDB.sync(localDB, remoteDB, {

418

push: {

419

filter: 'myfilter/outgoing',

420

batch_size: 25

421

},

422

pull: {

423

filter: 'myfilter/incoming',

424

batch_size: 100

425

},

426

live: true,

427

retry: true

428

});

429

```

430

431

## Error Handling

432

433

### Common Error Types

434

435

```javascript { .api }

436

interface ReplicationError {

437

/** HTTP status code (if applicable) */

438

status?: number;

439

440

/** Error name/type */

441

name: string;

442

443

/** Human-readable error message */

444

message: string;

445

446

/** Detailed error information */

447

error?: any;

448

449

/** Error reason/cause */

450

reason?: string;

451

}

452

```

453

454

### Error Handling Patterns

455

456

```javascript

457

const replication = PouchDB.replicate(localDB, remoteDB, {

458

live: true,

459

retry: true

460

});

461

462

replication.on('error', (err) => {

463

switch (err.status) {

464

case 401:

465

console.error('Authentication failed');

466

// Handle authentication error

467

break;

468

case 404:

469

console.error('Database not found');

470

// Handle missing database

471

break;

472

case 409:

473

console.error('Conflict occurred');

474

// Handle conflict

475

break;

476

default:

477

console.error('Replication error:', err.message);

478

// Handle other errors

479

}

480

});

481

482

// Network error handling

483

replication.on('paused', (err) => {

484

if (err) {

485

console.log('Replication paused due to error, will retry...');

486

// Replication will automatically retry if retry: true

487

}

488

});

489

```

490

491

## Performance Considerations

492

493

### Optimizing Replication Performance

494

495

```javascript

496

// Optimize for throughput

497

const replication = PouchDB.replicate(localDB, remoteDB, {

498

batch_size: 500, // Larger batches for better throughput

499

batches_limit: 10, // More concurrent batches

500

live: true,

501

retry: true

502

});

503

504

// Optimize for responsiveness

505

const replication = PouchDB.replicate(localDB, remoteDB, {

506

batch_size: 50, // Smaller batches for quicker updates

507

batches_limit: 5, // Fewer concurrent batches

508

heartbeat: 10000, // More frequent heartbeats

509

live: true

510

});

511

512

// Memory-conscious replication

513

const replication = PouchDB.replicate(localDB, remoteDB, {

514

batch_size: 100,

515

batches_limit: 2, // Limit memory usage

516

live: true,

517

retry: true

518

});

519

```