Start a Postgres server for local development while using Vite's serve mode
https://github.com/aleclarson/vite-postgres.git
Vite dev-only plugin that bootstraps and runs a local PostgreSQL server for your app.
vite dev only (apply: 'serve')initdb, postgres, createdb, pg_isready)pnpm add -D vite-postgres
vite.config.ts
import { defineConfig } from 'vite'
import postgres from 'vite-postgres'
export default defineConfig({
plugins: [
postgres({
// dbPath: '.postgres', // persist in-repo (optional)
// dbName: 'myapp', // defaults to Vite root folder name
// seedModule: 'src/seed.ts' // optional, runs after DB is ready
// verbose: true, // optional, inherit Postgres logs in Vite output
// logFile: 'postgres.log', // optional, relative to Vite root (ignored if verbose)
}),
],
})
Then start Vite. Your app can connect using the injected env:
PGHOST=127.0.0.1PGPORT=<free port>PGDATABASE=<db name>PGDATA=<data directory>psql "host=$PGHOST port=$PGPORT dbname=$PGDATABASE"
# or (common default)
psql "postgresql://127.0.0.1:$PGPORT/$PGDATABASE"
export interface VitePostgresOptions {
dbPath?: string
dbName?: string
seedModule?: string
verbose?: boolean
logFile?: string
}
dbPath: Postgres data directory. Default: ${os.tmpdir()}/vite-postgres/<root>-<hash>dbName: Database name. Default: Vite root folder nameseedModule: Module path (relative to Vite root) to execute after the DB is readyverbose: Inherit Postgres stdout/stderr in the Vite process. Default: false (logs go to a file)logFile: Where to write Postgres logs (relative to Vite root). Default: ${PGDATA}/postgres.log (ignored if verbose)If seedModule is set, itβs loaded via server.ssrLoadModule(...) after:
initdb (only if PG_VERSION missing)postgres startedpg_isready succeedscreatedb attempted (ignored if it already exists)--auth=trust (no password). This is for local dev.${PGDATA}/postgres.log to keep Vite output clean (unless verbose is enabled).PATH (initdb, postgres, createdb, pg_isready)Failed to initialize DB. Ensure "initdb" is in your PATH.: install Postgres (or add its bin/ directory to PATH).process.env.PGPORT from your app instead of hard-coding 5432.