{"id":17214,"library":"embedded-postgres","title":"Node.js Embedded PostgreSQL","description":"Embedded Postgres is a Node.js package designed to programmatically spawn and manage PostgreSQL database clusters directly within your application runtime. It simplifies local development, testing, and CI/CD pipelines by eliminating the need for pre-installed PostgreSQL instances. The package, currently in beta (version 18.3.0-beta.17), abstracts away the complexities of PostgreSQL binary management by leveraging `zonkyio/embedded-postgres-binaries` and tracking PostgreSQL's official support policy. This means new PostgreSQL major versions are typically supported annually, with minor bug and security fixes integrated quarterly. Key differentiators include its ability to fully manage the PostgreSQL lifecycle (initialization, start, stop, create/drop databases), provide direct access to a `node-postgres` client, and offer configurable persistence, making it a robust solution for environments requiring ephemeral or managed PostgreSQL instances.","status":"active","version":"18.3.0-beta.17","language":"javascript","source_language":"en","source_url":"https://github.com/leinelissen/embedded-postgres","tags":["javascript","postgres","postgresql","database","embedded"],"install":[{"cmd":"npm install embedded-postgres","lang":"bash","label":"npm"},{"cmd":"yarn add embedded-postgres","lang":"bash","label":"yarn"},{"cmd":"pnpm add embedded-postgres","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library is designed for ESM environments and ships with TypeScript definitions. While CommonJS `require` might work in some setups, the recommended approach is ESM `import`.","wrong":"const EmbeddedPostgres = require('embedded-postgres');","symbol":"EmbeddedPostgres","correct":"import EmbeddedPostgres from 'embedded-postgres';"},{"note":"Import the type for constructor options for better type safety in TypeScript projects.","symbol":"EmbeddedPostgresOptions","correct":"import type { EmbeddedPostgresOptions } from 'embedded-postgres';"}],"quickstart":{"code":"import EmbeddedPostgres from 'embedded-postgres';\n\nasync function main() {\n    // Create the object with custom options for data directory, user, password, port, and persistence.\n    const pg = new EmbeddedPostgres({\n        databaseDir: './data/db',\n        user: 'testuser',\n        password: 'testpassword',\n        port: 5433, // Use a non-default port to avoid conflicts\n        persistent: true,\n    });\n\n    try {\n        // Create the cluster configuration files and data directory.\n        await pg.initialise();\n\n        // Start the PostgreSQL server process.\n        await pg.start();\n\n        // Create a new database named 'MYAPP_DB'.\n        await pg.createDatabase('MYAPP_DB');\n\n        // Initialize a node-postgres client using the embedded instance's connection details.\n        const client = pg.getPgClient();\n        await client.connect();\n\n        // Execute a simple query to verify connection and functionality.\n        const result = await client.query('SELECT current_database(), current_user, pg_backend_pid() AS pid;');\n        console.log('PostgreSQL server started and connected successfully.');\n        console.log('Connected to database:', result.rows[0].current_database);\n        console.log('Current user:', result.rows[0].current_user);\n        console.log('Backend PID:', result.rows[0].pid);\n        \n        // Example: Create a table and insert data\n        await client.query('CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(255));');\n        await client.query(\"INSERT INTO users (name) VALUES ('Alice'), ('Bob');\");\n        const users = await client.query('SELECT * FROM users;');\n        console.log('Users:', users.rows);\n\n        // Drop the created database, cleaning up.\n        await pg.dropDatabase('MYAPP_DB');\n\n    } catch (error) {\n        console.error('An error occurred:', error);\n    } finally {\n        // Ensure the server is stopped, even if errors occur.\n        await pg.stop();\n        console.log('PostgreSQL server stopped.');\n    }\n}\n\nmain();\n","lang":"typescript","description":"This quickstart demonstrates the full lifecycle of an embedded PostgreSQL instance, including initialization, starting the server, creating and dropping a database, connecting with a `node-postgres` client to perform queries, and properly stopping the server."},"warnings":[{"fix":"For PNPM, run `pnpm approve-builds` after installation. For other environments, ensure `ignore-scripts` is not enabled in your npm/yarn configuration, or explicitly enable script execution.","message":"The package requires post-install scripts to generate necessary symlinks for PostgreSQL operation. If you have post-install scripts disabled (e.g., when using PNPM with strict settings or in certain CI/CD environments), you will need to manually approve or enable them, or the package will not function correctly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Consult the project's GitHub releases and changelog for detailed information on API changes between versions. Pin to specific beta versions if necessary, but prepare for potential refactoring when upgrading to stable releases.","message":"The package version `18.3.0-beta.17` indicates a beta release. API stability is not guaranteed, and breaking changes might occur in subsequent beta or stable releases. Users should exercise caution when deploying beta versions in production and monitor release notes for changes.","severity":"breaking","affected_versions":">=18.3.0-beta.0"},{"fix":"Refer to the 'PostgreSQL Versions' matrix in the documentation to verify compatibility for your desired PostgreSQL version and target platform/architecture. If an older version is required on a newer architecture, consider upgrading the PostgreSQL version.","message":"PostgreSQL binaries have specific platform and architecture support. Older PostgreSQL versions might not be available for all combinations (e.g., Darwin arm64 for PostgreSQL versions prior to 15.x). Attempting to use an unsupported combination will lead to installation or startup failures.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Configure your Dockerfile or runtime environment to use a non-root user (e.g., `USER node`) to execute your application and the embedded PostgreSQL instance. Alternatively, for development, you might be able to use `--privileged` with Docker, but this is not recommended for production.","message":"PostgreSQL, by design, cannot be run by the root user due to security considerations. In environments like Docker containers where applications often run as root by default, this can prevent the embedded database from starting.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure post-install scripts are enabled (e.g., `pnpm approve-builds`). Verify that the process running `embedded-postgres` is not `root`. Check system logs for more specific `initdb` errors.","cause":"The PostgreSQL `initdb` command failed during initialization, often due to missing symlinks or incorrect permissions, which can be caused by disabled post-install scripts or running as the root user.","error":"Error: Command failed with exit code 1: initdb ..."},{"fix":"Ensure the post-install script ran successfully. If the issue persists, you might need to manually add the directory containing `libpq.so.5` (usually `<databaseDir>/bin` or `<databaseDir>/lib`) to your system's dynamic linker search path (e.g., via `/etc/ld.so.conf.d/`).","cause":"This error typically occurs on Linux systems when the dynamic linker cannot find the `libpq.so.5` shared library, which is part of the PostgreSQL binaries. It means the library path is not correctly configured or the binaries were not extracted properly.","error":"Error: libpq.so.5: cannot open shared object file: No such file or directory"},{"fix":"Check the console output for any errors during `pg.start()` or `pg.initialise()`. Verify that the `port` option in `EmbeddedPostgres` constructor matches the one the client is trying to connect to. Ensure the server has enough time to start before the client attempts connection.","cause":"The Node.js `node-postgres` client attempted to connect to the PostgreSQL server but was refused. This indicates the embedded PostgreSQL server either failed to start, is not listening on the expected port, or was already stopped.","error":"Error: connect ECONNREFUSED 127.0.0.1:<port>"}],"ecosystem":"npm","meta_description":null}