express-slonik provides an Express.js middleware for managing PostgreSQL transactions using the Slonik client library. It simplifies the integration of database transactions into Express route handlers, ensuring that all database operations within a request either commit successfully or roll back entirely. The current stable version is 3.2.0, released in October 2023. The project maintains a frequent release cadence, primarily to align with new major versions of its peer dependency, Slonik, adding support for recent Slonik versions shortly after their release. Its key differentiator is its zero-dependency approach (beyond Express and Slonik itself) and its focus on robust transaction management within the Express middleware pattern, including support for isolation levels and explicit transaction control across multiple handlers.
npm install express-slonikVerified import paths — ran on the pinned version, not inferred.
This example demonstrates basic usage, setting up an Express application with Slonik, initializing express-slonik middleware, and handling a GET request within a database transaction.
Ensure your project's `slonik` dependency is at version `33.x.x` or higher when upgrading to `express-slonik` v3.x.x. Specifically, peer dependency `slonik` should be `>=33.0.0 <38.0.0` for `express-slonik@3.2.0`.
Upgrade your `slonik` dependency to version `30.x.x` or higher before upgrading to `express-slonik` v2.x.x.
Ensure `express-slonik` middleware is placed appropriately in your Express middleware chain so that `transaction.begin()` runs before route handlers that need `req.transaction`, and no subsequent middleware overwrites `req.transaction`.
For explicit control, always include `transaction.end()` after your route logic. Implement robust error handling (`try-catch`) to manage transaction outcomes precisely, especially for non-critical errors that shouldn't roll back the entire transaction.
Ensure `transaction.begin()` is used before the route handler that accesses `req.transaction`. Verify `slonik` is installed and meets the `express-slonik` peer dependency requirements (e.g., `npm ls slonik` or `yarn why slonik`).
Upgrade your `slonik` dependency to a compatible version, e.g., `npm install slonik@^37` or `yarn add slonik@^37`.
Either change your file to use CommonJS `require()` syntax (`const createMiddleware = require('express-slonik').default;`) or configure your project to use ES Modules by adding `"type": "module"` to your `package.json` and using `.mjs` file extensions if necessary.