Node.js Embedded PostgreSQL

18.3.0-beta.17 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import EmbeddedPostgres from 'embedded-postgres';

async function main() {
    // Create the object with custom options for data directory, user, password, port, and persistence.
    const pg = new EmbeddedPostgres({
        databaseDir: './data/db',
        user: 'testuser',
        password: 'testpassword',
        port: 5433, // Use a non-default port to avoid conflicts
        persistent: true,
    });

    try {
        // Create the cluster configuration files and data directory.
        await pg.initialise();

        // Start the PostgreSQL server process.
        await pg.start();

        // Create a new database named 'MYAPP_DB'.
        await pg.createDatabase('MYAPP_DB');

        // Initialize a node-postgres client using the embedded instance's connection details.
        const client = pg.getPgClient();
        await client.connect();

        // Execute a simple query to verify connection and functionality.
        const result = await client.query('SELECT current_database(), current_user, pg_backend_pid() AS pid;');
        console.log('PostgreSQL server started and connected successfully.');
        console.log('Connected to database:', result.rows[0].current_database);
        console.log('Current user:', result.rows[0].current_user);
        console.log('Backend PID:', result.rows[0].pid);
        
        // Example: Create a table and insert data
        await client.query('CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(255));');
        await client.query("INSERT INTO users (name) VALUES ('Alice'), ('Bob');");
        const users = await client.query('SELECT * FROM users;');
        console.log('Users:', users.rows);

        // Drop the created database, cleaning up.
        await pg.dropDatabase('MYAPP_DB');

    } catch (error) {
        console.error('An error occurred:', error);
    } finally {
        // Ensure the server is stopped, even if errors occur.
        await pg.stop();
        console.log('PostgreSQL server stopped.');
    }
}

main();

view raw JSON →