{"id":17522,"library":"can-connect","title":"Can-Connect Data Middleware","description":"Can-Connect is a JavaScript library providing a flexible, framework-agnostic middleware layer for managing persisted data. It allows developers to compose various behaviors to create powerful model layers, abstracting data access from underlying sources like REST APIs, WebSockets, or local storage. The current stable version is 4.0.6, with recent releases including maintenance patches for both the v3 and v4 series, indicating active development. Its core differentiator lies in its highly modular, behavior-driven architecture, enabling custom data handling logic to be assembled and reused, making it suitable for complex data interaction patterns across any JavaScript environment, not just the CanJS ecosystem.","status":"active","version":"4.0.6","language":"javascript","source_language":"en","source_url":"https://github.com/canjs/can-connect","tags":["javascript","CanJS"],"install":[{"cmd":"npm install can-connect","lang":"bash","label":"npm"},{"cmd":"yarn add can-connect","lang":"bash","label":"yarn"},{"cmd":"pnpm add can-connect","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary function to compose connection behaviors. ESM imports are standard for v4+.","wrong":"const connect = require('can-connect');","symbol":"connect","correct":"import { connect } from 'can-connect';"},{"note":"A common behavior for creating RESTful data connections. Specific behavior paths like 'can-connect/data/url' were common in older versions, but named exports from the root are preferred in v4+.","wrong":"import dataUrl from 'can-connect/data/url';","symbol":"dataUrl","correct":"import { dataUrl } from 'can-connect';"},{"note":"A behavior that provides methods for creating, updating, and deleting instances (constructorStore, constructor-hydrate, etc.). Named exports from the root are standard.","wrong":"import Constructor from 'can-connect/constructor';","symbol":"constructor","correct":"import { constructor } from 'can-connect';"}],"quickstart":{"code":"import { connect, dataUrl, constructor } from 'can-connect';\n\n// Mock global fetch for demonstration purposes\nglobal.fetch = async (url, options) => {\n  console.log(`Mock fetch: ${options?.method || 'GET'} ${url}`);\n  if (url === '/api/todos' && options?.method === 'GET') {\n    return {\n      json: async () => ([\n        { _id: '1', title: 'Buy milk' },\n        { _id: '2', title: 'Walk dog' }\n      ]),\n      status: 200\n    };\n  }\n  if (url.startsWith('/api/todos/') && options?.method === 'GET') {\n    const id = url.split('/').pop();\n    return {\n      json: async () => ({ _id: id, title: `Todo ${id}` }),\n      status: 200\n    };\n  }\n  return { json: async () => ({}), status: 200 };\n};\n\nconst TodoConnection = connect([\n  dataUrl('/api/todos'), // Defines how to fetch data from a URL\n  constructor(),         // Provides methods for creating, updating, deleting instances\n  {\n    name: 'todos',\n    // Custom behaviors or overrides can be added here\n    getListData() {\n      console.log('Custom getListData called...');\n      return this._super(); // Call the base dataUrl behavior's getListData\n    },\n    getData(id) {\n      console.log(`Custom getData for ID: ${id} called...`);\n      return this._super(id); // Call the base dataUrl behavior's getData\n    }\n  }\n], {\n  // Connection options\n  idProp: '_id' // Specify the ID property, default is 'id'\n});\n\nasync function run() {\n  try {\n    console.log('Fetching all todos...');\n    const todos = await TodoConnection.getList({});\n    console.log('Retrieved Todos:', todos);\n\n    console.log('\\nFetching todo with ID 1...');\n    const todo1 = await TodoConnection.get('1');\n    console.log('Retrieved Todo 1:', todo1);\n\n  } catch (error) {\n    console.error('Operation failed:', error.message);\n  }\n}\n\nrun();","lang":"javascript","description":"This quickstart demonstrates how to define a data connection using `can-connect` by composing various behaviors like `dataUrl` for RESTful interaction and `constructor` for instance management. It showcases fetching a list and a single item from a mock API."},"warnings":[{"fix":"Migrate usage to `can-connect-tag` by installing it separately (`npm install can-connect-tag`) and updating import paths.","message":"The `can-connect/tag/` module has been removed in v4.0.0 and moved to its own repository, `can-connect-tag`. Direct imports from `can-connect/tag/` will now fail.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Upgrade to v4.0.5 or newer. Ensure data objects consistently include properties expected by the connection's `idProp`.","message":"Prior to v4.0.5, hydrating Map types without a `props` object could lead to errors related to `connection.id`. Ensure objects passed for hydration have expected properties, especially for ID retrieval.","severity":"gotcha","affected_versions":"<4.0.5"},{"fix":"Upgrade to v3.2.6 (for 3.x series) or v4.0.1 (for 4.x series) or newer to ensure compatibility with various bundlers.","message":"Versions prior to v3.2.6 and v4.0.1 experienced issues with production builds when using non-StealJS bundlers, potentially causing build failures or incorrect output.","severity":"gotcha","affected_versions":"<3.2.6 || >3.x.x <4.0.1"},{"fix":"Directly import `can-util` if your application explicitly uses its utilities; otherwise, ensure your code no longer implicitly relies on its presence via `can-connect`.","message":"The `can-util` dependency was removed in v3.2.3. If your application indirectly relied on `can-util` exports through `can-connect`, this change might break existing functionality.","severity":"gotcha","affected_versions":">=3.2.3"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Install `can-connect-tag` separately via `npm install can-connect-tag` and update your import statements to point to the new package.","cause":"Attempting to import from `can-connect/tag/` after upgrading to v4.0.0, where this module was removed.","error":"Error: Cannot find module 'can-connect/tag/'"},{"fix":"Ensure you are using `import { connect } from 'can-connect';` for ESM environments and `const { connect } = require('can-connect');` if using CommonJS (though ESM is preferred for v4+).","cause":"This error often occurs in bundlers (like Webpack) when mixing CommonJS `require()` with ESM `import`, or when attempting to destructure a named export that doesn't exist or isn't properly aliased.","error":"TypeError: (0 , can_connect__WEBPACK_IMPORTED_MODULE_0__.connect) is not a function"},{"fix":"Verify that your data consistently includes the ID property defined by `idProp` (defaulting to 'id'). Consider upgrading to `can-connect@4.0.5` or newer for improved handling of missing `props` objects during hydration.","cause":"A data object being processed by `can-connect` (e.g., in a `constructor-hydrate` behavior) is missing the property designated as the ID, or the `idProp` option is misconfigured, especially for Map types.","error":"TypeError: Cannot read properties of undefined (reading 'id') during data hydration"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}