To integrate Backbone.js with a JSON:API server, you must bridge the gap between Backbone's expected flat JSON structure and JSON:API's nested document format. This requires overriding the sync method for outgoing data and the parse method for incoming de-serialization.
1. Extracting Data and Relationships
p>The most robust pattern for extracting data is to implement a collection-level
parse method. JSON:API returns resources within a
data envelope and separates related entities into
relationships and
included keys. You must manually map these to a format Backbone models can consume.
- Iterate through the
response.data array to create primary models.
- Use the
response.included array to populate a cache of related models by ID to avoid duplication.
- Map the
relationships object to model attributes as IDs or references, depending on your architecture's needs.
2. Custom Sync and Auth Headers
To add authentication headers without breaking optimistic UI behavior, override the sync method at the Base Model or Collection level. By intercepting the options object before it reaches the server, you can inject headers without interfering with the internal state logic.
MyCollection.sync = function(method, model, options) {
options.headers = options.headers || {};
options.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token');
options.headers['Content-Type'] = 'application/vnd.api+json';
// Wrap data in JSON:API format
const payload = {
data: {
type: this.model,
id: model.id,
attributes: model.toJSON()
}
};
return Backbone.sync.apply(this, method, model, options);
}
Handling Parse Errors
Overriding parse at the collection level can mask per-model errors if the logic uses a generic try-catch block. To surface these errors:
- Implement individual model-level
parse methods to validate specific attributes.
- Have the collection-level
parse aggregate errors or trigger a custom event when validation fails.
- Listen for the
error event in your views to ensure the UI reflects specific model failures.
Note: This strategy assumes Backbone 1.3.5+. If using 1.4.0+, ensure your event listeners account for the updated event signatures where the model is passed as the second argument in collection-related events.