### Install Dependencies and Start Project
Source: https://neon.com/docs/guides/wundergraph
Install project dependencies and start the local development server.
```bash
npm install && npm run dev
```
--------------------------------
### Medusa Application Setup Output
Source: https://neon.com/docs/guides/medusajs
Example output after successfully running the `create-medusa-app` command, indicating dependencies installed, migrations ran, database seeded, and the Medusa server starting.
```bash
$ npx create-medusa-app@latest --db-url "YOUR_NEON_CONNECTION_STRING"
? What's the name of your project? my-medusa-store
? Would you like to install the Next.js Starter Storefront? You can also install it later. Yes
🚀 Starting project setup, this may take a few minutes.
✔ Created project directory
✔ Installed Next.js Starter Storefront successfully in the my-medusa-store-storefront directory.
✔ Installed Dependencies
✔ Ran Migrations
✔ Seeded database with demo data
✔ Finished Preparation
✔ Project Prepared
Starting Medusa...
> my-medusa-store@0.0.1 dev
> medusa develop
- Creating server
✔ Server is ready on port: 9000 – 11ms
```
--------------------------------
### Get Started Component
Source: https://neon.com/docs/community/component-specialized
Use this component to display getting started information for a specific SDK.
```mdx
```
--------------------------------
### Vite project setup confirmation
Source: https://neon.com/docs/guides/cloudflare-pages
Example output from the 'npm create vite@latest' command, showing the project name, framework, and variant selected. It also provides commands to navigate into the project directory, install dependencies, and start the development server.
```bash
✔ Project name: … my-neon-page
✔ Select a framework: ' React
✔ Select a variant: ' JavaScript
Scaffolding project in /Users/ishananand/repos/javascript/my-neon-page...
Done. Now run:
cd my-neon-page
npm install
npm run dev
```
--------------------------------
### Initialize Node.js Project and Install Dependencies
Source: https://neon.com/docs/guides/heroku
Sets up a new Node.js project, enables ES6 module support, configures a start script, and installs the 'express' and 'pg' packages. It also creates a .env file for environment variables.
```bash
mkdir neon-heroku-example && cd neon-heroku-example
npm init -y && npm pkg set type="module" && npm pkg set scripts.start="node index.js"
npm install express pg
touch .env
```
--------------------------------
### Example Prompt for Neon Auth Setup
Source: https://neon.com/docs/auth/overview
Use this example prompt with your AI assistant to enable and configure Neon Auth, including OAuth providers and sign-in methods.
```text
Set up Neon Auth for my project. Enable Google OAuth and email/password sign-in,
and set the application name to "My App".
```
--------------------------------
### Getting Started with Neon API
Source: https://neon.com/docs/reference/api-reference
This section provides an overview of how to get started with the Neon API, including obtaining an API key and authenticating your requests.
```APIDOC
## Getting Started with Neon API
To interact with the Neon API, you will need an API key. You can obtain one by following the instructions provided in the prompt linked below.
[View prompt](https://neon.com/prompts/neon-api-prompt.md)
Once you have your API key, you can authenticate your requests using Bearer tokens. The base URL for the Neon API is `https://console.neon.tech/api/v2/`.
### Authentication
Requests to the Neon API must be authenticated using a Bearer token. Include your API key in the `Authorization` header as follows:
```
Authorization: Bearer YOUR_API_KEY
```
### Rate Limits
Be aware of the API rate limits to ensure smooth operation of your automated workflows. Refer to the official documentation for details on current limits.
### Async Operation Polling
Some API operations are asynchronous. You may need to poll a status endpoint to determine when an operation has completed.
### Branch Deletion Rules
Understand the rules and constraints associated with deleting branches via the API to avoid unintended data loss.
```
--------------------------------
### Update Provider Setup (Before)
Source: https://neon.com/docs/auth/migrate/from-legacy-auth
Example of setting up the legacy Stack Auth provider and theme.
```tsx
import { StackProvider, StackTheme } from '@stackframe/stack';
import { stackClientApp } from './stack';
function App() {
return (
{/* Your app */}
);
}
```
--------------------------------
### Quick start scaffolding
Source: https://neon.com/docs/cli/bootstrap
Quickly scaffolds the default template (or a specified template with --template) into './my-app' and automatically runs dependency installation and git initialization without interactive prompts.
```bash
neonctl bootstrap my-app --default
```
--------------------------------
### Hono.js Project Setup CLI Prompts
Source: https://neon.com/docs/guides/drizzle-migrations
Example interactive CLI prompts for setting up a new Hono.js project. Select 'nodejs' for the template and 'npm' as the package manager.
```bash
Need to install the following packages:
create-hono@0.9.0
Ok to proceed? (y) y
create-hono version 0.9.0
✔ Using target directory … neon-drizzle-guide
✔ Which template do you want to use? ' nodejs
cloned honojs/starter#main to ./repos/javascript/neon-drizzle-guide
✔ Do you want to install project dependencies? … yes
✔ Which package manager do you want to use? ' npm
```
--------------------------------
### Example: Get Neon Project by ID
Source: https://neon.com/docs/cli/projects
This example demonstrates how to retrieve details for a Neon project with the ID `muddy-wood-859533`. Ensure you have the Neon CLI installed and configured.
```bash
neonctl projects get muddy-wood-859533
```
--------------------------------
### Quick Setup for Neon AI Integrations
Source: https://neon.com/docs/ai/ai-agents-tools
Use this command to authenticate, create an API key, configure your editor/CLI, and install agent skills. Restart your AI assistant after running this command.
```bash
npx neonctl@latest init
```
--------------------------------
### Environment Variables Setup
Source: https://neon.com/docs/ai-gateway/chat-completions
Set these environment variables before making requests to the AI Gateway. Refer to the 'Get started' guide for obtaining the necessary values.
```bash
NEON_AI_GATEWAY_TOKEN=nt_live_...
NEON_AI_GATEWAY_BASE_URL=https://br-winter-pond-aptw82ef-api.c2.us-east-2.aws.neon.tech
```
--------------------------------
### Prompt Agent for Neon Setup
Source: https://neon.com/docs/get-started/with-an-agent
After initializing, use this prompt in your editor's AI chat to guide your agent through Neon setup, including project creation and database configuration.
```text
Get started with Neon
```
--------------------------------
### Set up Python Virtual Environment and Install Packages
Source: https://neon.com/docs/guides/sqlalchemy-migrations
Creates a Python virtual environment, activates it, and installs necessary packages for SQLAlchemy, Alembic, FastAPI, and database connection.
```bash
python -m venv myenv
# On macOS and Linux
source myenv/bin/activate
# On Windows
myenv\Scripts\activate
mkdir guide-neon-sqlalchemy && cd guide-neon-sqlalchemy
pip install sqlalchemy alembic "psycopg2-binary"
pip install fastapi uvicorn python-dotenv
pip freeze > requirements.txt
```
--------------------------------
### Update Provider Setup (After)
Source: https://neon.com/docs/auth/migrate/from-legacy-auth
Example of setting up the Neon Auth UI provider and importing its styles. This replaces the Stack Auth provider and theme.
```tsx
import { NeonAuthUIProvider } from '@neondatabase/auth-ui';
import '@neondatabase/auth-ui/css';
import { authClient } from './auth';
function App() {
return {/* Your app */};
}
```
--------------------------------
### Install Neon Plugin in Cursor
Source: https://neon.com/docs/ai/ai-cursor-plugin
Use this command in Cursor chat to add the Neon plugin. After installation, prompt Cursor with 'Get started with Neon' to complete authentication.
```text
/add-plugin neon-postgres
```
--------------------------------
### Install and Use @neondatabase/env
Source: https://neon.com/docs/reference/neon-ts
Install the package to get type-safe access to environment variables. This example shows how to parse environment variables based on your Neon configuration and access specific service URLs.
```bash
npm install @neondatabase/env
```
```typescript
import { parseEnv } from '@neondatabase/env';
import config from './neon';
const env = parseEnv(config);
env.postgres.databaseUrl;
env.postgres.databaseUrlUnpooled;
env.auth.baseUrl;
env.auth.jwksUrl;
env.dataApi.url;
```
--------------------------------
### Install MCP Server Configuration
Source: https://neon.com/docs/ai/connect-mcp-clients-to-neon
This command installs the MCP configuration for your editor. Add `-g` for global setup. For API key authentication, include the authorization header. Refer to the add-mcp repository for more options.
```bash
npx add-mcp https://mcp.neon.tech/mcp
--header "Authorization: Bearer $NEON_API_KEY"
```
--------------------------------
### pg_restore Verbose Output Example
Source: https://neon.com/docs/import/migrate-from-railway
Example output indicating a successful connection and the start of the restore process for various database objects.
```bash
pg_restore: connecting to database for restore
pg_restore: creating SCHEMA "public"
pg_restore: creating TABLE "public.lego_colors"
pg_restore: creating SEQUENCE "public.lego_colors_id_seq"
pg_restore: creating SEQUENCE OWNED BY "public.lego_colors_id_seq"
pg_restore: creating TABLE "public.lego_inventories"
pg_restore: creating SEQUENCE "public.lego_inventories_id_seq"
...
```
--------------------------------
### Install Encore CLI on Linux
Source: https://neon.com/docs/guides/encore
Download and execute the installation script to install the Encore CLI on Linux.
```bash
curl -L https://encore.dev/install.sh | bash
```
--------------------------------
### Initialize libsql/client Connection
Source: https://neon.com/docs/import/migrate-from-turso
Example of initializing a database client using libsql/client before migration.
```javascript
import { createClient } from "@libsql/client";
const db = createClient({...config});
```
--------------------------------
### Initialize Node.js project and install dependencies
Source: https://neon.com/docs/guides/railway
Sets up a new Node.js project, enables ES6 module support, installs Express and pg, and creates a .env file for environment variables.
```bash
mkdir neon-railway-example && cd neon-railway-example
npm init -y && npm pkg set type="module"
npm install express pg
touch .env
```
--------------------------------
### Create Express Project and Install Dependencies
Source: https://neon.com/docs/guides/express
Initializes a new Express project and installs the core Express framework.
```shell
mkdir neon-express-example
cd neon-express-example
npm init -y
npm install express
```
--------------------------------
### Clone and Install Dependencies
Source: https://neon.com/docs/data-api/demo
Clone the demo application repository and install its dependencies using Bun.
```bash
git clone https://github.com/neondatabase-labs/neon-data-api-neon-auth.git
cd neon-data-api-neon-auth
bun install
```
--------------------------------
### Initialize Neon Project with AI Setup
Source: https://neon.com/docs/changelog/2025-11-28
Run this command to initiate the Neon setup process, which configures the Neon MCP Server for AI-assisted project onboarding. It supports VS Code and Claude CLI.
```bash
npx neonctl@latest init
┌ Adding Neon to your project
│
◆ Which editor(s) would you like to configure? (Space to toggle each option, Enter to confirm your selection)
│ ◼ Cursor
│ ◼ VS Code
│ ◻ Claude CLI
│
◒ Authenticating
┌────────┬──────────────────┬────────┬────────────────┐
│ Login │ Email │ Name │ Projects Limit │
├────────┼──────────────────┼────────┼────────────────┤
│ alex │ alex@domain.com │ Alex │ 60 │
└────────┴──────────────────┴────────┴────────────────┘
◇ Authentication successful ✓
│
◇ Installed Neon MCP server
│
◇ Success! Neon is now ready to use with Cursor / VS Code.
│
│
◇ What's next? ─────────────────────────────────────────────────────────────╮
│ │
│ Restart Cursor / VS Code and type in "Get started with Neon" in the chat │
│ │
├────────────────────────────────────────────────────────────────────────────╯
```
--------------------------------
### Create Project Directory and Initialize npm
Source: https://neon.com/docs/guides/drizzle
Sets up a new Node.js project by creating a directory and initializing a package.json file.
```bash
mkdir my-drizzle-neon-project
cd my-drizzle-neon-project
npm init -y
```
--------------------------------
### Example Neon to Neon Migration with Connection Details
Source: https://neon.com/docs/import/migrate-from-neon
An example of the migration command with placeholder connection details. Note that the hostnames for source and destination databases will differ.
```bash
pg_dump -Fc -v -d postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/my_source_db?sslmode=require&channel_binding=require | pg_restore -v -d postgresql://alex:AbC123dEf@square-shadow-654321.us-east-2.aws.neon.tech/my_destination_db?sslmode=require&channel_binding=require
```
--------------------------------
### Run neonctl link interactively
Source: https://neon.com/docs/cli/link
Execute the link command without flags to initiate an interactive guided setup process.
```bash
neonctl link
```
--------------------------------
### Example Application: Go and Terraform Integration
Source: https://neon.com/docs/reference/terraform
Demonstrates setting up Terraform, connecting to a Neon Postgres database, and performing Terraform runs (init, plan, apply) using Go's `os/exec` package. Includes a Go test function for validation.
```go
package main
import (
"fmt"
"os/exec"
)
func main() {
// Example: Run terraform init
cmdInit := exec.Command("terraform", "init")
cmdInit.Dir = "./path/to/your/terraform/config"
outputInit, err := cmdInit.CombinedOutput()
if err != nil {
fmt.Printf("Terraform init failed: %v\n%s\n", err, outputInit)
return
}
fmt.Printf("Terraform init successful:\n%s\n", outputInit)
// Example: Run terraform plan
cmdPlan := exec.Command("terraform", "plan")
cmdPlan.Dir = "./path/to/your/terraform/config"
outputPlan, err := cmdPlan.CombinedOutput()
if err != nil {
fmt.Printf("Terraform plan failed: %v\n%s\n", err, outputPlan)
return
}
fmt.Printf("Terraform plan successful:\n%s\n", outputPlan)
// Example: Run terraform apply (use with caution)
// cmdApply := exec.Command("terraform", "apply", "-auto-approve")
// cmdApply.Dir = "./path/to/your/terraform/config"
// outputApply, err := cmdApply.CombinedOutput()
// if err != nil {
// fmt.Printf("Terraform apply failed: %v\n%s\n", err, outputApply)
// return
// }
// fmt.Printf("Terraform apply successful:\n%s\n", outputApply)
}
```
--------------------------------
### Package.json Dependency
Source: https://neon.com/docs/guides/aws-lambda
Example of the 'pg' package dependency as it should appear in the 'package.json' file after installation.
```json
{
"dependencies": {
"pg": "^8.13.1"
}
}
```
--------------------------------
### CheckList with CheckItems
Source: https://neon.com/docs/community/component-guide
An interactive checklist for setup guides, composed of multiple CheckItem components. Each CheckItem requires a title and an optional href.
```mdx
Sign up for a free Neon account at console.neon.tech
Install the required packages for your project
Set up your database connection string
Verify your application can connect to Neon
```
--------------------------------
### Micronaut Application Startup Log
Source: https://neon.com/docs/guides/micronaut-kotlin
This is an example of the expected output when the Micronaut application starts successfully. It shows the connection to the database, Flyway migrations, and the application becoming ready to handle requests.
```bash
$ ./gradlew run
[test-resources-service] 15:48:33.940 [main] INFO i.m.c.DefaultApplicationContext$RuntimeConfiguredEnvironment - Established active environments: [test]
> Task :run
__ __ _ _
| \/ (_) ___ _ __ ___ _ __ __ _ _ _| |_
| |\/| | |/ __| '__/ _ \| '_ \ / _` | | | | __|
| | | | | (__| | | (_) | | | | (_| | |_| | |_
|_| |_|_|\___|_| \___/|_| |_|\__,_|\__,_|\__|
15:48:43.830 [main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
15:48:45.974 [main] INFO com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@30506c0d
15:48:45.975 [main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
15:48:46.126 [main] INFO i.m.flyway.AbstractFlywayMigration - Running migrations for database with qualifier [default]
15:48:46.298 [main] INFO org.flywaydb.core.FlywayExecutor - Database: jdbc:postgresql://endpoint.neon.tech/examples?sslmode=require&channelBinding=require (PostgreSQL 17.5)
15:48:48.110 [main] INFO o.f.c.i.s.JdbcTableSchemaHistory - Schema history table "public"."flyway_schema_history" does not exist yetn
15:48:48.250 [main] INFO o.f.core.internal.command.DbValidate - Successfully validated 1 migration (execution time 00:00.432s)
15:48:49.524 [main] INFO o.f.c.i.s.JdbcTableSchemaHistory - Creating Schema History table "public"."flyway_schema_history" ...
15:48:51.817 [main] INFO o.f.core.internal.command.DbMigrate - Current version of schema "public": << Empty Schema >>
15:48:52.243 [main] INFO o.f.core.internal.command.DbMigrate - Migrating schema "public" to version "1 - create book table"
15:48:54.757 [main] INFO o.f.core.internal.command.DbMigrate - Successfully applied 1 migration to schema "public", now at version v1 (execution time 00:00.969s)
15:48:55.841 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 12788ms. Server Running: http://localhost:8080 :run
<=============> 92% EXECUTING [38s]
> :run
> IDLE
```
--------------------------------
### Example .env file output from neon-new
Source: https://neon.com/docs/reference/claimable-postgres
This example shows the connection strings and claim URL generated by the neon-new CLI. DATABASE_URL is for pooled connections, and DATABASE_URL_DIRECT is for direct connections.
```dotenv
DATABASE_URL=postgresql://neondb_owner:npg_xxxxxxxxxxxx@ep-cool-breeze-a1b2c3d4-pooler.c-2.us-east-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require
DATABASE_URL_DIRECT=postgresql://neondb_owner:npg_xxxxxxxxxxxx@ep-cool-breeze-a1b2c3d4.c-2.us-east-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require
# Claimable DB expires at: Sat, 01 Feb 2026 12:00:00 GMT
# Claim it now to your account using the link below:
PUBLIC_POSTGRES_CLAIM_URL=https://neon.new/claim/01abc123-def4-5678-9abc-def012345678
```
--------------------------------
### Create Sample Table and Data
Source: https://neon.com/docs/extensions/dict_int
Sets up a sample `documents` table with `version_code` as text and inserts initial data for demonstrating full-text search with custom configurations.
```sql
CREATE TABLE documents (
id SERIAL PRIMARY KEY,
title TEXT,
content TEXT,
version_code TEXT
);
INSERT INTO documents (title, content, version_code) VALUES
('Intro Guide', 'Content of version 1...', '1'),
('Advanced Manual', 'More content...', '0042'),
('Internal Spec', 'Spec details...', '7654321'),
('Internal Spec v2', 'Updated spec...', '+7654321'),
('Draft Notes', 'Preliminary ideas...', 'ver003');
```
--------------------------------
### Asyncpg Setup for Database Operations
Source: https://neon.com/docs/guides/python
This snippet shows the initial setup for using asyncpg to connect to a Neon database. It imports necessary libraries and loads environment variables for the connection string.
```python
import asyncio
import os
import asyncpg
from dotenv import load_dotenv
```
--------------------------------
### Connect to Neon using postgres.js
Source: https://neon.com/docs/guides/tanstack-start
Integrate Neon with TanStack Start using the postgres.js driver. This example requires the DATABASE_URL environment variable.
```typescript
import postgres from 'postgres';
import { createServerFn } from "@tanstack/react-start";
import { staticFunctionMiddleware } from "@tanstack/start-static-server-functions";
export const getData = createServerFn({ method: "GET" })
.middleware([staticFunctionMiddleware])
.handler(async () => {
const sql = postgres(process.env.DATABASE_URL, { ssl: 'require' });
const response = await sql`SELECT version()`;
return response[0].version;
});
```
--------------------------------
### Create App Directory and Initialize
Source: https://neon.com/docs/guides/sqlalchemy-migrations
Creates the 'app' directory for application files and initializes it as a Python package.
```bash
mkdir app
touch guide-neon-sqlalchemy/app/__init__.py
```
--------------------------------
### Get Help for Meta-Command
Source: https://neon.com/docs/get-started/query-with-neon-sql-editor
Use `\h [NAME]` to get help for a specific PostgreSQL command. For example, `\h SELECT`.
```sql
\h [NAME]
```
```sql
\h SELECT
```
--------------------------------
### Next.js App Router Auth Page Setup
Source: https://neon.com/docs/auth/reference/ui-components
Example for Next.js App Router, using a catch-all route to manage all authentication views. This setup requires `dynamicParams = false` and `generateStaticParams`.
```tsx
import { AuthView } from '@neondatabase/auth-ui';
import { authViewPaths } from '@neondatabase/auth-ui/server';
export const dynamicParams = false;
export function generateStaticParams() {
return Object.values(authViewPaths).map((path) => ({ path }));
}
export default async function AuthPage({
params,
}: {
params: Promise<{ path: string }>;
}) {
const { path } = await params;
return (
);
}
```
--------------------------------
### Initialize Neon Project
Source: https://neon.com/docs/cli/init
Navigate to your application's root directory and execute the init command to set up Neon integration. This command handles authentication and configuration for your project.
```bash
cd /path/to/your/app
npx neonctl@latest init
```
--------------------------------
### Install Neon Codex Plugin via npm
Source: https://neon.com/docs/changelog/2026-04-17
Use this command to install the OpenAI Codex CLI globally if you don't have it. After installation, start the Codex CLI to access its features.
```bash
npm install -g @openai/codex
codex
```
--------------------------------
### Install Neon Codex Plugin via Homebrew
Source: https://neon.com/docs/changelog/2026-04-17
Use this command to install the OpenAI Codex CLI via Homebrew if you prefer. After installation, start the Codex CLI to access its features.
```bash
brew install --cask codex
codex
```
--------------------------------
### Clone and Start Grafana Docker OTEL LGTM Stack
Source: https://neon.com/docs/guides/opentelemetry
Use this command to clone the Grafana Docker OTEL LGTM repository and start the observability stack using Docker Compose. Ensure Docker is installed and running.
```bash
git clone https://github.com/grafana/docker-otel-lgtm.git
cd docker-otel-lgtm
docker compose up -d
```
--------------------------------
### Install psql on Mac (Intel x64)
Source: https://neon.com/docs/connect/query-with-psql-editor
Installs libpq and configures the PATH for psql on Intel-based Macs using Homebrew.
```bash
brew install libpq
echo 'export PATH="/usr/local/opt/libpq/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```
--------------------------------
### Create and Insert Data into weather_data Table
Source: https://neon.com/docs/functions/avg
This snippet demonstrates how to create a sample table named 'weather_data' and insert sample temperature readings for different cities and dates. This setup is used for subsequent examples.
```sql
CREATE TABLE weather_data (
date DATE,
city TEXT,
temperature NUMERIC
);
INSERT INTO weather_data (date, city, temperature) VALUES
('2024-03-01', 'New York', 5.5),
('2024-03-01', 'Los Angeles', 22.0),
('2024-03-01', 'Chicago', 2.0),
('2024-03-02', 'New York', 7.0),
('2024-03-02', 'Los Angeles', 23.5),
('2024-03-02', 'Chicago', 3.5),
('2024-03-03', 'New York', 6.5),
('2024-03-03', 'Los Angeles', 21.5),
('2024-03-03', 'Chicago', 1.0);
```
--------------------------------
### Install Serverless Framework
Source: https://neon.com/docs/guides/aws-lambda
Installs the Serverless Framework globally using npm.
```bash
npm install -g serverless
```
--------------------------------
### Install Codex CLI with npm
Source: https://neon.com/docs/ai/ai-codex-plugin
Install the Codex CLI globally using npm. This command is used to get the necessary tools for interacting with Codex from your terminal.
```bash
npm install -g @openai/codex
codex
```
--------------------------------
### Example Workflow: Index and Statistics Proposals
Source: https://neon.com/docs/extensions/online_advisor
A comprehensive workflow demonstrating how to activate the advisor, view index and statistics proposals, apply a recommendation, and check performance metrics.
```sql
-- Activate and run workload
SELECT get_executor_stats();
-- View index proposals
SELECT create_index, n_filtered, n_called, elapsed_sec
FROM proposed_indexes
ORDER BY elapsed_sec DESC
LIMIT 10;
-- View extended statistics proposals
SELECT create_statistics, misestimation, n_called, elapsed_sec
FROM proposed_statistics
ORDER BY misestimation DESC
LIMIT 10;
-- Apply a recommendation
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_customer_date ON orders(customer_id, order_date);
VACUUM (ANALYZE) orders;
-- Check planning/execution times
SELECT * FROM get_executor_stats(true); -- reset after reading
```
--------------------------------
### Local Development Server Output Example
Source: https://neon.com/docs/guides/cloudflare-workers
Example output when running `npm run dev`, showing the Wrangler CLI version and local server readiness.
```bash
❯ npm run dev
> my-neon-worker@0.0.0 dev
> wrangler dev
⛅️ wrangler 4.61.0
───────────────────
Your Worker has access to the following bindings:
Binding Resource Mode
env.HYPERDRIVE (YOUR_HYPERDRIVE_ID) Hyperdrive Config local
❓ Your types might be out of date. Re-run `wrangler types` to ensure your types are correct.
╭──────────────────────────────────────────────────────────────────────╮
│ [b] open a browser [d] open devtools [c] clear console [x] to exit │
╰──────────────────────────────────────────────────────────────────────╯
⎔ Starting local server...
[wrangler:info] Ready on http://localhost:8787
```
--------------------------------
### Full Stack Neon Configuration Example
Source: https://neon.com/docs/reference/neon-ts
A comprehensive example demonstrating the configuration of Neon Functions, Storage, and AI Gateway, along with branch-specific PostgreSQL settings for production and development environments.
```typescript
import { defineConfig } from "@neondatabase/config/v1";
export default defineConfig({
auth: true,
dataApi: true,
preview: {
aiGateway: true,
buckets: {
uploads: {},
},
functions: {
api: {
name: "API",
source: "./functions/api.ts",
},
},
},
branch: (branch) => {
if (branch.isDefault) {
// Protect and size for production
return {
protected: true,
postgres: {
computeSettings: {
autoscalingLimitMinCu: 0.5,
autoscalingLimitMaxCu: 4,
},
},
};
}
if (!branch.exists) {
// New non-default branches: minimum compute, auto-expire, suspend on idle
return {
ttl: "7d",
postgres: {
computeSettings: {
autoscalingLimitMinCu: 0.25,
autoscalingLimitMaxCu: 0.25,
suspendTimeout: "5m",
},
},
};
}
// Existing branch: no changes
return {};
},
});
```
--------------------------------
### API Response Example for Masking Rules
Source: https://neon.com/docs/workflows/data-anonymization
This JSON structure shows an example response from the Get Masking Rules API endpoint, illustrating how masking rules are represented.
```json
{
"masking_rules": [
{
"database_name": "neondb",
"schema_name": "public",
"table_name": "users",
"column_name": "email",
"masking_function": "anon.dummy_free_email()"
},
{
"database_name": "neondb",
"schema_name": "public",
"table_name": "users",
"column_name": "phone",
"masking_function": "anon.partial(phone, 2, 'XXX-XXXX', 2)"
},
{
"database_name": "neondb",
"schema_name": "public",
"table_name": "users",
"column_name": "address",
"masking_value": "'CONFIDENTIAL'"
}
]
}
```
--------------------------------
### Initialize Project with neonctl for Preview Features
Source: https://neon.com/docs/ai/agent-skills
For access to platform private preview features like Functions, Storage, and AI Gateway, use `neonctl init --preview`. This command ensures proper setup for these advanced capabilities.
```bash
npx neonctl@latest init --preview
```
--------------------------------
### Automatic Neon AI Tooling Setup
Source: https://neon.com/docs/ai/ai-cursor-plugin
Run this command to automatically configure MCP and install Neon agent skills for supported editors.
```bash
npx neonctl@latest init
```
--------------------------------
### Create and Populate Employees Table
Source: https://neon.com/docs/functions/age
Defines an 'employees' table with name, birth_date, and hire_date, and inserts sample data. This setup is required for the subsequent age calculation examples.
```sql
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name TEXT,
birth_date DATE,
hire_date DATE
);
INSERT INTO employees (name, birth_date, hire_date) VALUES
('John Doe', '1985-05-15', '2010-03-01'),
('Jane Smith', '1990-08-22', '2015-07-10'),
('Bob Johnson', '1978-12-03', '2005-11-15');
```
--------------------------------
### Analyze a SELECT Query with EXPLAIN ANALYZE
Source: https://neon.com/docs/postgresql/query-performance
This example demonstrates how to use EXPLAIN ANALYZE to get a detailed execution plan for a SELECT query. The output can reveal performance bottlenecks, such as sequential scans on large tables, suggesting the need for indexing.
```sql
EXPLAIN ANALYZE SELECT * FROM users WHERE id = '1';
```
--------------------------------
### Create New .NET Project
Source: https://neon.com/docs/guides/entity-migrations
Initializes a new .NET console application and navigates into its directory.
```bash
dotnet new console -o guide-neon-entityframework
cd guide-neon-entityframework
```
--------------------------------
### Successful Deployment Output Example
Source: https://neon.com/docs/guides/cloudflare-pages
Example output after a successful deployment to Cloudflare Pages, including the application's public URL.
```bash
✨ Compiled Worker successfully
🌍 Uploading... (4/4)
✨ Success! Uploaded 0 files (4 already uploaded) (0.72 sec)
✨ Uploading Functions bundle
✨ Deployment complete! Take a peek over at https://21ea2a57.my-neon-page.pages.dev
```
--------------------------------
### Run the Application
Source: https://neon.com/docs/guides/entity-migrations
Starts a local web server to test the API endpoints. Navigate to http://localhost:5000/authors and http://localhost:5000/books/1 to view seeded data.
```bash
dotnet run
```
```bash
curl http://localhost:5000/authors
curl http://localhost:5000/books/1
```
--------------------------------
### Navigate to Project and Create Properties File
Source: https://neon.com/docs/guides/liquibase
Change into the project directory and create the Liquibase properties file.
```bash
cd blogdb
touch liquibase.properties
```
--------------------------------
### Install JWT libraries for Go
Source: https://neon.com/docs/auth/guides/plugins/jwt
Install the 'jwt' and 'keyfunc' libraries for Go to handle JWT verification.
```bash
go get github.com/golang-jwt/jwt/v5
go get github.com/MicahParks/keyfunc/v3
```
--------------------------------
### Create and Populate Workflow Table
Source: https://neon.com/docs/functions/jsonb_array_elements
Defines a 'workflow' table with a JSONB 'steps' column and inserts sample data. This setup is necessary for the subsequent query example.
```sql
CREATE TABLE workflow (
id SERIAL PRIMARY KEY,
workflow_name TEXT,
steps JSONB
);
INSERT INTO workflow (workflow_name, steps) VALUES
('Employee Onboarding', '{"tasks": ["Submit Resume", "Interview", "Background Check", "Offer", "Orientation"]}'),
('Project Development', '{"tasks": ["Requirement Analysis", "Design", "Implementation", "Testing", "Deployment"] }'),
('Order Processing', '{"tasks": ["Order Received", "Payment Verification", "Packing", "Shipment", "Delivery"]}');
```
--------------------------------
### Start Embedded PostgreSQL Instance
Source: https://neon.com/docs/guides/embedded-postgres
Demonstrates how to start an embedded PostgreSQL instance with custom configuration. Ensure the configuration is valid and all necessary properties are set.
```java
EmbeddedPostgres embeddedPostgres = new EmbeddedPostgres();
embeddedPostgres.start();
```
--------------------------------
### pgloader Configuration File Example
Source: https://neon.com/docs/import/migrate-from-planetscale
An example pgloader configuration file (`.load`) specifying the source PlanetScale database and the destination Neon database connection strings.
```plaintext
load database
from mysql://username:password@host/source_db?sslmode=require
into postgresql://alex:endpoint=ep-cool-darkness-123456;AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require;
```
--------------------------------
### Create sample book inventory table
Source: https://neon.com/docs/functions/json_object
Sets up a sample 'book_inventory' table with book details for demonstrating JSON functions.
```sql
-- Test database table for a bookstore inventory
CREATE TABLE book_inventory (
book_id INT,
title TEXT,
author TEXT,
price NUMERIC,
genre TEXT
);
-- Inserting some test data into `book_inventory`
INSERT INTO book_inventory VALUES
(101, 'The Great Gatsby', 'F. Scott Fitzgerald', 18.99, 'Classic'),
(102, 'Invisible Man', 'Ralph Ellison', 15.99, 'Novel');
```
--------------------------------
### Install psql on Linux
Source: https://neon.com/docs/connect/query-with-psql-editor
Installs the postgresql-client package on Debian-based Linux systems using apt.
```bash
sudo apt update
sudo apt install postgresql-client
```
--------------------------------
### Start Local Development Server
Source: https://neon.com/docs/guides/netlify-functions
Command to start the Netlify local development server.
```bash
netlify dev
```
--------------------------------
### psql Connection Example
Source: https://neon.com/docs/connect/connect-from-any-app
Connect to Neon using the 'psql' command-line tool. The DATABASE_URL environment variable should be set.
```bash
psql "$DATABASE_URL"
```
--------------------------------
### Install and Run app.build CLI
Source: https://neon.com/docs/changelog/2025-06-06
Use this command to create and deploy a complete application with its own GitHub repository using the app.build CLI.
```bash
npx @app.build/cli
```
--------------------------------
### Get Email Provider Configuration
Source: https://neon.com/docs/cli/neon-auth
Retrieves the current configuration for the email provider. This is useful for auditing or understanding the existing setup.
```bash
neonctl neon-auth config email-provider get [options]
```
```bash
neonctl neon-auth config email-provider get
```
--------------------------------
### Get Next Page of Project Consumption Data
Source: https://neon.com/docs/guides/consumption-metrics
Use this example to retrieve the next page of project consumption data by providing the cursor from the previous response. Ensure all other parameters match the initial request.
```bash
curl --request GET \
--url 'https://console.neon.tech/api/v2/consumption_history/v2/projects?cursor=divine-tree-77657175&limit=10&from=2024-06-30T00%3A00%3A00Z&to=2024-07-02T00%3A00%3A00Z&granularity=daily&org_id=$ORG_ID&metrics=compute_unit_seconds,root_branch_bytes_month,child_branch_bytes_month,instant_restore_bytes_month,snapshot_storage_bytes_month,public_network_transfer_bytes,private_network_transfer_bytes,extra_branches_month' \
--header 'accept: application/json' \
--header 'authorization: Bearer $NEON_API_KEY'
```
--------------------------------
### Example Project Response
Source: https://neon.com/docs/reference/api-reference
This is an example of the JSON response you can expect when listing projects.
```json
{
"projects": [
{
"id": "spring-example-302709",
"name": "my-project",
"region_id": "aws-us-east-2",
"pg_version": 17,
"created_at": "2024-01-15T10:30:00Z"
}
]
}
```
--------------------------------
### Start Development Server
Source: https://neon.com/docs/data-api/demo
Launch the development server for the note-taking application. Access the app in your browser at http://localhost:5173.
```bash
bun dev
```
--------------------------------
### List Projects Example
Source: https://neon.com/docs/reference/api-reference
This example demonstrates how to authenticate and make a request to list projects using your API key.
```APIDOC
## GET /projects
### Description
Retrieves a list of projects accessible via the API.
### Method
GET
### Endpoint
https://console.neon.tech/api/v2/projects
### Parameters
#### Headers
- **Accept**: application/json
- **Authorization**: Bearer $NEON_API_KEY
### Request Example
```bash
curl 'https://console.neon.tech/api/v2/projects' \
-H 'Accept: application/json' \
-H "Authorization: Bearer $NEON_API_KEY"
```
### Response
#### Success Response (200)
- **projects**: array - A list of project objects.
- **id**: string - The unique identifier for the project.
- **name**: string - The name of the project.
- **created_at**: string - The timestamp when the project was created.
- **owner_id**: string - The ID of the user who owns the project.
- **cloud_provider**: string - The cloud provider where the project is hosted.
- **region_id**: string - The ID of the region where the project is located.
- **billing_period_end**: string - The end date of the current billing period.
- **safeguard_stop_period**: string - The period for safeguard stop.
- **storage_quota**: integer - The storage quota for the project in bytes.
- **storage_used**: integer - The amount of storage currently used in bytes.
- **vm_cpu_cores**: integer - The number of CPU cores allocated to the project.
- **vm_ram_bytes**: integer - The amount of RAM allocated to the project in bytes.
- **vm_ram_used_bytes**: integer - The amount of RAM currently used in bytes.
- **vm_storage_bytes**: integer - The amount of storage allocated for the VM in bytes.
- **vm_storage_used_bytes**: integer - The amount of storage currently used by the VM in bytes.
- **role**: string - The user's role in the project.
- **parent_organization_id**: string - The ID of the parent organization.
- **parent_workspace_id**: string - The ID of the parent workspace.
- **is_protected**: boolean - Indicates if the project is protected.
- **is_shared**: boolean - Indicates if the project is shared.
- **branch_count**: integer - The number of branches in the project.
- **connection_uris**: array - A list of connection URIs for the project.
- **uri**: string - The connection URI.
- **type**: string - The type of the URI (e.g., "read-only", "read-write").
- **operations_count**: integer - The number of operations performed on the project.
- **operations_limit**: integer - The limit for operations on the project.
- **operations_period**: string - The period for the operations limit.
- **operations_used**: integer - The number of operations used.
#### Response Example
```json
{
"projects": [
{
"id": "your-project-id",
"name": "My Project",
"created_at": "2023-10-27T10:00:00Z",
"owner_id": "your-user-id",
"cloud_provider": "aws",
"region_id": "aws-us-east-1",
"billing_period_end": "2023-11-30T23:59:59Z",
"safeguard_stop_period": "7d",
"storage_quota": 10737418240,
"storage_used": 5368709120,
"vm_cpu_cores": 2,
"vm_ram_bytes": 2147483648,
"vm_ram_used_bytes": 1073741824,
"vm_storage_bytes": 21474836480,
"vm_storage_used_bytes": 10737418240,
"role": "owner",
"parent_organization_id": "your-org-id",
"parent_workspace_id": "your-workspace-id",
"is_protected": false,
"is_shared": false,
"branch_count": 5,
"connection_uris": [
{
"uri": "postgresql://user:password@host:port/database?sslmode=require",
"type": "read-write"
}
],
"operations_count": 1000,
"operations_limit": 5000,
"operations_period": "1d",
"operations_used": 50
}
]
}
```
```
--------------------------------
### Install psql on Mac (Apple Silicon)
Source: https://neon.com/docs/connect/query-with-psql-editor
Installs libpq and configures the PATH for psql on Apple Silicon Macs using Homebrew.
```bash
brew install libpq
echo 'export PATH="/opt/homebrew/opt/libpq/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```
--------------------------------
### Create and Populate Existing Table
Source: https://neon.com/docs/extensions/pg_partman
Creates a sample table and inserts data into it. This table will be partitioned in subsequent steps.
```sql
CREATE TABLE public.test_user_activities (
activity_id serial,
activity_time TIMESTAMPTZ NOT NULL,
activity_type TEXT NOT NULL,
content_id INT NOT NULL,
user_id INT NOT NULL
);
INSERT INTO test_user_activities (activity_time, activity_type, content_id, user_id)
VALUES
('2024-03-15 10:00:00', 'like', 1001, 101),
('2024-03-16 15:30:00', 'comment', 1002, 102),
('2024-03-17 09:45:00', 'share', 1003, 103),
('2024-03-18 18:20:00', 'like', 1004, 104),
('2024-03-19 12:10:00', 'comment', 1005, 105),
('2024-03-20 08:00:00', 'like', 1006, 106),
('2024-03-21 14:15:00', 'share', 1007, 107),
('2024-03-22 11:30:00', 'like', 1008, 108),
('2024-03-23 16:45:00', 'comment', 1009, 109),
('2024-03-24 20:00:00', 'share', 1010, 110),
('2024-03-25 09:30:00', 'like', 1011, 111),
('2024-03-26 13:45:00', 'comment', 1012, 112),
('2024-03-27 17:00:00', 'share', 1013, 113),
('2024-03-28 11:15:00', 'like', 1014, 114),
('2024-03-29 15:30:00', 'comment', 1015, 115);
```
--------------------------------
### Get Email-Password Configuration
Source: https://neon.com/docs/cli/neon-auth
Retrieves the current configuration for email and password authentication. This helps in auditing or understanding the existing auth setup.
```bash
neonctl neon-auth config email-password get [options]
```
```bash
neonctl neon-auth config email-password get
```
--------------------------------
### Get Auth Configuration
Source: https://neon.com/docs/auth/guides/manage-auth-api
Retrieve the current Neon Auth configuration for a specific branch. This is useful for auditing or understanding the existing setup.
```bash
curl -X GET 'https://console.neon.tech/api/v2/projects/{project_id}/branches/{branch_id}/auth' \
-H 'Authorization: Bearer $NEON_API_KEY'
```
--------------------------------
### Install Required Packages
Source: https://neon.com/docs/guides/reflex
Install Reflex, python-dotenv for environment variable management, and psycopg2-binary for connecting to Neon Postgres.
```bash
pip install reflex python-dotenv psycopg2-binary
```
--------------------------------
### Start the API Server
Source: https://neon.com/docs/guides/prisma-migrations
Run the Express API server using the configured start script.
```bash
npm start
```
--------------------------------
### Deno Deploy Deployment Output Example
Source: https://neon.com/docs/guides/deno
This is an example of the output you will see after a successful deployment to Deno Deploy. It includes the project name, deployment status, and URLs to access your application.
```bash
$ deployctl deploy --project=cloudy-otter-57 --prod server.ts
✔ Deploying to project cloudy-otter-57.
ℹ The project does not have a deployment yet. Automatically pushing initial deployment to production (use --prod for further updates).
✔ Entrypoint: /home/ubuntu/neon-deno/server.ts
ℹ Uploading all files from the current dir (/home/ubuntu/neon-deno)
✔ Found 1 asset.
✔ Uploaded 1 new asset.
✔ Production deployment complete.
✔ Created config file 'deno.json'.
View at:
- https://cloudy-otter-57-8csne31fymac.deno.dev
- https://cloudy-otter-57.deno.dev
```
--------------------------------
### Install Netlify CLI
Source: https://neon.com/docs/guides/netlify-functions
Command to install the Netlify CLI globally using npm.
```bash
npm install netlify-cli -g
```
--------------------------------
### Install neon_utils Extension
Source: https://neon.com/docs/extensions/neon-utils
Use this SQL command to install the neon_utils extension if it's not already present.
```sql
CREATE EXTENSION IF NOT EXISTS neon_utils;
```
--------------------------------
### Initialize Medusa Application with Neon
Source: https://neon.com/docs/guides/medusajs
Use the `create-medusa-app` CLI to set up your Medusa project and connect to your Neon database. Replace YOUR_NEON_CONNECTION_STRING with your actual connection string.
```bash
npx create-medusa-app@latest --db-url "YOUR_NEON_CONNECTION_STRING"
```
--------------------------------
### Install Encore CLI on Windows
Source: https://neon.com/docs/guides/encore
Use PowerShell to install the Encore CLI on Windows.
```powershell
iwr https://encore.dev/install.ps1 | iex
```
--------------------------------
### Install neon-api
Source: https://neon.com/docs/reference/python-sdk
Install the neon-api Python SDK using pip.
```shell
pip install neon-api
```
--------------------------------
### Observe Index Statistics Example
Source: https://neon.com/docs/extensions/pgstattuple
This example demonstrates creating an index and then using pgstatindex() to check its statistics. The output provides details on the index's structure and space utilization.
```sql
-- Create an index on the customers table
CREATE INDEX idx_customers_first_name ON customers (first_name);
-- Check index statistics
SELECT * FROM pgstatindex('idx_customers_first_name');
```
--------------------------------
### Create and Insert Data into student_scores Table
Source: https://neon.com/docs/functions/dense_rank
This snippet demonstrates how to create a sample table named 'student_scores' and populate it with student names and their scores. This setup is used for subsequent examples of the dense_rank() function.
```sql
CREATE TABLE student_scores (
student_id SERIAL PRIMARY KEY,
student_name VARCHAR(50) NOT NULL,
score INT NOT NULL
);
INSERT INTO student_scores (student_name, score) VALUES
('Alice', 85),
('Bob', 92),
('Charlie', 78),
('David', 92),
('Eve', 85),
('Frank', 78);
```
--------------------------------
### Get Current Timestamp
Source: https://neon.com/docs/functions/current_timestamp
This snippet demonstrates the basic usage of `current_timestamp` to retrieve the current date and time with timezone at the start of the transaction. No parentheses are used in this form.
```sql
current_timestamp
```
--------------------------------
### Interactive Neon Initialization Process
Source: https://neon.com/docs/changelog/2025-11-07
This output shows the interactive steps involved when running `npx neonctl@latest init`, including authentication, project selection, and confirmation of successful setup.
```bash
npx neonctl@latest init
┌ Adding Neon to your project
│
◒ Authenticating.
┌────────┬──────────────────┬────────┬────────────────┐
│ Login │ Email │ Name │ Projects Limit │
├────────┼──────────────────┼────────┼────────────────┤
│ alex │ alex@domain.com │ Alex │ 20 │
└────────┴──────────────────┴────────┴────────────────┘
◇ Authentication successful ✓
│
◇ Installed Neon MCP server
│
◇ Success! Neon is now ready to use with Cursor.
│
│
◇ What's next? ────────────────────────────────────────────────────────────────────────────╮
│ │
│ Restart Cursor and ask Cursor to "Get started with Neon using MCP Resource" in the chat │
│ │
├───────────────────────────────────────────────────────────────────────────────────────────╯
│
└ Have feedback? Email us at feedback@neon.tech
```
--------------------------------
### Install Neon Platform and Storage Skills
Source: https://neon.com/docs/storage/get-started
Install the Neon Platform and Neon Object Storage skills using npx. This is the first step to setting up Neon Storage with an AI coding assistant.
```bash
npx skills add neondatabase/agent-skills -s neon -s neon-object-storage
```
--------------------------------
### Get Prisma Connection String
Source: https://neon.com/docs/cli/connection-string
Retrieves a PostgreSQL connection string formatted for Prisma setup. Use the `--prisma` flag when configuring Prisma with Neon.
```bash
neonctl connection-string --prisma
```
--------------------------------
### Install Neon Agent Skills
Source: https://neon.com/docs/compute/functions/get-started
Install the Neon Platform and Neon Functions skills for your AI coding assistant. Ensure you have the latest `neonctl` installed and authenticated.
```bash
npx skills add neondatabase/agent-skills -s neon -s neon-functions
```
--------------------------------
### Initialize Turso Serverless Connection
Source: https://neon.com/docs/import/migrate-from-turso
Example of initializing a database connection using the Turso serverless client before migration.
```javascript
import { connect } from "@tursodatabase/serverless";
const db = connect({
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
});
```
--------------------------------
### Initializing Git Repository and Pushing to GitHub
Source: https://neon.com/docs/guides/railway
Prepare your project for deployment by initializing a Git repository, creating a .gitignore file, committing your code, and pushing it to a remote GitHub repository.
```bash
echo "node_modules/" > .gitignore && echo ".env" >> .gitignore
echo "# neon-railway-example" >> README.md
git init && git add . && git commit -m "Initial commit"
git branch -M main
git remote add origin YOUR_GITHUB_REPO_URL
git push -u origin main
```
--------------------------------
### Seed Database with Authors and Books
Source: https://neon.com/docs/guides/drizzle-migrations
This TypeScript script seeds the 'authors' and 'books' tables with example data. It requires Drizzle ORM, Neon, and dotenv to be installed and configured.
```typescript
// src/seed.ts
import { drizzle } from 'drizzle-orm/neon-http';
import { neon } from '@neondatabase/serverless';
import { authors, books } from './schema';
import { config } from 'dotenv';
config({ path: '.env' });
const sql = neon(process.env.DATABASE_URL!);
const db = drizzle(sql);
async function seed() {
await db.insert(authors).values([
{
name: 'J.R.R. Tolkien',
bio: 'The creator of Middle-earth and author of The Lord of the Rings.',
},
{
name: 'George R.R. Martin',
bio: 'The author of the epic fantasy series A Song of Ice and Fire.',
},
{
name: 'J.K. Rowling',
bio: 'The creator of the Harry Potter series.',
},
]);
const authorRows = await db.select().from(authors);
const authorIds = authorRows.map((row) => row.id);
await db.insert(books).values([
{
title: 'The Fellowship of the Ring',
authorId: authorIds[0],
},
{
title: 'The Two Towers',
authorId: authorIds[0],
},
{
title: 'The Return of the King',
authorId: authorIds[0],
},
{
title: 'A Game of Thrones',
authorId: authorIds[1],
},
{
title: 'A Clash of Kings',
authorId: authorIds[1],
},
{
title: "Harry Potter and the Philosopher's Stone",
authorId: authorIds[2],
},
{
title: 'Harry Potter and the Chamber of Secrets',
authorId: authorIds[2],
},
]);
}
async function main() {
try {
await seed();
console.log('Seeding completed');
} catch (error) {
console.error('Error during seeding:', error);
process.exit(1);
}
}
main();
```
--------------------------------
### Example PostgreSQL Connection String with Realistic Values
Source: https://neon.com/docs/community/contribution-guide
Use this example when a connection string with realistic values is needed. It includes a sample username, password, hostname, and database name, along with SSL parameters.
```text
postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
```
--------------------------------
### Native Table Partitioning Example
Source: https://neon.com/docs/extensions/pg_partman
Demonstrates native range partitioning for a 'measurement' table, including creating partitions for specific date ranges and detaching old partitions.
```sql
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int
) PARTITION BY RANGE (logdate);
-- Create a partition for each month of logged data.
-- Records with `logdate` in this range are automatically routed to this partition table
CREATE TABLE measurement_y2006m02 PARTITION OF measurement
FOR VALUES FROM ('2006-02-01') TO ('2006-03-01');
-- Moving older data to a different table.
-- Queries against the main table will not include the data in the detached partition
ALTER TABLE measurement DETACH PARTITION measurement_y2005m10;
```
--------------------------------
### Case-Insensitive Regex Matching with citext
Source: https://neon.com/docs/extensions/citext
Applies a case-insensitive regular expression match to a citext column. This example finds users whose email addresses start with 'AL'.
```sql
SELECT * FROM users WHERE regexp_match(email, '^AL', 'i') IS NOT NULL;
```
--------------------------------
### Install Neon CLI with Homebrew
Source: https://neon.com/docs/changelog/2023-07-12
Install the Neon CLI using Homebrew. This is an alternative installation method for macOS and Linux users.
```bash
brew install neonctl
```
--------------------------------
### Install Neon CLI
Source: https://neon.com/docs/cli
Install the Neon CLI globally using npm.
```APIDOC
## Install Neon CLI
Install the Neon CLI globally using npm.
```bash
npm i -g neonctl
```
```
--------------------------------
### Start Next.js Development Server
Source: https://neon.com/docs/guides/auth-clerk
Run this command to start the Next.js development server. Access your application at http://localhost:3000. You will be prompted to sign in with Clerk on the first run.
```bash
npm run dev
```
--------------------------------
### Implement Todo Controller
Source: https://neon.com/docs/guides/dotnet-entity-framework
Create a controller to handle CRUD operations for Todo items. This example includes GET and POST actions using Entity Framework Core.
```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NeonEfExample.Data;
using NeonEfExample.Models;
namespace NeonEfExample.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class TodoController : ControllerBase
{
private readonly ApplicationDbContext _context;
public TodoController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task>> GetTodos()
{
return await _context.Todos.ToListAsync();
}
[HttpPost]
public async Task> PostTodo(Todo todo)
{
_context.Todos.Add(todo);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetTodos), new { id = todo.Id }, todo);
}
}
}
```
--------------------------------
### Create Project and Connect with psql
Source: https://neon.com/docs/cli/projects
Use the --psql flag to create a project and immediately connect to it using psql. Arguments after -- are passed directly to psql, allowing execution of SQL files or queries.
```bash
neonctl projects create --psql
```
```bash
neonctl projects create --psql -- -f dump.sql
```
```bash
neonctl projects create --psql -- -c "SELECT version()"
```
--------------------------------
### Start local development server
Source: https://neon.com/docs/guides/cloudflare-hyperdrive
Use the wrangler CLI to start a local server for testing Cloudflare Workers.
```bash
npx wrangler dev
```
--------------------------------
### Install Dependencies
Source: https://neon.com/docs/guides/imagekit
Install the necessary Python libraries for Flask, ImageKit.io, PostgreSQL, and environment variable management.
```bash
pip install Flask imagekitio psycopg2-binary python-dotenv
```
--------------------------------
### Install Dependencies and Configure Environment
Source: https://neon.com/docs/get-started/full-backend-quickstart
Install necessary Neon.js, Drizzle ORM, and serverless packages, plus Drizzle Kit for development. Create a .env.local file with your Neon connection string, Auth URL, and a secure cookie secret.
```bash
npm install @neondatabase/neon-js drizzle-orm @neondatabase/serverless
npm install -D drizzle-kit
```
```dotenv
DATABASE_URL=postgresql://...
NEON_AUTH_BASE_URL=https://ep-xxx.neonauth.c-7.us-east-1.aws.neon.tech/neondb/auth
NEON_AUTH_COOKIE_SECRET=replace-with-32-char-random-secret
```
--------------------------------
### Describe Specific Table Example
Source: https://neon.com/docs/get-started/query-with-neon-sql-editor
This example demonstrates how to use the `\d` meta-command to view the schema of a specific table named `playing_with_neon`.
```sql
\d playing_with_neon
```
--------------------------------
### Get Current Organization Plugin Configuration
Source: https://neon.com/docs/auth/guides/plugins/organization
Retrieve the current configuration settings for the organization plugin using the Neon API. This is useful for auditing or understanding the existing setup.
```bash
curl -X GET \
'https://console.neon.tech/api/v2/projects/{project_id}/branches/{branch_id}/auth/plugins' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer $NEON_API_KEY'
```
--------------------------------
### Create Products Table
Source: https://neon.com/docs/extensions/unaccent
Sets up a sample 'products' table with an 'id' and 'name' column for demonstrating accent-insensitive search.
```sql
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT
);
INSERT INTO products (name) VALUES
('cafe'),
('café'),
('Café'),
('Café au lait');
```
--------------------------------
### Install Project Dependencies
Source: https://neon.com/docs/guides/auth-clerk
Install the Neon serverless client, Drizzle ORM for database interactions, Drizzle Kit for migrations, dotenv for environment variables, and the Clerk Next.js SDK.
```bash
npm install @neondatabase/serverless drizzle-orm
npm install -D drizzle-kit dotenv
npm install @clerk/nextjs
```
--------------------------------
### Install Neon Extension
Source: https://neon.com/docs/extensions/neon
Use this SQL command to install the neon extension on your Neon database.
```sql
CREATE EXTENSION neon;
```
--------------------------------
### Koyeb CLI Deployment Command
Source: https://neon.com/docs/guides/koyeb
Deploy the example application using the Koyeb CLI. Ensure you replace the placeholder with your actual Neon connection string for the DATABASE_URL.
```bash
koyeb apps init express-neon \
--instance-type free \
--git github.com/koyeb/example-express-prisma \
--git-branch main \
--git-build-command "npm run postgres:init" \
--ports 8080:http \
--routes /:8080 \
--env PORT=8080 \
--env DATABASE_URL="{}
```
--------------------------------
### Set up Environment Variables
Source: https://neon.com/docs/auth/quick-start/nextjs-api-only
Configure your authentication URL and cookie secret in the `.env.local` file. Ensure the cookie secret is at least 32 characters long.
```bash
NEON_AUTH_BASE_URL=https://ep-xxx.neonauth.us-east-1.aws.neon.tech/neondb/auth
NEON_AUTH_COOKIE_SECRET=your-secret-at-least-32-characters-long
```
--------------------------------
### Install postgres.js Dependency
Source: https://neon.com/docs/guides/astro
Install the postgres.js package for connecting to PostgreSQL.
```shell
npm install postgres
```
--------------------------------
### Get Project Postgres Version with Neon CLI
Source: https://neon.com/docs/postgresql/postgres-version-policy
Use the Neon CLI to retrieve project details, including the PostgreSQL version, in JSON format. Ensure the CLI is installed and authenticated.
```bash
neon projects get --output json
```
--------------------------------
### Create a Bun Project
Source: https://neon.com/docs/guides/bun
Initializes a new Bun project and navigates into the project directory.
```shell
mkdir bun-neon-example
cd bun-neon-example
bun init -y
```
--------------------------------
### Initialize Neon Serverless Connection
Source: https://neon.com/docs/import/migrate-from-turso
Example of initializing a database connection using the Neon serverless driver after migration.
```javascript
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
```
--------------------------------
### Get Branch Details with Data Transfer Bytes
Source: https://neon.com/docs/introduction/network-transfer
Retrieves the total data transfer bytes for a specific branch in the current billing period. This value resets at the start of each billing cycle.
```bash
curl --request GET \
--url https://console.neon.tech/api/v2/projects/$PROJECT_ID/branches/$BRANCH_ID \
--header 'Accept: application/json' \
--header 'Authorization: Bearer $NEON_API_KEY'
```
--------------------------------
### Drizzle Migration Generation Output Example
Source: https://neon.com/docs/guides/drizzle
Example output from the 'drizzle-kit generate' command, showing the successful creation of SQL migration files.
```bash
$ npx drizzle-kit generate
No config path provided, using default 'drizzle.config.ts'
Reading config file '/home/user/drizzle/drizzle.config.ts'
1 tables
demo_users 2 columns 0 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0000_clever_purple_man.sql 🚀
```
--------------------------------
### Get Project Details with Data Transfer Bytes
Source: https://neon.com/docs/introduction/network-transfer
Retrieves the total data transfer bytes for a specific project in the current billing period. This value resets at the start of each billing cycle.
```bash
curl --request GET \
--url https://console.neon.tech/api/v2/projects/$PROJECT_ID \
--header 'Accept: application/json' \
--header 'Authorization: Bearer $NEON_API_KEY'
```
--------------------------------
### Example Neon Connection String
Source: https://neon.com/docs/reference/glossary
An example of a connection string for a Neon Postgres database, including user, hostname, and database name.
```bash
postgresql://alex:AbC123dEf@ep-cool-darkness-123456.c-2.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
```
--------------------------------
### Install AI SDK and Dependencies
Source: https://neon.com/docs/compute/functions/agents
Install the necessary npm packages for the AI SDK, Neon provider, and database interaction.
```bash
npm install ai @neondatabase/ai-sdk-provider pg zod
```
--------------------------------
### Install Neon TypeScript SDK
Source: https://neon.com/docs/reference/typescript-sdk
Install the SDK package using npm, yarn, or pnpm.
```bash
npm install @neondatabase/api-client
```
```bash
yarn add @neondatabase/api-client
```
```bash
pnpm add @neondatabase/api-client
```
--------------------------------
### Using lead() with multiple partitions
Source: https://neon.com/docs/functions/window-lead
This example shows how to apply the `lead()` function across multiple partitions simultaneously. The `OVER` clause partitions the data by `device_id` and orders it by `reading_date`, enabling calculations for each device independently.
```sql
WITH readings AS (
SELECT 1 AS device_id, date '2023-01-01' AS reading_date, 25.5 AS temperature
UNION ALL
SELECT 1 AS device_id, date '2023-01-02' AS reading_date, 26.0 AS temperature
UNION ALL
SELECT 2 AS device_id, date '2023-01-01' AS reading_date, 22.1 AS temperature
UNION ALL
SELECT 1 AS device_id, date '2023-01-03' AS reading_date, 25.8 AS temperature
UNION ALL
SELECT 2 AS device_id, date '2023-01-02' AS reading_date, 21.9 AS temperature
)
SELECT
device_id,
reading_date,
temperature,
lead(temperature) OVER (PARTITION BY device_id ORDER BY reading_date) AS next_temperature,
lead(temperature) OVER (PARTITION BY device_id ORDER BY reading_date) - temperature AS temperature_change
FROM readings;
```
--------------------------------
### Neon App for Slack: Subscribe Command
Source: https://neon.com/docs/changelog/2025-04-04
Use the `/neon subscribe` command in Slack to re-establish your Neon account connection and begin receiving notifications. The bot will guide you through the necessary setup.
```bash
/neon subscribe
```
--------------------------------
### Install Django and PostgreSQL Driver
Source: https://neon.com/docs/guides/django-migrations
Installs Django, the psycopg2-binary driver for PostgreSQL, python-dotenv for environment variables, and dj-database-url for parsing database URLs. Saves installed packages to requirements.txt.
```bash
pip install Django "psycopg2-binary"
pip install python-dotenv dj-database-url
pip freeze > requirements.txt
```
--------------------------------
### Local Wrangler Output Example
Source: https://neon.com/docs/guides/cloudflare-pages
Example output from running 'wrangler pages dev', showing local server readiness and environment variable access.
```bash
❯ npx wrangler pages dev -- npm run dev
Running npm run dev...
.
.
.
.
-------------------
Using vars defined in .dev.vars
Your worker has access to the following bindings:
- Vars:
- DATABASE_URL: "(hidden)"
⎔ Starting local server...
[wrangler:inf] Ready on http://localhost:8788
```
--------------------------------
### Install node-postgres dependencies
Source: https://neon.com/docs/guides/cloudflare-hyperdrive
Install the 'pg' package and its types for Node.js.
```bash
npm install pg
npm install -D @types/pg
```
--------------------------------
### Install Auth.js and Neon Dependencies
Source: https://neon.com/docs/guides/auth-authjs
Install the necessary packages for Auth.js, the Neon Postgres adapter, and the Neon serverless client.
```bash
cd guide-neon-next-authjs
npm install next-auth@beta
npm install @auth/pg-adapter @neondatabase/serverless
```
--------------------------------
### Install Neon CLI with bun
Source: https://neon.com/docs/cli/install
Install the Neon CLI globally using bun. This is an alternative package manager.
```bash
bun install -g neonctl
```
--------------------------------
### Start Next.js Development Server
Source: https://neon.com/docs/guides/auth-auth0
Run this command in your project directory to start the Next.js development server. Access the application at http://localhost:3000.
```bash
npm run dev
```
--------------------------------
### DocsList Component Structure Example
Source: https://neon.com/docs/community/component-architecture
Provides a specific example of the file structure for the DocsList component, including its implementation, export, and image assets.
```text
src/components/pages/doc/docs-list/
├── docs-list.jsx # Main component implementation
├── index.js # Export: export { default } from './docs-list'
└── images/ # Component-specific images
├── docs.inline.svg
└── repo.inline.svg
```
--------------------------------
### Start Grafbase CLI
Source: https://neon.com/docs/guides/grafbase
Command to start the Grafbase development server.
```bash
npx grafbase dev
```
--------------------------------
### Example Request to Create Anonymized Branch
Source: https://neon.com/docs/workflows/data-anonymization-api
Use this `curl` command to send a POST request to create an anonymized branch. It includes masking rules for specific columns and an option to start anonymization automatically.
```bash
curl -X POST \
'https://console.neon.tech/api/v2/projects/{project_id}/branch_anonymized' \
-H 'Authorization: Bearer $NEON_API_KEY' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"masking_rules": [
{
"database_name": "neondb",
"schema_name": "public",
"table_name": "users",
"column_name": "email",
"masking_function": "pg_catalog.concat(anon.dummy_uuidv4(), '@example.com')"
},
{
"database_name": "neondb",
"schema_name": "public",
"table_name": "users",
"column_name": "age",
"masking_function": "anon.random_int_between(25,65)"
}
],
"start_anonymization": true
}'
```
--------------------------------
### Initialize Full Client
Source: https://neon.com/docs/reference/javascript-sdk
Use `createClient` for authentication and database queries. Ensure environment variables for auth and data API URLs are set.
```typescript
import { createClient } from '@neondatabase/neon-js';
const client = createClient({
auth: {
url: import.meta.env.VITE_NEON_AUTH_URL,
},
dataApi: {
url: import.meta.env.VITE_NEON_DATA_API_URL,
},
});
```
--------------------------------
### Install Project Dependencies
Source: https://neon.com/docs/guides/elixir-ecto
Install the Ecto and Postgrex dependencies after updating your `mix.exs` file. This command fetches the specified packages.
```bash
mix deps.get
```
--------------------------------
### Install ws dependency
Source: https://neon.com/docs/compute/functions/websockets
Install the `ws` package and its types for WebSocket functionality.
```bash
npm install ws
npm install --save-dev @types/ws
```
--------------------------------
### Connect with postgres.js
Source: https://neon.com/docs/guides/node
Use the `postgres` library for a streamlined connection experience. This example connects and retrieves the database version.
```javascript
require('dotenv').config();
const postgres = require('postgres');
const { PGHOST, PGDATABASE, PGUSER, PGPASSWORD } = process.env;
const sql = postgres({
host: PGHOST,
database: PGDATABASE,
username: PGUSER,
password: PGPASSWORD,
port: 5432,
ssl: 'require',
});
async function getPgVersion() {
const result = await sql`select version()`;
console.log(result[0]);
}
getPgVersion();
```
--------------------------------
### Create Table with Default Timestamp
Source: https://neon.com/docs/functions/current_timestamp
This example shows how to create a `purchase_orders` table where the `order_date` column defaults to the current timestamp using `current_timestamp`. New records automatically get the current transaction time.
```sql
CREATE TABLE purchase_orders (
order_id SERIAL PRIMARY KEY,
order_date TIMESTAMP WITH TIME ZONE DEFAULT current_timestamp
);
INSERT INTO purchase_orders (order_id)
VALUES (1);
INSERT INTO purchase_orders (order_id)
VALUES (2);
SELECT * FROM purchase_orders;
```
--------------------------------
### Create Node.js Project and Initialize npm
Source: https://neon.com/docs/guides/node
Initializes a new Node.js project and sets up the package.json file.
```shell
mkdir neon-nodejs-example
cd neon-nodejs-example
npm init -y
```
--------------------------------
### Drizzle Migration Application Output Example
Source: https://neon.com/docs/guides/drizzle
Example output from the 'drizzle-kit migrate' command, indicating successful application of migrations.
```bash
$ npx drizzle-kit migrate
No config path provided, using default 'drizzle.config.ts'
Reading config file '/home/user/drizzle/drizzle.config.ts'
Using 'pg' driver for database querying
```
--------------------------------
### Install Lakebase Search Dependencies
Source: https://neon.com/docs/ai/lakebase-search-get-started
Install the necessary packages for Neon serverless, OpenAI, and environment variable management.
```bash
npm install @neondatabase/serverless openai dotenv
```
--------------------------------
### Initialize Node.js Project with Express
Source: https://neon.com/docs/guides/sequelize
Sets up a new Node.js project with Express.js, initializing npm and creating necessary files.
```bash
mkdir neon-sequelize-guide && cd neon-sequelize-guide
npm init -y && touch .env index.js
npm install express dotenv
```
--------------------------------
### Install Neon CLI with NPM
Source: https://neon.com/docs/get-started/signing-up
Use this command to install the Neon CLI on any platform that supports Node.js.
```bash
npm install -g neonctl
```
--------------------------------
### Install Inngest Client
Source: https://neon.com/docs/guides/trigger-serverless-functions
Install the Inngest client package using npm. This is the first step to integrating Inngest with your project.
```bash
npm i inngest
```
--------------------------------
### Create Table for Time Zone Examples
Source: https://neon.com/docs/data-types/date-and-time
Create a table with TIMESTAMP (timezone-unaware) and TIMESTAMPTZ (timezone-aware) columns to demonstrate time zone handling in Postgres. This setup is crucial for observing how time zone information is stored and displayed.
```sql
CREATE TABLE time_example (
ts TIMESTAMP,
tstz_utc TIMESTAMPTZ,
tstz_pst TIMESTAMPTZ
);
INSERT INTO time_example (ts, tstz_utc, tstz_pst)
VALUES
('2024-01-01 09:00:00-08', '2024-01-01 09:00:00+00', '2024-01-01 09:00:00-08');
```
--------------------------------
### Install Prisma Read Replicas Extension
Source: https://neon.com/docs/guides/read-replica-integrations
Install the `@prisma/extension-read-replicas` package using npm. This is the first step to enabling read replica support in Prisma.
```bash
npm install @prisma/extension-read-replicas
```
--------------------------------
### Basic pg_repack command with connection details
Source: https://neon.com/docs/extensions/pg_repack
This is a basic example of how to use pg_repack, specifying connection parameters for your Neon database and the table to repack.
```bash
pg_repack -k -h -p 5432 -d -U --table your_table_name
```
--------------------------------
### Install Encore CLI on macOS
Source: https://neon.com/docs/guides/encore
Use Homebrew to install the Encore CLI on macOS.
```bash
brew install encoredev/tap/encore
```
--------------------------------
### Configure CORS for R2 Bucket
Source: https://neon.com/docs/guides/cloudflare-r2
Example CORS configuration for an R2 bucket to allow PUT uploads and GET requests from specific origins. Replace placeholder domains with your actual frontend application URL and local development server.
```json
[
{
"AllowedOrigins": [
"https://your-production-app.com",
"http://localhost:3000"
],
"AllowedMethods": ["PUT", "GET"]
}
]
```
--------------------------------
### Install Python Dependencies
Source: https://neon.com/docs/storage/get-started
Install the boto3 library for S3 interaction and python-dotenv for loading environment variables.
```bash
pip install boto3 python-dotenv
```
--------------------------------
### pgloader migration output example
Source: https://neon.com/docs/import/migrate-from-planetscale
This is an example of the output you can expect when running a pgloader migration. It details the time taken for various stages of the import process.
```bash
LOG report summary reset
table name errors rows bytes total time
----------------------- --------- --------- --------- --------------
fetch meta data 0 2 0.727s
Create Schemas 0 0 0.346s
Create SQL Types 0 0 0.178s
Create tables 0 2 0.551s
Set Table OIDs 0 1 0.094s
----------------------- --------- --------- --------- --------------
"db-test".dbname 0 1 0.0 kB 0.900s
----------------------- --------- --------- --------- --------------
COPY Threads Completion 0 4 0.905s
Index Build Completion 0 1 0.960s
Create Indexes 0 1 0.257s
Reset Sequences 0 0 1.083s
Primary Keys 0 1 0.263s
Create Foreign Keys 0 0 0.000s
Create Triggers 0 0 0.169s
Set Search Path 0 1 0.427s
Install Comments 0 0 0.000s
----------------------- --------- --------- --------- --------------
Total import time ✓ 1 0.0 kB 4.064s
```
--------------------------------
### Install TypeScript API Client
Source: https://neon.com/docs/reference/api-reference
Install the necessary package for interacting with the Neon API using TypeScript.
```bash
npm install @neondatabase/api-client
```
--------------------------------
### Install neon-js Client Library
Source: https://neon.com/docs/data-api/get-started
Install the `@neondatabase/neon-js` library for projects using Neon Auth. This library simplifies token management.
```bash
npm install @neondatabase/neon-js
```
--------------------------------
### Start Python Project with app.build CLI
Source: https://neon.com/docs/changelog/2025-07-18
Use this command to initialize a new Python project with app.build, enabling the creation of data apps and ML dashboards on Neon.
```bash
npx @app.build/cli --template=python
```
--------------------------------
### Create a SELECT Policy with RLS
Source: https://neon.com/docs/data-api/database-advisor
Example of creating a Row Level Security policy for SELECT operations, restricting access based on user ID. This assumes an 'auth.uid()' function is available to get the current user's ID.
```sql
CREATE POLICY restrict_access ON .
FOR SELECT
USING ((SELECT auth.uid()) = user_id);
```
--------------------------------
### Create Neon Project
Source: https://neon.com/docs/reference/typescript-sdk
This example shows how to create a new Neon project using the SDK. It includes specifying the project name, region, and PostgreSQL version, and outputs the connection string for the newly created project.
```APIDOC
## Create Project
This operation creates a new Neon project with the specified configuration.
### Method
`apiClient.createProject(params: { project: CreateProjectParams }): Promise `
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **project** (Object) - Required - Configuration for the new project.
- **name** (string) - Required - The name of the project.
- **region_id** (string) - Required - The ID of the cloud region where the project will be hosted (e.g., 'aws-us-east-1').
- **pg_version** (number) - Required - The major PostgreSQL version to use (e.g., 17).
### Request Example
```typescript
import { createApiClient } from '@neondatabase/api-client';
const apiClient = createApiClient({
apiKey: process.env.NEON_API_KEY!,
});
async function createNeonProject(projectName: string) {
try {
const response = await apiClient.createProject({
project: {
name: projectName,
region_id: 'aws-us-east-1',
pg_version: 17,
},
});
console.log('Project created:', response.data.project);
console.log('Project ID:', response.data.project.id);
console.log('Database connection string:', response.data.connection_uris[0].connection_uri);
} catch (error) {
console.error('Error creating project:', error);
throw error;
}
}
// Example usage: Create a project named "test-project"
createNeonProject('test-project').catch((error) => {
console.error('Error creating project:', error.message);
});
```
### Response
#### Success Response (200)
Returns details of the newly created project and its connection URIs.
- **data.project** (Project) - The created Neon project object.
- **data.connection_uris** (Array) - An array of connection URIs for the project.
#### Response Example
```json
{
"project": {
"id": "example-project-id",
"name": "test-project",
"region_id": "aws-us-east-1",
"pg_version": 17,
"created_at": "2025-03-01T10:00:00Z",
"updated_at": "2025-03-01T10:00:00Z"
// ... other project details
},
"connection_uris": [
{
"connection_uri": "postgresql://user:password@host:port/database?sslmode=require"
}
]
}
```
```
--------------------------------
### Offload AI Requests with step.ai.infer()
Source: https://neon.com/docs/ai/inngest
Utilize `step.ai.infer()` to offload AI requests to the LLM provider, pausing the workflow while waiting for a response. This minimizes serverless compute usage. This example shows how to get a prompt and then infer AI output.
```typescript
import { inngest } from '@/inngest';
import { getPromptForToolsSearch, vectorSearch } from '@/helpers';
export const ragWorkflow = client.createFunction(
{ id: 'rag-workflow', concurrency: 10 },
{ event: 'chat.message' },
async ({ event, step }) => {
const { message } = event.data;
const prompt = getPromptForToolsSearch(message);
await step.ai.infer('tools.search', {
model: openai({ model: 'gpt-4o' }),
body: {
messages: prompt,
},
});
// other steps...
}
);
```
--------------------------------
### Launch Exograph development server
Source: https://neon.com/docs/guides/exograph
Start the Exograph development server by setting the `EXO_POSTGRES_URL` environment variable to your Neon connection string and running `exo dev`.
```bash
EXO_POSTGRES_URL= exo dev
```
--------------------------------
### Initialize Full Client
Source: https://neon.com/docs/reference/javascript-sdk
Creates a full client instance that provides both authentication and database query methods. Requires both auth and data API URLs.
```APIDOC
## Initialize Full Client
Use `createClient()` to initialize a client with both authentication and database query capabilities.
### Method Signature
```typescript
createClient(options: {
auth: {
url: string;
};
dataApi: {
url: string;
};
}): NeonClient;
```
### Example
```typescript
import { createClient } from '@neondatabase/neon-js';
const client = createClient({
auth: {
url: import.meta.env.VITE_NEON_AUTH_URL,
},
dataApi: {
url: import.meta.env.VITE_NEON_DATA_API_URL,
},
});
```
```
--------------------------------
### Verify Liquibase Installation
Source: https://neon.com/docs/guides/liquibase
Confirm that the Liquibase CLI is installed and accessible by checking its version.
```bash
liquibase --version
...
Liquibase Version: x.yy.z
Liquibase Open Source x.yy.z by Liquibase
```
--------------------------------
### Attach Database Pool with Drizzle ORM on Vercel
Source: https://neon.com/docs/guides/vercel-connection-methods
Example using Drizzle ORM with `attachDatabasePool` from `@vercel/functions` for efficient connection pooling with Postgres TCP on Vercel Fluid compute. This setup establishes a TCP connection on the first request and reuses it for subsequent queries.
```typescript
import { attachDatabasePool } from '@vercel/functions';
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import * as schema from './schema';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
attachDatabasePool(pool);
export const db = drizzle({ client: pool, schema });
```
--------------------------------
### Run the Application
Source: https://neon.com/docs/guides/dotnet-entity-framework
Execute the command to start your .NET application. Access the Swagger UI to test your API endpoints.
```bash
dotnet run
```
--------------------------------
### Stytch Example JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of a Stytch JWKS URL with a specific Project ID.
```bash
https://test.stytch.com/v1/sessions/jwks/my-awesome-project
```
--------------------------------
### Using LAG() with a Default Value
Source: https://neon.com/docs/functions/window-lag
When the offset in LAG() goes beyond the start of the window frame, it returns null by default. You can specify a default value to use instead, so the resulting column does not contain nulls. This example uses the current quantity as the default for the first row.
```sql
WITH inventory AS (
SELECT date '2023-01-01' AS snapshot_date, 100 AS quantity
UNION ALL
SELECT date '2023-01-02' AS snapshot_date, 80 AS quantity
UNION ALL
SELECT date '2023-01-03' AS snapshot_date, 120 AS quantity
UNION ALL
SELECT date '2023-01-04' AS snapshot_date, 90 AS quantity
)
SELECT
snapshot_date,
quantity,
lag(quantity, 1, quantity) OVER (ORDER BY snapshot_date) AS prev_quantity,
quantity - lag(quantity, 1, quantity) OVER (ORDER BY snapshot_date) AS change
FROM inventory;
```
--------------------------------
### Install Neon Auth SDK
Source: https://neon.com/docs/auth/quick-start/tanstack-router
Install the Neon Auth SDK and UI library into your TanStack Router project.
```bash
cd my-app && npm install @neondatabase/neon-js@latest @neondatabase/auth-ui
```
--------------------------------
### GitHub Workflow Template
Source: https://neon.com/docs/guides/multitenancy
This template generates a GitHub Actions workflow file for a specific Neon project. It automates database migration jobs triggered by pushes to the main branch or manual dispatch, including checkout, Node.js setup, dependency installation, and migration execution.
```javascript
// src/templates/github-workflow.js
export const githubWorkflow = (projectName, configFileName) => {
const secretName = projectName.toUpperCase().replace(/\s+/g, '_');
const jobName = projectName.toLowerCase().replace(/\s+/g, '-');
return `name: ${projectName} DB Migration
on:
push:
branches:
- main
paths:
- 'src/db/schema.ts'
workflow_dispatch:
jobs:
migrate-${jobName}:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run Drizzle Migrations
env:
${secretName}_CONNECTION_STRING: $${{ secrets.${secretName}_CONNECTION_STRING }}
run: npx drizzle-kit push:pg --config ./configs/${configFileName}
`;
};
```
--------------------------------
### Reflex Initialization Output
Source: https://neon.com/docs/guides/reflex
Example output from the 'reflex init' command, showing the initialization process and success message.
```bash
$ reflex init
──────────────────────────────────────────── Initializing with_reflex ─────────────────────────────────────────────
[07:20:37] Initializing the web directory. console.py:231
Get started with a template:
(0) Try our free AI builder.
(1) A blank Reflex app.
(2) Premade templates built by the Reflex team.
Which template would you like to use? (0): 1
[07:20:39] Initializing the app directory. console.py:231
Success: Initialized with_reflex using the blank template.
```
--------------------------------
### List available templates
Source: https://neon.com/docs/cli/bootstrap
Use the --list-templates option to see all available starter templates for scaffolding.
```bash
neonctl bootstrap --list-templates
```
--------------------------------
### Install Neon Serverless Driver
Source: https://neon.com/docs/serverless/serverless-driver
Install the Neon serverless driver using npm. TypeScript types are included.
```shell
npm install @neondatabase/serverless
```
--------------------------------
### Create Sample Table and Data for Testing
Source: https://neon.com/docs/guides/logical-replication-cloud-sql
Use these SQL statements to create a sample table and populate it with data for testing logical replication. Ensure your database and schema might differ.
```sql
CREATE TABLE IF NOT EXISTS playing_with_neon(id SERIAL PRIMARY KEY, name TEXT NOT NULL, value REAL);
INSERT INTO playing_with_neon(name, value)
SELECT LEFT(md5(i::TEXT), 10), random() FROM generate_series(1, 10) s(i);
```
--------------------------------
### View Flyway Installation Contents
Source: https://neon.com/docs/guides/flyway
Navigate to your Flyway installation directory and list its contents to confirm the extraction. This helps verify the installation.
```bash
cd ~/flyway-x.y.z
ls
```
--------------------------------
### Example pg_restore Command with Connection String
Source: https://neon.com/docs/guides/export-neon-postgres-compatible
An example of the `pg_restore` command using a sample PostgreSQL connection string and a common dump file name. This demonstrates how to connect to the destination database and specify the dump file.
```bash
pg_restore -v -d "postgresql://user:password@db.example.com:5432/mydb?sslmode=require" mydatabase.bak
```
--------------------------------
### Install EF Core Tools
Source: https://neon.com/docs/guides/entity-migrations
Installs the Entity Framework Core command-line tools globally, which are required for generating and applying migrations.
```bash
dotnet tool install --global dotnet-ef
```
--------------------------------
### Bootstrap ai-sdk Template
Source: https://neon.com/docs/ai-gateway/overview
Use this command to bootstrap the ai-sdk starter template, which utilizes AI Gateway for image generation.
```bash
neonctl bootstrap --template ai-sdk
```
--------------------------------
### Install Python Dependencies
Source: https://neon.com/docs/guides/azure-blob-storage
Installs the necessary Python packages for Flask, Azure Blob Storage, and PostgreSQL interaction. Ensure you have Python and pip installed.
```bash
pip install Flask azure-storage-blob psycopg2-binary python-dotenv python-dateutil
```
--------------------------------
### Install Neon Serverless Driver
Source: https://neon.com/docs/guides/grafbase
Install the Neon serverless driver within the Grafbase directory of your project.
```bash
cd ..
npm init -y
npm install @neondatabase/serverless
```
--------------------------------
### Install pgrag and Model Extensions
Source: https://neon.com/docs/extensions/pgrag
Installs the pgrag extension along with model extensions for tokenizing, embedding, and reranking. Cascade ensures pgvector is also installed.
```sql
create extension if not exists rag cascade;
create extension if not exists rag_bge_small_en_v15 cascade;
create extension if not exists rag_jina_reranker_v1_tiny_en cascade;
```
--------------------------------
### Install jose library for Node.js
Source: https://neon.com/docs/auth/guides/plugins/jwt
Install the 'jose' library, which is required for JWT verification in Node.js.
```bash
npm install jose
```
--------------------------------
### Insert sample data into 'books_to_read' table
Source: https://neon.com/docs/guides/cloudflare-hyperdrive
Use this SQL command to populate the 'books_to_read' table with sample book entries for testing.
```sql
INSERT INTO books_to_read (title, author)
VALUES
('The Way of Kings', 'Brandon Sanderson'),
('The Name of the Wind', 'Patrick Rothfuss'),
('Coders at Work', 'Peter Seibel'),
('1984', 'George Orwell');
```
--------------------------------
### Install pg_mooncake Extension
Source: https://neon.com/docs/extensions/pg_mooncake
After enabling unstable extensions, install the pg_mooncake extension using the CREATE EXTENSION command.
```sql
CREATE EXTENSION pg_mooncake;
```
--------------------------------
### Start Rails Development Server
Source: https://neon.com/docs/guides/ruby-on-rails
Run this command from the project root to start the Rails server in the development environment.
```shell
bin/rails server -e development
```
--------------------------------
### Install Claude Code Plugin for Neon
Source: https://neon.com/docs/changelog/2025-10-24
Use these commands to install the Neon plugin within Claude Code from the marketplace. Ensure you have the necessary permissions to install plugins.
```bash
/plugin marketplace add neondatabase-labs/ai-rules
/plugin install neon-plugin@neon
```
--------------------------------
### Neon CLI Connection String Example
Source: https://neon.com/docs/changelog/2025-07-25
This example shows the updated Neon CLI command to retrieve a project's connection string, now including the channel_binding=require option for enhanced security.
```bash
neon cs --project-id purple-cake-43891234
```
--------------------------------
### Descope Example JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of a Descope JWKS URL with a specific Project ID.
```bash
https://api.descope.com/P1234/.well-known/jwks.json
```
--------------------------------
### Install a PostgreSQL Extension
Source: https://neon.com/docs/extensions/pg-extensions
Use this SQL command to install a supported extension. Ensure you replace `` with the actual name of the extension.
```sql
CREATE EXTENSION ;
```
--------------------------------
### Install TypeScript and Node Types
Source: https://neon.com/docs/guides/kysely
Installs TypeScript, tsx, and Node.js type definitions, and initializes a tsconfig.json file.
```bash
npm install -D typescript tsx @types/node
npx tsc --init
```
--------------------------------
### Example Neon Connection String with sslmode
Source: https://neon.com/docs/connect/connect-securely
This is an example of a Neon connection string with the sslmode parameter set to 'verify-full'.
```text
postgresql://[user]:[password]@[neon_hostname]/[dbname]?sslmode=verify-full
```
--------------------------------
### Install postgrest-js Client Library
Source: https://neon.com/docs/data-api/get-started
Install the `@neondatabase/postgrest-js` library to use with any JWT-issuing authentication provider like Auth0, Clerk, or Firebase Auth.
```bash
npm install @neondatabase/postgrest-js
```
--------------------------------
### Install Python Dependencies
Source: https://neon.com/docs/guides/cloudinary
Install Flask, the Cloudinary Python SDK, psycopg2, and python-dotenv for managing environment variables.
```bash
pip install Flask cloudinary psycopg2-binary python-dotenv
```
--------------------------------
### Create users table and insert sample data
Source: https://neon.com/docs/functions/jsonb_extract_path_text
Sets up a table with a JSONB column and populates it with user profiles.
```sql
CREATE TABLE users (
id INT,
profile JSONB
);
INSERT INTO users (id, profile)
VALUES
(1, '{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "1234567890"}, "hobbies": ["reading", "cycling", "hiking"]}'),
(2, '{"name": "Bob", "contact": {"email": "bob@example.com", "phone": "0987654321"}, "hobbies": ["gaming", "cooking"]}');
```
--------------------------------
### Example Read Replica Connection String
Source: https://neon.com/docs/guides/read-only-access-read-replicas
This is an example of a connection string for a Neon read replica. Provide this string to partners or applications that require read-only access.
```bash
postgresql://partner:partner_password@ep-read-replica-12345.us-east-2.aws.neon.tech/sales_db?sslmode=require&channel_binding=require
```
--------------------------------
### Create and Insert Events Table
Source: https://neon.com/docs/functions/extract
Sets up a sample 'events' table with event names and timestamps, then inserts sample data for demonstration purposes.
```sql
CREATE TABLE events (
event_id SERIAL PRIMARY KEY,
event_name VARCHAR(100),
event_timestamp TIMESTAMP WITH TIME ZONE
);
INSERT INTO events (event_name, event_timestamp) VALUES
('Conference A', '2024-03-15 09:00:00+00'),
('Workshop B', '2024-06-22 14:30:00+00'),
('Seminar C', '2024-09-10 11:15:00+00'),
('Conference D', '2024-12-05 10:00:00+00'),
('Workshop E', '2025-02-18 13:45:00+00');
```
--------------------------------
### Example Neon Database Connection String
Source: https://neon.com/docs/manage/backup-pg-dump
This is an example of a direct connection string for a Neon database. Ensure you deselect connection pooling when retrieving your string.
```bash
postgresql://alex:AbC123dEf@ep-dry-morning-a8vn5za2.us-east-2.aws.neon.tech/neondb?sslmode=require&channel_binding=require
```
--------------------------------
### Connect with Go
Source: https://neon.com/docs/get-started/connect-neon
Example of connecting to Neon from a Go application using the standard database/sql package and lib/pq driver. Requires the DATABASE_URL environment variable and godotenv for loading.
```go
// Go example
package main
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/lib/pq"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
connStr := os.Getenv("DATABASE_URL")
if connStr == "" {
panic("DATABASE_URL environment variable is not set")
}
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
defer db.Close()
var version string
if err := db.QueryRow("select version()").Scan(&version); err != nil {
panic(err)
}
fmt.Printf("version=%s\n", version)
}
```
--------------------------------
### pgbench Test Output Example
Source: https://neon.com/docs/extensions/neon-utils
This is an example of the output you might see when running a pgbench test on Neon. The performance metrics can vary based on compute configuration.
```bash
pgbench (15.3)
starting vacuum...end.
progress: 8.4 s, 0.0 tps, lat 0.000 ms stddev 0.000, 0 failed
progress: 9.0 s, 0.0 tps, lat 0.000 ms stddev 0.000, 0 failed
progress: 10.0 s, 4.0 tps, lat 1246.290 ms stddev 3.253, 0 failed
progress: 11.0 s, 6.0 tps, lat 1892.455 ms stddev 446.686, 0 failed
progress: 12.0 s, 9.0 tps, lat 2091.352 ms stddev 1068.303, 0 failed
progress: 13.0 s, 5.0 tps, lat 1881.682 ms stddev 700.852, 0 failed
progress: 14.0 s, 6.0 tps, lat 2660.009 ms stddev 1404.672, 0 failed
progress: 15.0 s, 9.0 tps, lat 2354.776 ms stddev 1248.686, 0 failed
progress: 16.0 s, 8.0 tps, lat 1770.870 ms stddev 776.465, 0 failed
progress: 17.0 s, 7.0 tps, lat 1800.686 ms stddev 611.749, 0 failed
progress: 18.0 s, 18.0 tps, lat 1681.841 ms stddev 1187.918, 0 failed
progress: 19.0 s, 29.0 tps, lat 561.201 ms stddev 139.565, 0 failed
progress: 20.0 s, 27.0 tps, lat 507.782 ms stddev 153.889, 0 failed
progress: 21.0 s, 30.0 tps, lat 493.312 ms stddev 121.688, 0 failed
progress: 22.0 s, 32.0 tps, lat 513.444 ms stddev 185.033, 0 failed
progress: 23.0 s, 32.0 tps, lat 503.135 ms stddev 199.435, 0 failed
progress: 24.0 s, 28.0 tps, lat 492.913 ms stddev 124.019, 0 failed
progress: 25.0 s, 43.0 tps, lat 366.719 ms stddev 123.547, 0 failed
progress: 26.0 s, 49.0 tps, lat 334.276 ms stddev 79.043, 0 failed
progress: 27.0 s, 40.0 tps, lat 354.922 ms stddev 83.560, 0 failed
progress: 28.0 s, 31.0 tps, lat 400.645 ms stddev 29.236, 0 failed
progress: 29.0 s, 48.0 tps, lat 373.522 ms stddev 64.446, 0 failed
progress: 30.0 s, 44.0 tps, lat 333.343 ms stddev 86.497, 0 failed
progress: 31.0 s, 44.0 tps, lat 326.754 ms stddev 82.990, 0 failed
progress: 32.0 s, 44.0 tps, lat 329.317 ms stddev 76.728, 0 failed
progress: 33.0 s, 53.0 tps, lat 321.572 ms stddev 76.427, 0 failed
progress: 34.0 s, 57.0 tps, lat 254.500 ms stddev 33.013, 0 failed
progress: 35.0 s, 60.0 tps, lat 251.035 ms stddev 37.574, 0 failed
progress: 36.0 s, 58.0 tps, lat 256.846 ms stddev 36.390, 0 failed
progress: 37.0 s, 60.0 tps, lat 249.165 ms stddev 36.764, 0 failed
progress: 38.0 s, 57.0 tps, lat 263.885 ms stddev 31.351, 0 failed
progress: 39.0 s, 56.0 tps, lat 262.529 ms stddev 43.900, 0 failed
progress: 40.0 s, 58.0 tps, lat 259.052 ms stddev 39.737, 0 failed
...
```
--------------------------------
### Install node-postgres Dependency
Source: https://neon.com/docs/guides/astro
Install the node-postgres package for connecting to PostgreSQL.
```shell
npm install pg
```
--------------------------------
### Interactive link output example
Source: https://neon.com/docs/cli/link
Example output from an interactive `neonctl link` session, showing organization and project selection, new project creation, and confirmation of the linked context.
```text
? Which organization would you like to link? ' Personal Org (org-abc123)
? Which project would you like to link? ' + Create new project
? Name for the new project: ' my-app
? Which region should the new project run in? ' AWS US East (Ohio) (aws-us-east-2)
Created project polished-snowflake-12345678 ("my-app") in aws-us-east-2.
Linked .neon:
orgId: org-abc123
projectId: polished-snowflake-12345678
branchId: br-steep-math-aiu3vve7
```
--------------------------------
### Example WorkOS JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of a WorkOS JWKS URL, given a specific Client ID.
```bash
https://api.workos.com/sso/jwks/client_12345
```
--------------------------------
### Example PostgreSQL Version Output
Source: https://neon.com/docs/guides/ruby-on-rails
This is an example of the output you will see in your browser when the application successfully connects to the Neon database and displays its PostgreSQL version.
```text
PostgreSQL 15.5 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
```
--------------------------------
### Note Admonition Example
Source: https://neon.com/docs/community/contribution-guide
An example of a basic note admonition in Markdown.
```markdown
This is an important note
```
--------------------------------
### Neon Database Connection String Example
Source: https://neon.com/docs/guides/bemi
This is an example of a Neon database connection string. Ensure you replace placeholders with your actual database credentials and host information.
```sql
postgresql://neondb_owner:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/neondb?sslmode=require&channel_binding=require
```
--------------------------------
### Install Neon Auth UI Package
Source: https://neon.com/docs/auth/reference/ui-components
Install the necessary Neon JS and Auth UI packages using npm.
```bash
npm install @neondatabase/neon-js@latest @neondatabase/auth-ui
```
--------------------------------
### Create Sample Table 1
Source: https://neon.com/docs/extensions/pg_prewarm
Creates the first sample table for performance comparison.
```sql
CREATE TABLE tbl_transactions_1
(
tran_id_ SERIAL,
transaction_date TIMESTAMPTZ,
transaction_name TEXT
);
INSERT INTO tbl_transactions_1
(transaction_date, transaction_name)
SELECT x, 'dbrnd'
FROM generate_series('2010-01-01 00:00:00'::timestamptz, '2018-02-01 00:00:00'::timestamptz, '1 minutes'::interval) a(x);
```
--------------------------------
### Install pgloader on Debian/Ubuntu
Source: https://neon.com/docs/import/migrate-sqlite
Installs the pgloader utility on Debian or Ubuntu systems using apt-get. This is a prerequisite for migrating databases.
```shell
sudo apt-get install pgloader
```
--------------------------------
### Run Reflex Development Server
Source: https://neon.com/docs/guides/reflex
Use this command in your project directory to start the Reflex development server. The app will be accessible at http://localhost:3000.
```bash
reflex run
```
--------------------------------
### Run Java Transaction Example
Source: https://neon.com/docs/guides/java
Execute the Java transaction example using Maven. Ensure your project is configured with the necessary dependencies.
```bash
mvn exec:java -Dexec.mainClass="com.neon.quickstart.TransactionExample"
```
--------------------------------
### Uninstall libsql/client and Install Neon Serverless
Source: https://neon.com/docs/import/migrate-from-turso
Use npm to remove the libsql/client package and install the Neon serverless driver or the pg package.
```bash
npm uninstall @libsql/client
npm install @neondatabase/serverless # or npm install pg
```
--------------------------------
### Install Neon Serverless Driver Dependency
Source: https://neon.com/docs/guides/astro
Install the Neon serverless driver package for connecting to Neon Postgres.
```shell
npm install @neondatabase/serverless
```
--------------------------------
### PostgreSQL Connection String Example
Source: https://neon.com/docs/connect/connect-postgres-gui
This is an example of a PostgreSQL connection string used to connect to Neon. It shows the format for role, hostname, and database name.
```text
postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
^ ^ ^
|- |- |-
```
--------------------------------
### Install Dependencies
Source: https://neon.com/docs/compute/functions/get-started
Install the necessary npm packages for your Neon Function project, including the Neon config, Hono for routing, and pg for Postgres interaction. Also install types for pg.
```bash
npm install @neondatabase/config hono pg
npm install --save-dev @types/pg
```
--------------------------------
### Example Completion Script Output
Source: https://neon.com/docs/cli/completion
This is an example of the output generated by `neonctl completion`. It contains shell functions and configurations for enabling tab completion.
```text
###-begin-neonctl-completions-###
#
# yargs command completion script
#
# Installation: neonctl completion >> ~/.bashrc
# or neonctl completion >> ~/.bash_profile on OSX.
#
_neonctl_yargs_completions()
{
local cur_word args type_list
cur_word="${COMP_WORDS[COMP_CWORD]}"
args=("${COMP_WORDS[@]}")
# ask yargs to generate completions.
type_list=$(neonctl --get-yargs-completions "${args[@]}")
COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )
# if no match was found, fall back to filename completion
if [ ${#COMPREPLY[@]} -eq 0 ]; then
COMPREPLY=()
fi
return 0
}
complete -o bashdefault -o default -F _neonctl_yargs_completions neonctl
###-end-neonctl-completions-###
```
--------------------------------
### Install Dependencies
Source: https://neon.com/docs/guides/backblaze-b2
Install the necessary Python packages for Flask, AWS SDK (boto3), PostgreSQL driver, and environment variable management.
```bash
pip install Flask boto3 psycopg2-binary python-dotenv
```
--------------------------------
### Run Development Server
Source: https://neon.com/docs/auth/migrate/from-supabase
Start your application in development mode using npm. This command is used to test the migration and verify that authentication and database queries function correctly.
```bash
npm run dev
```
--------------------------------
### Run FastAPI Server
Source: https://neon.com/docs/guides/sqlalchemy-migrations
Starts the FastAPI development server using uvicorn.
```bash
python main.py
```
--------------------------------
### Install pg_cron Extension
Source: https://neon.com/docs/extensions/pg_cron
Run this SQL command in your Neon database to install the pg_cron extension after enabling it and restarting your compute.
```sql
CREATE EXTENSION IF NOT EXISTS pg_cron;
```
--------------------------------
### Create and Populate Sample Table via SQL Editor
Source: https://neon.com/docs/get-started/signing-up
Use this SQL command to create a new table named 'playing_with_neon' and populate it with sample data. This is typically done the first time you open the SQL Editor for a new project.
```sql
CREATE TABLE IF NOT EXISTS playing_with_neon(id SERIAL PRIMARY KEY, name TEXT NOT NULL, value REAL);
INSERT INTO playing_with_neon(name, value)
SELECT LEFT(md5(i::TEXT), 10), random() FROM generate_series(1, 10) s(i);
```
--------------------------------
### Add Start Script to package.json
Source: https://neon.com/docs/guides/prisma-migrations
Configure the start script in your package.json to run the Express API using tsx.
```bash
npm pkg set scripts.start="tsx src/index.ts"
```
--------------------------------
### Neon Serverless Driver Connection Examples
Source: https://neon.com/docs/changelog/2023-11-10
Examples for connecting to Neon using HTTP and WebSockets with the serverless driver. These are intended for use within the Connection Details widget.
```text
HTTP Connection:
psql "postgresql://user:password@host:port/dbname?sslmode=require&options=--cluster%3D"
WebSockets Connection:
psql "postgresql://user:password@host:port/dbname?sslmode=require&channel_protocol=ws&options=--cluster%3D"
```
--------------------------------
### Seed Database with Sample Data
Source: https://neon.com/docs/guides/sequelize
Create and populate your database with initial data using a seed script. This example demonstrates creating authors and associating books with them.
```javascript
// seed.js
const { Sequelize, DataTypes } = require('sequelize');
const { config } = require('dotenv');
config();
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is not set');
}
const sequelize = new Sequelize(process.env.DATABASE_URL, {
dialectOptions: {
ssl: {
require: true,
},
},
});
const Author = require('./models/author')(sequelize, DataTypes);
const Book = require('./models/book')(sequelize, DataTypes);
const seedDatabase = async () => {
const author = await Author.create({
name: 'J.K. Rowling',
bio: 'The creator of the Harry Potter series',
});
await Book.create({ title: "Harry Potter and the Philosopher's Stone", authorId: author.id });
await Book.create({ title: 'Harry Potter and the Chamber of Secrets', authorId: author.id });
const author2 = await Author.create({
name: 'J.R.R. Tolkien',
bio: 'The creator of Middle-earth and author of The Lord of the Rings.',
});
await Book.create({ title: 'The Hobbit', authorId: author2.id });
await Book.create({ title: 'The Fellowship of the Ring', authorId: author2.id });
await Book.create({ title: 'The Two Towers', authorId: author2.id });
await Book.create({ title: 'The Return of the King', authorId: author2.id });
const author3 = await Author.create({
name: 'George R.R. Martin',
bio: 'The author of the epic fantasy series A Song of Ice and Fire.',
});
await Book.create({ title: 'A Game of Thrones', authorId: author3.id });
await Book.create({ title: 'A Clash of Kings', authorId: author3.id });
await sequelize.close();
};
seedDatabase();
```
--------------------------------
### Stack Auth Example JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of a Stack Auth JWKS URL with a specific Project ID.
```bash
https://api.stack-auth.com/api/v1/projects/my-awesome-project/.well-known/jwks.json
```
--------------------------------
### Project Details Response Example
Source: https://neon.com/docs/introduction/network-transfer
Example JSON snippet showing the 'data_transfer_bytes' field within the project object.
```json
{
"project": {
"data_transfer_bytes": 40821459,
...
}
}
```
--------------------------------
### Install pgloader using Docker
Source: https://neon.com/docs/import/migrate-sqlite
Pulls the latest pgloader Docker image. This is an alternative method for installing pgloader.
```shell
docker pull dimitri/pgloader:latest
```
--------------------------------
### Claimable Postgres CLI .env Output Example
Source: https://neon.com/docs/reference/claimable-postgres
This is an example of the DATABASE_URL written to your .env file after using the neon-new CLI command. It provides the connection string for the provisioned database.
```env
DATABASE_URL=postgresql://neondb_owner:npg_xxxxxxxxxxxx@ep-cool-breeze-a1b2c3d4-pooler.c-2.us-east-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require
```
--------------------------------
### Install Prisma Dependencies
Source: https://neon.com/docs/guides/prisma
Installs the necessary Prisma client, Neon adapter, dotenv for environment variables, and development dependencies like prisma and tsx.
```bash
npm install @prisma/client @prisma/adapter-neon dotenv
npm install prisma tsx --save-dev
```
--------------------------------
### Install Dependencies for B2 Upload Workflow
Source: https://neon.com/docs/guides/backblaze-b2
Install the necessary Node.js packages for interacting with Backblaze B2, Neon, and setting up a web server with Hono.
```bash
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner @neondatabase/serverless @hono/node-server hono dotenv
```
--------------------------------
### Initialize Neon CLI with Preview Flag
Source: https://neon.com/docs/get-started/platform-private-preview
Use this command when prompted by an AI agent to initialize the Neon CLI and begin the private preview setup process.
```text
I'm part of the Neon private preview. Please run and follow `npx neonctl@latest init --preview`
```
--------------------------------
### Create New Django Project
Source: https://neon.com/docs/guides/django-migrations
Creates a new Django project named 'guide_neon_django' in the current directory.
```bash
django-admin startproject guide_neon_django .
```
--------------------------------
### Generate Maven Project
Source: https://neon.com/docs/guides/java
Creates a new Maven project with the standard quickstart archetype. This command sets up the basic project structure for a Java application.
```bash
mvn archetype:generate \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DarchetypeVersion=1.5 \
-DgroupId=com.neon.quickstart \
-DartifactId=neon-java-jdbc \
-DinteractiveMode=false
```
--------------------------------
### Example Neon Connection String
Source: https://neon.com/docs/connect/connect-looker-studio
This is an example of a Neon database connection string that can be used to configure the PostgreSQL connector in Looker Studio.
```bash
psql 'postgresql://neondb_owner:AbC123dEf@ep-quiet-mountain-a1t1firv-pooler.ap-southeast-1.aws.neon.tech/neondb?sslmode=require&channel_binding=require'
```
--------------------------------
### Install Kysely with node-postgres Driver
Source: https://neon.com/docs/guides/kysely
Installs Kysely core, the pg driver, and dotenv. Recommended for long-running Node.js servers.
```bash
npm install kysely pg dotenv
npm install -D @types/pg
```
--------------------------------
### Create Accounts Table for Lock Demonstration
Source: https://neon.com/docs/extensions/pgrowlocks
Sets up a sample 'accounts' table with initial data to facilitate the demonstration of row lock scenarios.
```sql
CREATE TABLE accounts (
account_id SERIAL PRIMARY KEY,
owner_name TEXT,
balance NUMERIC(10, 2)
);
INSERT INTO accounts (owner_name, balance) VALUES
('Alice', 1000.00),
('Bob', 500.00),
('Charlie', 750.00);
```
--------------------------------
### Move ltree Extension Example
Source: https://neon.com/docs/data-api/database-advisor
Example of moving the 'ltree' extension to the 'extensions' schema.
```sql
ALTER EXTENSION ltree SET SCHEMA extensions;
```
--------------------------------
### Start Micronaut Application
Source: https://neon.com/docs/guides/micronaut-kotlin
Use the Gradle wrapper to start the Micronaut application. This command initiates the application and connects to the Neon Postgres database, running any necessary migrations.
```bash
./gradlew run
```
--------------------------------
### Create Database via Neon API
Source: https://neon.com/docs/data-api/troubleshooting
Example of creating a database using the Neon API. Use this method instead of direct SQL to ensure proper permissions are set.
```bash
curl -X POST "https://console.neon.tech/api/v2/projects/${projectId}/branches/${branchId}/databases" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $NEON_API_KEY" \
-d '{
"database": {
"name": "your_database_name"
}
}'
```
--------------------------------
### Neon JDBC Connection String Example
Source: https://neon.com/docs/guides/liquibase
An example of a JDBC connection string for a Neon Postgres database, including host, database name, user, and password.
```bash
jdbc:postgresql://ep-cool-darkness-123456.us-east-2.aws.neon.tech/blog?user=alex&password=AbC123dEf
```
--------------------------------
### Install Neon Auth Packages
Source: https://neon.com/docs/auth/migrate/from-legacy-auth
Uninstall Stack Auth packages and install the latest Neon Auth SDK and UI packages.
```bash
npm uninstall @stackframe/stack
npm install @neondatabase/auth@latest @neondatabase/auth-ui
```
--------------------------------
### Create and Populate electronics_products Table
Source: https://neon.com/docs/functions/jsonb_array_elements
Sets up a table with product data, including nested JSONB details for variants, sizes, and colors. This is the prerequisite for the query example.
```sql
CREATE TABLE electronics_products (
id INTEGER PRIMARY KEY,
name TEXT,
details JSONB
);
INSERT INTO electronics_products (id, name, details) VALUES
(1, 'Laptop', '{"variants": [{"model": "A", "sizes": ["13 inch", "15 inch"], "colors": ["Silver", "Black"]}, {"model": "B", "sizes": ["15 inch", "17 inch"], "colors": ["Gray", "White"]}]}'),
(2, 'Smartphone', '{"variants": [{"model": "X", "sizes": ["5.5 inch", "6 inch"], "colors": ["Black", "Gold"]}, {"model": "Y", "sizes": ["6.2 inch", "6.7 inch"], "colors": ["Blue", "Red"]}]}');
```
--------------------------------
### Install Vite Plugin for Neon
Source: https://neon.com/docs/reference/claimable-postgres
Install the vite-plugin-neon-new package as a development dependency for your Vite project.
```bash
npm install -D vite-plugin-neon-new
```
--------------------------------
### Create Project Directory and Virtual Environment
Source: https://neon.com/docs/guides/tortoise-orm
Sets up a new directory for the project and optionally creates and activates a Python virtual environment for dependency management.
```bash
mkdir tortoise-neon-demo
cd tortoise-neon-demo
python3 -m venv venv
source venv/bin/activate # macOS / Linux
# venv\Scripts\activate # Windows
```
--------------------------------
### Example Output of PostgreSQL Version
Source: https://neon.com/docs/guides/bun
Displays the version information retrieved from the PostgreSQL database.
```json
{
version: "PostgreSQL 17.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit",
}
```
--------------------------------
### Azure AD Example JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of an Azure AD JWKS URL with a specific tenant ID.
```bash
https://login.microsoftonline.com/12345678-1234-1234-1234-1234567890ab/discovery/v2.0/keys
```
--------------------------------
### Install neon_utils Extension
Source: https://neon.com/docs/extensions/neon-utils
Install the neon_utils extension in your Neon database using the CREATE EXTENSION statement. This enables the num_cpus() function.
```sql
CREATE EXTENSION neon_utils;
```
--------------------------------
### Basic NeonAuthUIProvider Setup
Source: https://neon.com/docs/auth/reference/ui-components
Wrap your application with NeonAuthUIProvider and import the necessary CSS. Ensure your authClient is correctly configured.
```tsx
import { NeonAuthUIProvider } from '@neondatabase/auth-ui';
import '@neondatabase/auth-ui/css';
import { authClient } from './auth';
function App() {
return (
{/* Your app components */}
);
}
```
--------------------------------
### Verify pgvector Installation and Version
Source: https://neon.com/docs/extensions/pgvector
Confirm that the pgvector extension is installed and check its current version.
```sql
SELECT extname, extversion FROM pg_extension WHERE extname = 'vector';
```
--------------------------------
### Create a sample table with bloat
Source: https://neon.com/docs/extensions/pg_repack
SQL commands to create a sample table and insert/delete data to simulate bloat for demonstration purposes.
```sql
CREATE TABLE public.bloated_table (
id SERIAL PRIMARY KEY,
data TEXT
);
-- Insert some initial data
INSERT INTO public.bloated_table (data)
SELECT md5(random()::text)
FROM generate_series(1, 100000);
-- Delete a significant portion of the data to simulate bloat
DELETE FROM public.bloated_table WHERE id % 2 = 0;
```
--------------------------------
### Initialize Serverless Project
Source: https://neon.com/docs/guides/aws-lambda
Initiates a new serverless project, prompting for configuration details and AWS credentials. This process creates an 'aws-node-project' directory.
```bash
serverless
? What do you want to make? AWS - Node.js - Starter
? What do you want to call this project? aws-node-project
✔ Project successfully created in aws-node-project folder
? Do you want to login/register to Serverless Dashboard? Yes
Logging into the Serverless Dashboard via the browser
If your browser does not open automatically, please open this URL:
https://app.serverless.com?client=cli&transactionId=jP-Zz5A9xu67PPYqzIhOe
✔ You are now logged into the Serverless Dashboard
? What application do you want to add this to? [create a new app]
? What do you want to name this application? aws-node-project
✔ Your project is ready to be deployed to Serverless Dashboard (org: "myorg", app: "aws-node-project")
? No AWS credentials found, what credentials do you want to use? AWS Access Role
(most secure)
If your browser does not open automatically, please open this URL: https://app.serverless.com/myorg/settings/providers?source=cli&providerId=new&provider=aws
To learn more about providers, visit: http://slss.io/add-providers-dashboard
?
[If you encountered an issue when setting up a provider, you may press Enter to
skip this step]
✔ AWS Access Role provider was successfully created
? Do you want to deploy now? Yes
Deploying aws-node-project to stage dev (us-east-1, "default" provider)
✔ Service deployed to stack aws-node-project-dev (71s)
dashboard: https://app.serverless.com/myorg/apps/my-aws-node-project/aws-node-project/dev/us-east-1
functions:
hello: aws-node-project-dev-hello (225 kB)
What next?
Run these commands in the project directory:
serverless deploy Deploy changes
serverless info View deployed endpoints and resources
serverless invoke Invoke deployed functions
serverless --help Discover more commands
```
--------------------------------
### pgloader Configuration File Example
Source: https://neon.com/docs/import/migrate-mysql
This is an example of a pgloader configuration file. It specifies the MySQL source database and the modified Neon Postgres destination, including SSL mode.
```plaintext
load database
from mysql://user:password@host/source_db?sslmode=require
into postgresql://alex:endpoint=ep-cool-darkness-123456;AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require;
```
--------------------------------
### Update SDK Initialization (Before)
Source: https://neon.com/docs/auth/migrate/from-legacy-auth
Example of initializing the Stack Auth client app.
```tsx
// src/stack.ts
import { StackClientApp } from '@stackframe/stack';
export const stackClientApp = new StackClientApp({
urls: {
signIn: '/sign-in',
signUp: '/sign-up',
},
});
```
--------------------------------
### Create users table and insert sample data
Source: https://neon.com/docs/functions/json_extract_path_text
Creates a 'users' table with an 'id' and a 'JSON' profile column, then inserts sample user data.
```sql
CREATE TABLE users (
id INT,
profile JSON
);
INSERT INTO users (id, profile)
VALUES
(1, '{"name": "Alice", "contact": {"email": "alice@example.com", "phone": "1234567890"}, "hobbies": ["reading", "cycling", "hiking"]'),
(2, '{"name": "Bob", "contact": {"email": "bob@example.com", "phone": "0987654321"}, "hobbies": ["gaming", "cooking"]}');
```
--------------------------------
### Install Neon CLI Globally
Source: https://neon.com/docs/get-started/platform-private-preview
Install the Neon command-line interface globally on your system to manage Neon projects and resources.
```bash
npm install -g neonctl@latest
```
--------------------------------
### Initializing Git Repository and Pushing to GitHub
Source: https://neon.com/docs/guides/render
Commands to set up a .gitignore file, initialize a Git repository, commit changes, and push to a remote GitHub repository. Replace YOUR_GITHUB_REPO_URL with your actual repository URL.
```bash
echo "node_modules/" > .gitignore && echo ".env" >> .gitignore
echo "# neon-render-example" >> README.md
git init && git add . && git commit -m "Initial commit"
git branch -M main
git remote add origin YOUR_GITHUB_REPO_URL
git push -u origin main
```
--------------------------------
### Install Dependencies for ImageKit and Neon Integration
Source: https://neon.com/docs/guides/imagekit
Install the necessary Node.js packages for ImageKit, Neon, Hono, and environment variable management.
```bash
npm install imagekit @neondatabase/serverless @hono/node-server hono dotenv
```
--------------------------------
### Initialize node-postgres Connection
Source: https://neon.com/docs/import/migrate-from-turso
Example of initializing a database connection using node-postgres after migration.
```javascript
import { Pool } from 'pg';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
```
--------------------------------
### Initialize Neon MCP Server for Claude Desktop (Local)
Source: https://neon.com/docs/ai/connect-mcp-clients-to-neon
Initialize the Neon MCP server locally for Claude Desktop. Replace `` with your actual Neon API key. A restart of Claude Desktop is required after initialization.
```bash
npx @neondatabase/mcp-server-neon init
```
--------------------------------
### PropelAuth Example JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of a PropelAuth JWKS URL with a specific Auth URL.
```bash
https://3211758.propelauthtest.com/.well-known/jwks.json
```
--------------------------------
### Create Node.js Project with Express and Prisma
Source: https://neon.com/docs/guides/prisma-migrations
Sets up a new Node.js project, installs necessary dependencies including Express, Prisma Client, and the Neon adapter, and initializes Prisma.
```bash
mkdir neon-prisma-migrations && cd neon-prisma-migrations
npm init -y
npm pkg set type="module"
npm install express dotenv @prisma/client @prisma/adapter-neon
npm install prisma typescript tsx @types/node --save-dev
npx prisma init
```
--------------------------------
### Install Neon SDK
Source: https://neon.com/docs/auth/quick-start/react
Install the latest version of the Neon SDK for JavaScript to enable authentication functionalities in your React application.
```bash
cd my-app
npm install @neondatabase/neon-js@latest
```
--------------------------------
### Displaying Help Information
Source: https://neon.com/docs/extensions/pg_repack
The --help option displays comprehensive help information about pg_repack and all its available options.
```bash
pg_repack --help
```
--------------------------------
### Initialize Neon CLI
Source: https://neon.com/docs/cli/init
Basic usage of the Neon CLI init command to set up a project.
```bash
neonctl init [options]
```
--------------------------------
### Install Entity Framework Core Tools and Npgsql Provider
Source: https://neon.com/docs/guides/dotnet-entity-framework
Install the global dotnet-ef tool, the EF Core Design package, and the Npgsql provider for PostgreSQL. Ensure package versions match your .NET version.
```bash
dotnet tool install --global dotnet-ef --version YOUR_DOTNET_VERSION
dotnet add package Microsoft.EntityFrameworkCore.Design --version YOUR_DOTNET_VERSION
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version YOUR_DOTNET_VERSION
```
--------------------------------
### Example Pulse Event Payload
Source: https://neon.com/docs/guides/logical-replication-prisma-pulse
This is an example of the event payload you might receive when a 'create' action occurs on the 'User' model.
```bash
Just received an event: {
action: 'create',
created: {
id: 'clzvgzq4b0d016s28yluse9r1',
name: 'Polly Pulse',
age: 35
},
id: '01J5BCFR8F8DBJDXAQ5YJPZ6VY',
modelName: 'User'
}
```
--------------------------------
### Install Neon CLI with npm
Source: https://neon.com/docs/cli/install
Install the Neon CLI globally using npm. Requires Node.js 18.0 or higher.
```shell
npm i -g neonctl
```
--------------------------------
### Create Books Table and Insert Data
Source: https://neon.com/docs/extensions/pg_trgm
Sets up a sample 'books' table and populates it with initial data for demonstrating text search functionalities.
```sql
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title TEXT
);
INSERT INTO books (title)
VALUES
('The Great Gatsby'),
('The Grapes of Wrath'),
('Great Expectations'),
('War and Peace'),
('Pride and Prejudice'),
('To Kill a Mockingbird'),
('1984');
```
--------------------------------
### Insert Sample Data into Articles Table
Source: https://neon.com/docs/extensions/intarray
Populates the articles table with example data, including integer arrays for tag IDs.
```sql
INSERT INTO articles (title, tag_ids) VALUES
('Postgres Performance Tips', '{1,2,3}'),
('Introduction to SQL', '{2,4}'),
('Advanced intarray Usage', '{1,3,5}'),
('Database Normalization', '{4,6}');
```
--------------------------------
### Install psycopg2
Source: https://neon.com/docs/guides/sqlalchemy
Installs the psycopg2-binary package, a Python library for running raw Postgres queries. This is a prerequisite for connecting SQLAlchemy to Neon.
```shell
pip install psycopg2-binary
```
--------------------------------
### Check Installed Extension Versions
Source: https://neon.com/docs/extensions/pg-extensions
Query the `pg_extension` table to view the current versions of all installed extensions.
```bash
SELECT * FROM pg_extension;
```
--------------------------------
### Configure Environment Variables
Source: https://neon.com/docs/ai/lakebase-search-get-started
Set up your .env file with your Neon connection string and OpenAI API key. Ensure the DATABASE_URL includes sslmode=require.
```ini
DATABASE_URL=postgresql://[user]:[password]@[neon_hostname]/[dbname]?sslmode=require
OPENAI_API_KEY=your-openai-api-key
```
--------------------------------
### Create a Branch using Neon API
Source: https://neon.com/docs/manage/branches
This example demonstrates how to create a new branch using the Neon API. Ensure you have your API key available.
```bash
curl --request POST \
--url https://console.neon.tech/api/v2/projects/$NEON_PROJECT_ID/branches \
--header "Authorization: Bearer $NEON_API_KEY" \
--header "accept: application/json" \
--header "content-type: application/json" \
--data '{
"name": "my-new-branch",
"parent_id": "main"
}'
```
--------------------------------
### Example MAX_HISTORY_TOKENS Calculation
Source: https://neon.com/docs/extensions/pg_tiktoken
An example calculation for MAX_HISTORY_TOKENS for the gpt-3.5-turbo model, assuming a desired completion length of 100 tokens.
```text
MAX_HISTORY_TOKENS = 4096 – 6 – 90 = 4000
```
--------------------------------
### Install pgloader on macOS
Source: https://neon.com/docs/import/migrate-sqlite
Installs the pgloader utility on macOS using Homebrew. This is a prerequisite for migrating databases.
```shell
brew install pgloader
```
--------------------------------
### pg_restore verbose output example
Source: https://neon.com/docs/import/migrate-from-digital-ocean
Example output from pg_restore when run in verbose mode, indicating the progress of restoring database objects.
```bash
pg_restore: connecting to database for restore
pg_restore: creating SCHEMA "public"
pg_restore: creating TABLE "public.lego_colors"
pg_restore: creating SEQUENCE "public.lego_colors_id_seq"
pg_restore: creating SEQUENCE OWNED BY "public.lego_colors_id_seq"
pg_restore: creating TABLE "public.lego_inventories"
pg_restore: creating SEQUENCE "public.lego_inventories_id_seq"
...
```
--------------------------------
### Install Dependencies for Cloudinary and Neon Integration
Source: https://neon.com/docs/guides/cloudinary
Install the necessary npm packages for Cloudinary, Neon, Hono, and environment variable management.
```bash
npm install cloudinary @neondatabase/serverless @hono/node-server hono dotenv
```
--------------------------------
### Database Connection Setup
Source: https://neon.com/docs/guides/sqlalchemy-migrations
Sets up the database connection using SQLAlchemy by reading the DATABASE_URL from environment variables. It creates a database engine and a session factory.
```python
import os
import dotenv
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
dotenv.load_dotenv()
SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
```
--------------------------------
### Example Neon Pooled Database Connection String
Source: https://neon.com/docs/guides/cloudflare-workers
A sample connection string for a Neon database, including the '-pooler' option for serverless environments.
```bash
postgresql://alex:AbC123dEf@ep-cool-darkness-123456-pooler.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
```
--------------------------------
### Bootstrap Neon Project from Template
Source: https://neon.com/docs/get-started/platform-private-preview
Run this command in an empty folder to start a new Neon project using an interactive template selector or by specifying a template ID.
```bash
neonctl bootstrap
```
--------------------------------
### Uninstall Turso Serverless and Install Neon Serverless
Source: https://neon.com/docs/import/migrate-from-turso
Use npm to remove the Turso serverless package and install the Neon serverless driver or the pg package.
```bash
npm uninstall @tursodatabase/serverless
npm install @neondatabase/serverless # or npm install pg
```
--------------------------------
### Install Neon Serverless Driver with NPM
Source: https://neon.com/docs/guides/deno
Installs the Neon serverless driver using npm, which can be used in Deno projects that leverage npm compatibility.
```bash
npx jsr add @neon/serverless
```
--------------------------------
### Install Python Dependencies
Source: https://neon.com/docs/ai-gateway/get-started
Install the required Python packages for interacting with the AI Gateway using the OpenAI SDK and loading environment variables.
```bash
pip install openai python-dotenv
```
--------------------------------
### Install pg_tiktoken Extension
Source: https://neon.com/docs/extensions/pg_tiktoken
Installs the pg_tiktoken extension in your Neon database. This is a prerequisite for using its tokenization functions.
```sql
CREATE EXTENSION pg_tiktoken
```
--------------------------------
### Install Neon Python SDK
Source: https://neon.com/docs/changelog/2024-11-22
Install the Neon Python SDK using pip. This is the first step to programmatically manage Neon resources from Python applications.
```bash
pip install neon-api
```
--------------------------------
### Install Files SDK Dependencies
Source: https://neon.com/docs/storage/get-started
Install the Files SDK along with necessary AWS SDK packages and dotenv for environment variable management.
```bash
npm install files-sdk @aws-sdk/client-s3 @aws-sdk/s3-request-presigner @aws-sdk/s3-presigned-post dotenv
```
--------------------------------
### Connect to Database and Create Schema (CLI)
Source: https://neon.com/docs/guides/schema-diff-tutorial
Connects to the 'people' database using psql and applies the initial schema.
```bash
psql 'postgresql://neondb_owner:*********@ep-crimson-frost-a5i6p18z.us-east-2.aws.neon.tech/people?sslmode=require&channel_binding=require'
```
```sql
CREATE TABLE person (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
```
--------------------------------
### Install pg_stat_statements Extension
Source: https://neon.com/docs/extensions/pg_stat_statements
Installs the pg_stat_statements extension if it is not already present. This is the first step to enable its functionality.
```sql
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
```
--------------------------------
### Install S3 Client Dependencies
Source: https://neon.com/docs/storage/get-started
Install the AWS S3 client and related packages for interacting with S3-compatible storage, including dotenv for configuration.
```bash
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner dotenv
```
--------------------------------
### Initialize Liquibase Project
Source: https://neon.com/docs/guides/liquibase-workflow
Initializes a new Liquibase project in the specified directory, creating a pre-populated properties file.
```bash
liquibase init project --project-dir ~/blogdb
```
--------------------------------
### Initialize Reflex App
Source: https://neon.com/docs/guides/reflex
Initialize a new Reflex application using the Reflex CLI. Choose 'A blank Reflex app' when prompted.
```bash
reflex init
```
--------------------------------
### Install Neon Plugin in Claude Code
Source: https://neon.com/docs/ai/agent-skills
Install the Neon agent skills and MCP integration for Claude Code. This involves two commands: one to add the plugin from the marketplace and another to install the specific Neon Postgres package.
```bash
/plugin marketplace add neondatabase/agent-skills
```
```bash
/plugin install neon-postgres@neon
```
--------------------------------
### Example .neon Context File Content
Source: https://neon.com/docs/cli/quickstart
This is an example of the JSON structure found within a .neon context file, containing organization and project IDs.
```json
{
"projectId": "broad-surf-52155946",
"orgId": "org-solid-base-83603457"
}
```
--------------------------------
### Example API Response for Projects
Source: https://neon.com/docs/manage/api-keys
This is an example JSON response when retrieving project details. It includes project ID, region, creation date, and other relevant information.
```json
{
"projects": [
{
"cpu_used_sec": 0,
"id": "purple-shape-411361",
"platform_id": "aws",
"region_id": "aws-us-east-2",
"name": "purple-shape-411361",
"provisioner": "k8s-pod",
"pg_version": 15,
"locked": false,
"created_at": "2023-01-03T18:22:56Z",
"updated_at": "2023-01-03T18:22:56Z",
"proxy_host": "us-east-2.aws.neon.tech",
"branch_logical_size_limit": 3072
}
]
}
```
--------------------------------
### Add asynchronous tokio-postgres dependencies
Source: https://neon.com/docs/guides/rust
Add the `tokio` (with full features), `tokio-postgres`, `postgres-openssl`, and `dotenvy` crates for an asynchronous setup.
```bash
cargo add tokio --features "tokio/full" tokio-postgres postgres-openssl openssl dotenvy
```
--------------------------------
### Install pgx_ulid Extension
Source: https://neon.com/docs/changelog/2025-01-31
Run this command to install the pgx_ulid extension, which is now available for Postgres 17. No version specification is needed for the latest.
```sql
CREATE EXTENSION pgx_ulid;
```
--------------------------------
### Install the anon Extension
Source: https://neon.com/docs/extensions/postgresql-anonymizer
Installs the PostgreSQL Anonymizer extension if it is not already present in the database. This command should be run after enabling experimental extensions.
```sql
CREATE EXTENSION IF NOT EXISTS anon;
```
--------------------------------
### One-click Neon MCP setup for Kiro
Source: https://neon.com/docs/changelog/2026-04-24
URL to initiate a one-click setup for the Neon MCP Server within Kiro. This allows for quick integration and configuration.
```url
https://kiro.dev/launch/mcp/add?name=Neon&config=%7B%22url%22%3A%20%22https%3A//mcp.neon.tech/mcp%22%7D
```
--------------------------------
### Example Metric: db_total_size
Source: https://neon.com/docs/reference/metrics-logs
An example of the neon_db_total_size metric, showing its value and common labels like project_id, endpoint_id, compute_id, and job.
```json
neon_db_total_size{project_id="square-daffodil-12345678", endpoint_id="ep-aged-art-260862", compute_id="compute-shrill-blaze-b4hry7fg", job="sql-metrics"} 10485760
```
--------------------------------
### Install Sequelize and Related Packages
Source: https://neon.com/docs/guides/sequelize
Installs the necessary packages for Sequelize ORM, including the PostgreSQL driver and the Sequelize CLI for managing migrations.
```bash
npm install sequelize pg pg-hstore
npm install sequelize-cli --save-dev
```
--------------------------------
### Example JDBC connection strings for Neon branches
Source: https://neon.com/docs/guides/flyway-multiple-environments
These are example JDBC connection strings for different Neon branches (main, development, staging). Note that the hostname differs for each branch, reflecting its isolated compute instance.
```bash
jdbc:postgresql://ep-cool-darkness-123456.us-east-2.aws.neon.tech/neondb?user=alex&password=AbC123dEf
```
```bash
jdbc:postgresql://ep-mute-night-47642501.us-east-2.aws.neon.tech/neondb?user=alex&password=AbC123dEf
```
```bash
jdbc:postgresql://ep-shrill-shape-27763949.us-east-2.aws.neon.tech/neondb?user=alex&password=AbC123dEf
```
--------------------------------
### Create and Insert Sample Data for JSON_QUERY()
Source: https://neon.com/docs/functions/json_query
Sets up a 'users' table with a JSONB column and inserts sample data to demonstrate JSON_QUERY() function.
```sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
data JSONB
);
INSERT INTO users (data) VALUES
('{
"profile": {
"name": "John Doe",
"contacts": {
"email": ["john@example.com", "john.doe@work.com"],
"phone": "+1-555-0123"
}
}
}');
```
--------------------------------
### Connect to Neon using psql
Source: https://neon.com/docs/get-started/connect-neon
Connect to your Neon database using the psql command-line tool. This example shows how to include SSL requirements in the connection string.
```bash
# psql example connection string
psql postgresql://username:password@hostname:5432/database?sslmode=require&channel_binding=require
```
--------------------------------
### Create a New Heroku App
Source: https://neon.com/docs/guides/heroku
Creates a new Heroku application named 'neon-heroku-example' and sets up a Git remote named 'heroku' for deployment.
```bash
heroku create neon-heroku-example
```
--------------------------------
### Install and Run with @neondatabase/env
Source: https://neon.com/docs/changelog/2026-06-12
Install the `@neondatabase/env` package to inject branch-scoped variables at runtime, avoiding the need to write secrets to disk. Use `neon-env run` to execute commands with these injected variables.
```bash
npm i @neondatabase/env
neon-env run -- npm run dev
```
--------------------------------
### Install PostgreSQL in GitHub Action
Source: https://neon.com/docs/guides/multitenancy
Installs a specified version of PostgreSQL into the GitHub Action's virtual environment using environment variables.
```yaml
- name: Install PostgreSQL
run: |
sudo apt install -y postgresql-common
yes '' | sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
sudo apt install -y postgresql-${{ env.PG_VERSION }}
```
--------------------------------
### Connect with Prisma ORM (JavaScript)
Source: https://neon.com/docs/get-started/connect-neon
Example of using Prisma with the Neon serverless driver in JavaScript. Requires the DATABASE_URL environment variable and setting up the Prisma adapter.
```javascript
// Prisma example with the Neon serverless driver
import { neon } from '@neondatabase/serverless';
import { PrismaNeonHTTP } from '@prisma/adapter-neon';
import { PrismaClient } from '@prisma/client';
const sql = neon(process.env.DATABASE_URL);
const adapter = new PrismaNeonHTTP(sql);
const prisma = new PrismaClient({ adapter });
```
--------------------------------
### Install Neon CLI with npm
Source: https://neon.com/docs/changelog/2023-07-12
Install the Neon CLI globally using npm. This command is used to manage Neon resources from your terminal.
```bash
npm i -g neonctl
```
--------------------------------
### Example Neon Branch Connection Strings
Source: https://neon.com/docs/get-started/workflow-primer
These are example PostgreSQL connection strings for two different Neon branches. Each branch has a unique connection string for isolated access.
```bash
# Branch 1
postgresql://database_name_owner:AbC123dEf@ep-shiny-cell-a5y2zuu0.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
# Branch 2
postgresql://database_name_owner:AbC123dEf@ep-hidden-hall-a5x58cuv.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
```
--------------------------------
### Neon Postgres Direct Connection String Example
Source: https://neon.com/docs/guides/logical-replication-estuary-flow
Example of a direct connection string for a Neon Postgres database, suitable for logical replication. Ensure it does not contain '-pooler' in the hostname.
```bash
postgres://cdc_role:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
```
--------------------------------
### Run Django Development Server
Source: https://neon.com/docs/guides/django-migrations
Starts the Django development server to test the application locally.
```bash
python manage.py runserver
```
--------------------------------
### Install JWT libraries for Python
Source: https://neon.com/docs/auth/guides/plugins/jwt
Install the necessary Python libraries for JWT verification: PyJWT, requests, and cryptography.
```bash
pip install PyJWT requests cryptography
```
--------------------------------
### Install psycopg Driver
Source: https://neon.com/docs/ai/ai-azure-notebooks
Install the psycopg adapter, a popular Postgres database adapter for Python, using pip.
```python
!pip install psycopg
```
--------------------------------
### Install Dependencies for Next.js App
Source: https://neon.com/docs/guides/auth-okta
Installs necessary packages for Neon Postgres integration, Drizzle ORM, environment variable management, and authentication with Auth.js.
```bash
npm install @neondatabase/serverless drizzle-orm
npm install -D drizzle-kit dotenv
npm install next-auth@beta
```
--------------------------------
### Navigate to Project Directory
Source: https://neon.com/docs/guides/medusajs
Change into your new Medusa project directory to begin local development.
```bash
cd medusa-neon-store
```
--------------------------------
### Incoming Webhook Request Example
Source: https://neon.com/docs/auth/guides/webhooks
An example of an incoming HTTP POST request for a Neon Auth webhook, including essential headers for signature verification.
```http
POST /webhooks/neon-auth HTTP/1.1
Content-Type: application/json
X-Neon-Signature: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXUyIsImtpZCI6IjAxZGVjNTJiIn0..MEUCIQDZ8Qs
X-Neon-Signature-Kid: 01dec52b-4666-40f7-87ed-6423552eecaf
X-Neon-Timestamp: 1740312000000
X-Neon-Event-Type: send.otp
X-Neon-Event-Id: 550e8400-e29b-41d4-a716-446655440000
X-Neon-Delivery-Attempt: 1
{"event_id":"550e8400-e29b-41d4-a716-446655440000","event_type":"send.otp",...}
```
--------------------------------
### Example Output of Neon Project Operations
Source: https://neon.com/docs/cli/operations
This is an example of the output format for the `neonctl operations list` command, showing operation ID, action, status, and creation timestamp.
```text
┌──────────────────────────────────────┬────────────────────┬──────────┬──────────────────────┐
│ Id │ Action │ Status │ Created At │
├──────────────────────────────────────┼────────────────────┼──────────┼──────────────────────┤
│ fce8642e-259e-4662-bdce-518880aee723 │ apply_config │ finished │ 2023-06-20T00:45:19Z │
├──────────────────────────────────────┼────────────────────┼──────────┼──────────────────────┤
│ dc1dfb0c-b854-474b-be20-2ea1d2172563 │ apply_config │ finished │ 2023-06-20T00:43:17Z │
├──────────────────────────────────────┼────────────────────┼──────────┼──────────────────────┤
│ 7a83e300-cf5f-4c1a-b9b5-569b6d6feab9 │ suspend_compute │ finished │ 2023-06-19T23:50:56Z │
└──────────────────────────────────────┴────────────────────┴──────────┴──────────────────────┘
```
--------------------------------
### Install PostgreSQL Client Tools on Ubuntu/Debian
Source: https://neon.com/docs/manage/backup-pg-dump
Use this command to install the PostgreSQL client tools, which include pg_dump and pg_restore, on Ubuntu or Debian-based Linux distributions.
```bash
sudo apt-get install postgresql-client
```
--------------------------------
### Branch Details Response Example
Source: https://neon.com/docs/introduction/network-transfer
Example JSON snippet showing the 'data_transfer_bytes' field within the branch object.
```json
{
"branch": {
"data_transfer_bytes": 40820887,
...
}
}
```
--------------------------------
### Create and Navigate to .NET Project Directory
Source: https://neon.com/docs/guides/dotnet-npgsql
Use the dotnet CLI to create a new console application and change into its directory. This sets up the basic structure for your .NET project.
```bash
dotnet new console -o NeonLibraryExample
cd NeonLibraryExample
```
--------------------------------
### Documentation File Structure Example
Source: https://neon.com/docs/community/contribution-guide
This tree structure shows the organization of documentation files within the project. Folder and file names should follow kebab-case.
```text
└── content
└── docs
├── ai
├── community
├── connect
├── extensions
├── get-started
├── guides
├── introduction
├── manage
├── reference
├── security
└── serverless
```
--------------------------------
### Install Neon SDK
Source: https://neon.com/docs/auth/migrate/from-supabase
Replace the Supabase SDK with the latest version of the Neon SDK using npm.
```bash
npm uninstall @supabase/supabase-js
npm install @neondatabase/neon-js@latest
```
--------------------------------
### Install All Neon Agent Skills
Source: https://neon.com/docs/ai/agent-skills
Use this command to install all available skills from the Neon agent skills repository. The `-y` flag skips interactive prompts.
```bash
npx skills add neondatabase/agent-skills -y
```
--------------------------------
### Lambda Function Response Example
Source: https://neon.com/docs/guides/aws-lambda
Example JSON response from the Lambda function, containing a list of user data.
```json
{
"data": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"created_at": "2023-01-10T17:46:29.353Z"
},
{
"id": 2,
"name": "Bob",
"email": "bob@example.com",
"created_at": "2023-01-10T17:46:29.353Z"
},
{
"id": 3,
"name": "Charlie",
"email": "charlie@example.com",
"created_at": "2023-01-10T17:46:29.353Z"
},
{
"id": 4,
"name": "Dave",
"email": "dave@example.com",
"created_at": "2023-01-10T17:46:29.353Z"
},
{
"id": 5,
"name": "Eve",
"email": "eve@example.com",
"created_at": "2023-01-10T17:46:29.353Z"
}
]
}
```
--------------------------------
### Create and Populate Sales Table
Source: https://neon.com/docs/functions/date_trunc
Sets up a sample 'sales' table with timestamped sales data for demonstrating date_trunc() functionality.
```sql
CREATE TABLE sales (
sale_date TIMESTAMP WITH TIME ZONE,
amount DECIMAL(10, 2)
);
INSERT INTO sales (sale_date, amount) VALUES
('2024-03-01 08:30:00+00', 100.50),
('2024-03-01 14:45:00+00', 200.75),
('2024-03-02 10:15:00+00', 150.25),
('2024-04-15 09:00:00+00', 300.00),
('2024-05-20 16:30:00+00', 250.50);
```
--------------------------------
### Neon CLI Init Command Output
Source: https://neon.com/docs/cli/init
This output shows the typical results of running the `neonctl init` command, including editor configuration prompts, authentication status, and installation of agent skills and extensions.
```text
┌ Adding Neon MCP server, extension (for VS Code and Cursor) and agent skills
│
◆ Which editor(s) would you like to configure? (Space to toggle each option, Enter to confirm your selection)
│ ◼ Cursor
│ ◼ VS Code
│ ◻ Claude CLI
│
◒ Authenticating...
┌────────┬──────────────────┬────────┬────────────────┐
│ Login │ Email │ Name │ Projects Limit │
├────────┼──────────────────┼────────┼────────────────┤
│ alex │ alex@domain.com │ Alex │ 100 │
└────────┴──────────────────┴────────┴────────────────┘
◇ Authentication successful ✓
│
◇ Installing agent skills for Neon...
│
◇ Agent skills installed ✓
│
◇ Neon Local Connect extension installed for Cursor / VS Code.
│
├ What's next? ───────────────────────────────────────────────────────────────────────────────────╮
│ │
│ Restart Cursor / VS Code, open the Neon extension and type │
│ in "Get started with Neon" in your agent chat │
│ │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
│
└ Have feedback? Email us at feedback@neon.tech
```
--------------------------------
### Example SuperTokens JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of a SuperTokens JWKS URL, given a specific Core connection URI.
```bash
https://try.supertokens.io/.well-known/jwks.json
```
--------------------------------
### Install Dependencies for Next.js App
Source: https://neon.com/docs/guides/auth-auth0
Installs necessary packages for Neon database connectivity, Drizzle ORM, and Auth0 authentication in a Next.js project.
```bash
npm install @neondatabase/serverless drizzle-orm
npm install -D drizzle-kit dotenv
npm install @auth0/nextjs-auth0
```
--------------------------------
### Example API Key Creation Response
Source: https://neon.com/docs/manage/api-keys
This is an example of a successful response when creating a project-scoped API key. It includes the key's ID, the generated key, name, and associated project.
```json
{
"id": 1904821,
"key": "neon_project_key_1234567890abcdef1234567890abcdef",
"name": "test-project-scope",
"created_at": "2024-12-11T21:34:58Z",
"created_by": "user_01h84bfr2npa81rn8h8jzz8mx4",
"project_id": "project-id-123"
}
```
--------------------------------
### Drizzle Query Execution Output Example
Source: https://neon.com/docs/guides/drizzle
Example output after running the Drizzle query script, showing successful data insertion and retrieval.
```bash
Successfully queried the database: [ { id: 1, name: 'John Doe' } ]
```
--------------------------------
### Complete Markdown Frontmatter Example
Source: https://neon.com/docs/community/contribution-guide
An example of a comprehensive frontmatter section including optional attributes like subtitle, enableTableOfContents, redirectFrom, and updatedOn.
```yaml
---
title: Connect a Next.js application to Neon
subtitle: Set up a Neon project and connect from a Next.js application
enableTableOfContents: true
redirectFrom:
- /docs/content/
updatedOn: '2023-10-07T12:25:27.662Z'
---
```
--------------------------------
### Example Query Plan Output
Source: https://neon.com/docs/ai/ai-vector-search-optimization
This is an example of the output you might see when analyzing the query plan for an IVFFlat index search. It shows the index scan and ordering details.
```sql
Limit (cost=1971.50..1982.39 rows=100 width=173) (actual time=4.500..5.738 rows=100 loops=1)
-> Index Scan using items_embedding_idx on vectors (cost=1971.50..3060.50 rows=10000 width=173) (actual time=4.499..5.726 rows=100 loops=1)
Order By: (vec <-> '[0.0117, ... ,0.0866]'::vector)
Planning Time: 0.295 ms
Execution Time: 5.867 ms
```
--------------------------------
### Configure Hono with postgres.js
Source: https://neon.com/docs/guides/hono
Set up a Hono application to connect to Neon using the postgres.js driver. This example shows how to query the database and return the version.
```typescript
import { Hono } from 'hono';
import postgres from 'postgres';
import { serve } from '@hono/node-server';
const app = new Hono();
app.get('/', async (c) => {
try {
const sql = postgres(process.env.DATABASE_URL, { ssl: 'require' });
const response = await sql`SELECT version()`;
return c.json({ version: response[0].version });
} catch (error) {
console.error('Database query failed:', error);
return c.text('Failed to connect to database', 500);
}
});
serve(app);
```
--------------------------------
### Node.js (pg) Connection Example
Source: https://neon.com/docs/connect/connect-from-any-app
Connect to Neon using the 'pg' library in Node.js. Ensure the DATABASE_URL environment variable is set.
```javascript
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const { rows } = await pool.query('SELECT * FROM users WHERE id = $1', [1]);
```
--------------------------------
### Install Entity Framework Core Dependencies
Source: https://neon.com/docs/guides/entity-migrations
Installs the necessary NuGet packages for Entity Framework Core, the Npgsql provider for PostgreSQL, and dotenv for environment variable management.
```bash
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add Microsoft.AspNetCore.App
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package dotenv.net
```
--------------------------------
### View pgcli Help
Source: https://neon.com/docs/connect/connect-pgcli
To see the available command-line options for pgcli, run the help command.
```bash
pgcli --help
```
--------------------------------
### Install Tortoise ORM and Dependencies
Source: https://neon.com/docs/guides/tortoise-orm
Installs Tortoise ORM with the asyncpg driver support and python-dotenv for loading environment variables.
```bash
pip install "tortoise-orm[asyncpg]" python-dotenv
```
--------------------------------
### Install OpenAI SDK and dotenv
Source: https://neon.com/docs/ai-gateway/get-started
Install the necessary npm packages for using the OpenAI SDK and managing environment variables. This is required for Node.js environments.
```bash
npm install openai dotenv
```
```bash
yarn add openai dotenv
```
```bash
pnpm add openai dotenv
```
--------------------------------
### Example Authorization URL
Source: https://neon.com/docs/guides/oauth-integration
An example of a complete authorization URL for initiating the OAuth flow with Neon. Ensure all parameters are correctly formatted and include your application's specific details.
```text
https://oauth2.neon.tech/oauth2/auth?client_id=neon-experimental&scope=openid%20offline%20offline_access%20urn%3Aneoncloud%3Aprojects%3Acreate%20urn%3Aneoncloud%3Aprojects%3Aread%20urn%3Aneoncloud%3Aprojects%3Aupdate%20urn%3Aneoncloud%3Aprojects%3Adelete&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fauth%2Fcallback%2Fneon&grant_type=authorization_code&state=H58y-rSTebc3QmNbRjNTX9dL73-IyoU2T_WNievO9as&code_challenge=99XcbwOFU6iEsvXr77Xxwsk9I0GL4c4c4Q8yPIVrF_0&code_challenge_method=S256
```
--------------------------------
### Example SQL Queries for Testing
Source: https://neon.com/docs/extensions/neon-utils
These SQL queries can be used in a test.sql file to evaluate the neon_utils extension's functionality.
```sql
SELECT LOG(factorial(5000)) / LOG(factorial(2500));
SELECT txid_current();
```
--------------------------------
### Initialize Claimable Postgres with SDK
Source: https://neon.com/docs/reference/claimable-postgres
Use the instantPostgres function from the neon-new SDK to provision a database. The referrer parameter is required. This function returns connection URLs and claim information.
```javascript
import { instantPostgres } from 'neon-new';
const { databaseUrl, databaseUrlDirect, claimUrl, claimExpiresAt } = await instantPostgres({
referrer: 'your-app-name',
});
```
--------------------------------
### Rename Function Script and Install Driver
Source: https://neon.com/docs/guides/netlify-functions
Commands to rename the function script to .mjs and install the Neon serverless driver.
```bash
mv netlify/functions/get_coffee_blends/get_coffee_blends.js netlify/functions/get_coffee_blends/get_coffee_blends.mjs
npm install @neondatabase/serverless
```
--------------------------------
### Connect with Ruby
Source: https://neon.com/docs/get-started/connect-neon
Basic Ruby example using the 'pg' gem to connect to Neon. Requires the 'dotenv' gem to load environment variables.
```ruby
# Ruby example
require 'pg'
require 'dotenv'
# Load environment variables from .env file
Dotenv.load()
```
--------------------------------
### Initialize pgbench Database
Source: https://neon.com/docs/extensions/neon-utils
Before running pgbench, initialize your Neon database with the necessary tables using this command. Replace placeholders with your actual connection details.
```bash
pgbench -i postgresql://[user]:[password]@[neon_hostname]/[dbname]
```
--------------------------------
### Example Prompt for Neon Database Creation
Source: https://neon.com/docs/ai/ai-codex-plugin
Use this prompt to ask Codex to create a new Neon Serverless Postgres database and assist with connecting to it.
```text
Use Neon to create a new Serverless Postgres database for my project and help me connect to it.
```
--------------------------------
### Create a branch and connect immediately with psql
Source: https://neon.com/docs/cli/branches
Create a branch and establish an immediate connection using `psql`. Arguments following `--` are passed directly to `psql`, enabling execution of SQL files or queries upon creation.
```bash
neonctl branches create --psql
```
```bash
neonctl branches create --psql -- -f dump.sql
```
```bash
neonctl branches create --psql -- -c "SELECT version()"
```
--------------------------------
### Update provider setup with NeonAuthUIProvider
Source: https://neon.com/docs/auth/migrate/from-legacy-auth
Wrap your app in `NeonAuthUIProvider`, pass it the `authClient`, and import the Neon Auth UI styles. This replaces the `StackProvider` and `StackTheme` setup.
```tsx
import { StackProvider, StackTheme } from '@stackframe/stack';
import { stackServerApp } from './stack';
export default function RootLayout({ children }) {
return (
{children}
);
}
```
```tsx
'use client';
import { NeonAuthUIProvider } from '@neondatabase/auth-ui';
import '@neondatabase/auth-ui/css';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { authClient } from '@/lib/auth/client';
export default function RootLayout({ children }) {
const router = useRouter();
return (
{children}
);
}
```
--------------------------------
### Install Neon Config Package
Source: https://neon.com/docs/get-started/platform-private-preview
Install the necessary package for defining your Neon project infrastructure as code using TypeScript.
```bash
npm install @neondatabase/config
```
--------------------------------
### Create a Project with Neon CLI
Source: https://neon.com/docs/cli
Use the 'projects create' command to provision a new Neon project. This command initiates the project creation process.
```bash
neonctl projects create
```
--------------------------------
### Example SQL Query Result from Neon
Source: https://neon.com/docs/import/migrate-mssql
This is an example of the output from the verification SQL query executed on the Neon database. It shows product details, including name, unit price, and units in stock.
```plaintext
productname | unitprice | unitsinstock
------------------------+-----------+--------------
Côte de Blaye | 263.5 | 17
Sir Rodney's Marmalade | 81.0 | 40
Carnarvon Tigers | 62.5 | 42
Raclette Courdavault | 55.0 | 79
Manjimup Dried Apples | 53.0 | 20
(5 rows)
```
--------------------------------
### List Buckets with neonctl
Source: https://neon.com/docs/storage/buckets
Use the neonctl command-line tool to list all available buckets.
```bash
neonctl bucket list
```
--------------------------------
### List Databases Meta-Command
Source: https://neon.com/docs/get-started/query-with-neon-sql-editor
Use `\l` to list all available databases.
```sql
\l
```
--------------------------------
### Schema Diff Output Example (CLI)
Source: https://neon.com/docs/guides/schema-diff-tutorial
This is an example of the output from the `schema-diff` command, showing added tables, sequences, and constraints in the feature branch compared to the production branch.
```diff
--- Database: people (Branch: br-falling-dust-a5bakdqt)
+++ Database: people (Branch: br-morning-heart-a5ltt10i)
@@ -20,8 +20,46 @@
SET default_table_access_method = heap;
--
+-- Name: address; Type: TABLE; Schema: public; Owner: neondb_owner
+--
+
+CREATE TABLE public.address (
id integer NOT NULL,
person_id integer NOT NULL,
street text NOT NULL,
city text NOT NULL,
state text NOT NULL,
zip_code text NOT NULL
);
+ALTER TABLE public.address OWNER TO neondb_owner;
+
+...
```
--------------------------------
### Create developers table and insert data
Source: https://neon.com/docs/functions/json_array_elements
Sets up a sample 'developers' table with JSON skills data for demonstrating json_array_elements().
```sql
CREATE TABLE developers (
id INT PRIMARY KEY,
name TEXT,
skills JSON
);
INSERT INTO developers (id, name, skills) VALUES
(1, 'Alice', '["Java", "Python", "SQL"]'),
(2, 'Bob', '["C++", "JavaScript"]'),
(3, 'Charlie', '["HTML", "CSS", "React"]);
```
--------------------------------
### Install Neon Serverless Driver with Deno
Source: https://neon.com/docs/guides/deno
Installs the Neon serverless driver for Deno applications using the 'deno add' command. This adds the dependency to your project's configuration.
```bash
deno add jsr:@neon/serverless
```
--------------------------------
### Deno JSON Configuration with Neon Driver
Source: https://neon.com/docs/guides/deno
Example deno.json file showing the Neon serverless driver dependency added for use in a Deno project.
```json
{
"imports": {
"@neon/serverless": "jsr:@neon/serverless@^0.10.1"
}
}
```
--------------------------------
### Create Sample Table 2
Source: https://neon.com/docs/extensions/pg_prewarm
Creates the second sample table, identical to the first, for comparison.
```sql
CREATE TABLE tbl_transactions_2
(
tran_id_ SERIAL,
transaction_date TIMESTAMPTZ,
transaction_name TEXT
);
INSERT INTO tbl_transactions_2
(transaction_date, transaction_name)
SELECT x, 'dbrnd'
FROM generate_series('2010-01-01 00:00:00'::timestamptz, '2018-02-01 00:00:00'::timestamptz, '1 minutes'::interval) a(x);
```
--------------------------------
### Install Drizzle and Neon Serverless Packages
Source: https://neon.com/docs/guides/drizzle-migrations
Installs the necessary Drizzle ORM and Neon serverless driver packages, along with development dependencies for drizzle-kit and dotenv.
```bash
cd neon-drizzle-guide && touch .env
npm install drizzle-orm @neondatabase/serverless
npm install -D drizzle-kit dotenv
```
--------------------------------
### Example Connection String with Endpoint in Password
Source: https://neon.com/docs/connect/connection-errors
An example demonstrating how to include the endpoint ID in the password field using a semicolon separator within a full connection string. Note the 'sslmode=require' and 'channel_binding=require' parameters.
```text
postgresql://alex:endpoint=ep-cool-darkness-123456;AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
```
--------------------------------
### Flask App Setup and B2 Client Initialization
Source: https://neon.com/docs/guides/backblaze-b2
Initializes the Flask application, loads environment variables, and configures the boto3 client for Backblaze B2 using S3 compatibility.
```python
import os
import uuid
import boto3
import psycopg2
from dotenv import load_dotenv
from urllib.parse import urlparse
from flask import Flask, jsonify, request
from botocore.exceptions import ClientError
load_dotenv()
B2_BUCKET_NAME = os.getenv("B2_BUCKET_NAME")
B2_ENDPOINT_URL = os.getenv("B2_ENDPOINT_URL")
parsed_endpoint = urlparse(B2_ENDPOINT_URL)
region_name = parsed_endpoint.hostname.split(".")[1]
s3_client = boto3.client(
service_name="s3",
endpoint_url=B2_ENDPOINT_URL,
aws_access_key_id=os.getenv("B2_APPLICATION_KEY_ID"),
aws_secret_access_key=os.getenv("B2_APPLICATION_KEY"),
region_name=region_name
)
app = Flask(__name__)
# Use a global PostgreSQL connection instead of creating a new one for each request in production
def get_db_connection():
return psycopg2.connect(os.getenv("DATABASE_URL"))
# Replace this with your actual user authentication logic
def get_authenticated_user_id(request):
# Example: Validate Authorization header, session cookie, etc.
return "user_123" # Static ID for demonstration
```
--------------------------------
### Create Sample Table and Insert Data in Neon
Source: https://neon.com/docs/guides/logical-replication-databricks
Use this SQL to create a sample table and populate it with data in your Neon Postgres database for testing replication.
```sql
CREATE TABLE IF NOT EXISTS playing_with_neon (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
value REAL
);
INSERT INTO playing_with_neon (name, value)
SELECT LEFT(md5(i::TEXT), 10), random()
FROM generate_series(1, 10) s(i);
```
--------------------------------
### Load Database Version with Postgres.js
Source: https://neon.com/docs/guides/sveltekit
Example load function for a SvelteKit route using postgres.js to fetch the database version.
```typescript
import { sql } from '../db.server';
export async function load() {
const response = await sql`SELECT version()`;
const { version } = response[0];
return {
version,
};
}
```
--------------------------------
### Install Azure Blob Storage and Neon Dependencies
Source: https://neon.com/docs/guides/azure-blob-storage
Install the necessary npm packages for Azure Blob Storage, Neon, Hono, and environment variable management.
```bash
npm install @azure/storage-blob @neondatabase/serverless @hono/node-server hono dotenv
```
--------------------------------
### Example Foreign Server Connection
Source: https://neon.com/docs/extensions/postgres_fdw
An example of creating a foreign server connection to a remote Postgres database named 'analytics'.
```sql
CREATE SERVER production_db
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'db.example.com', port '5432', dbname 'analytics');
```
--------------------------------
### Create TanStack App with Neon Add-on
Source: https://neon.com/docs/changelog/2025-07-04
Instantly set up a fullstack application with a Neon Postgres database using the Create TanStack command.
```bash
pnpm create tanstack --add-on neon
```
--------------------------------
### Full-Stack Example: Upload to Azure Blob Storage and Save Metadata to Neon
Source: https://neon.com/docs/guides/azure-blob-storage
This comprehensive example sets up a Hono server to handle SAS URL generation for Azure Blob Storage uploads and to save file metadata to Neon after upload confirmation. It includes authentication middleware and error handling.
```javascript
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import {
BlobServiceClient,
generateBlobSASQueryParameters,
BlobSASPermissions,
SASProtocol,
} from '@azure/storage-blob';
import { neon } from '@neondatabase/serverless';
import 'dotenv/config';
import { randomUUID } from 'crypto';
const AZURE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
const AZURE_CONTAINER_NAME = process.env.AZURE_STORAGE_CONTAINER_NAME;
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_CONNECTION_STRING);
const containerClient = blobServiceClient.getContainerClient(AZURE_CONTAINER_NAME);
const sql = neon(process.env.DATABASE_URL);
const app = new Hono();
// Replace this with your actual user authentication logic, by validating JWTs/Headers, etc.
const authMiddleware = async (c, next) => {
c.set('userId', 'user_123');
await next();
};
// 1. Generate SAS URL for upload
app.post('/generate-upload-sas', authMiddleware, async (c) => {
try {
const { fileName, contentType } = await c.req.json();
if (!fileName || !contentType) throw new Error('fileName and contentType required');
const blobName = `${randomUUID()}-${fileName}`;
const blobClient = containerClient.getBlockBlobClient(blobName);
const fileUrl = blobClient.url;
const sasOptions = {
containerName: AZURE_CONTAINER_NAME,
blobName: blobName,
startsOn: new Date(),
expiresOn: new Date(new Date().valueOf() + 300 * 1000), // 5 minutes expiry
permissions: BlobSASPermissions.parse('w'), // Write permission
protocol: SASProtocol.Https,
contentType: contentType,
};
const sasToken = generateBlobSASQueryParameters(
sasOptions,
blobServiceClient.credential
).toString();
const sasUrl = `${fileUrl}?${sasToken}`;
return c.json({ success: true, sasUrl, blobName, fileUrl });
} catch (error) {
console.error('SAS Generation Error:', error.message);
return c.json({ success: false, error: 'Failed to prepare upload URL' }, 500);
}
});
// 2. Save metadata after client upload confirmation
app.post('/save-metadata', authMiddleware, async (c) => {
try {
const { blobName, fileUrl } = await c.req.json();
const userId = c.get('userId');
if (!blobName || !fileUrl) throw new Error('blobName and fileUrl required');
await sql`
INSERT INTO azure_files (blob_name, file_url, user_id)
VALUES (${blobName}, ${fileUrl}, ${userId})
`;
console.log(`Metadata saved for Azure blob: ${blobName}`);
return c.json({ success: true });
} catch (error) {
console.error('Metadata Save Error:', error.message);
return c.json({ success: false, error: 'Failed to save metadata' }, 500);
}
});
const port = 3000;
serve({ fetch: app.fetch, port }, (info) => {
console.log(`Server running at http://localhost:${info.port}`);
});
```
--------------------------------
### Connect to Neon with postgres.js
Source: https://neon.com/docs/guides/express
This example uses the postgres.js library for connecting to Neon, ideal for Express applications. It demonstrates a straightforward approach to querying the database version.
```javascript
require('dotenv').config();
const express = require('express');
const postgres = require('postgres');
const app = express();
const PORT = process.env.PORT || 4242;
const sql = postgres(process.env.DATABASE_URL);
app.get('/', async (req, res) => {
try {
const [result] = await sql`SELECT version()`;
const version = result?.version || 'No version found';
res.json({ version });
} catch (error) {
console.error('Database query failed:', error);
res.status(500).json({ error: 'Failed to connect to the database.' });
}
});
app.listen(PORT, () => {
console.log(`Listening to http://localhost:${PORT}`);
});
```
--------------------------------
### Full Stack Example: Cloudinary Upload and Neon Metadata Storage
Source: https://neon.com/docs/guides/cloudinary
This comprehensive example sets up a Hono server to handle Cloudinary signed uploads and save asset metadata to a Neon database. It includes endpoints for generating upload signatures and for receiving and storing file metadata after a successful upload. Ensure your .env file is configured with the correct credentials.
```javascript
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { v2 as cloudinary } from 'cloudinary';
import { neon } from '@neondatabase/serverless';
import 'dotenv/config';
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
secure: true,
});
const sql = neon(process.env.DATABASE_URL);
const app = new Hono();
// Replace this with your actual user authentication logic
const authMiddleware = async (c, next) => {
// Example: Validate JWT, session, etc. and set user ID
c.set('userId', 'user_123'); // Static ID for demonstration
await next();
};
// 1. Generate signature for client-side upload
app.get('/generate-signature', authMiddleware, (c) => {
try {
const timestamp = Math.round(new Date().getTime() / 1000);
const paramsToSign = { timestamp: timestamp };
const signature = cloudinary.utils.api_sign_request(
paramsToSign,
process.env.CLOUDINARY_API_SECRET
);
return c.json({
success: true,
signature: signature,
timestamp: timestamp,
api_key: process.env.CLOUDINARY_API_KEY,
});
} catch (error) {
console.error('Signature Generation Error:', error);
return c.json({ success: false, error: 'Failed to generate signature' }, 500);
}
});
// 2. Save metadata after client confirms successful upload to Cloudinary
app.post('/save-metadata', authMiddleware, async (c) => {
try {
const userId = c.get('userId');
// Client sends metadata received from Cloudinary after upload
const { public_id, secure_url, resource_type } = await c.req.json();
if (!public_id || !secure_url || !resource_type) {
throw new Error('public_id, secure_url, and resource_type are required');
}
// Insert metadata into Neon database
await sql`
INSERT INTO cloudinary_files (public_id, media_url, resource_type, user_id)
VALUES (${public_id}, ${secure_url}, ${resource_type}, ${userId})
`;
console.log(`Metadata saved for Cloudinary asset: ${public_id}`);
return c.json({ success: true });
} catch (error) {
console.error('Metadata Save Error:', error.message);
return c.json({ success: false, error: 'Failed to save metadata' }, 500);
}
});
const port = 3000;
serve({ fetch: app.fetch, port }, (info) => {
console.log(`Server running at http://localhost:${info.port}`);
});
```
--------------------------------
### Organization Member Object Example
Source: https://neon.com/docs/changelog/2026-03-13
An example of the user object within a member response, indicating if multi-factor authentication is enabled.
```json
"user": { "email": "user@example.com", "has_mfa": true }
```
--------------------------------
### Create New TypeScript Project with Prisma
Source: https://neon.com/docs/guides/logical-replication-prisma-pulse
Use this command to set up a new TypeScript project with Prisma, which is a prerequisite for installing the Prisma Pulse extension.
```bash
npx try-prisma -t typescript/starter
```
--------------------------------
### Get Data API Details
Source: https://neon.com/docs/data-api/manage
Retrieve the current status and configuration of the Data API for a branch using a GET request.
```bash
curl -X GET 'https://console.neon.tech/api/v2/projects/{project_id}/branches/{branch_id}/data-api/{database_name}' \
-H 'Authorization: Bearer $NEON_API_KEY'
```
--------------------------------
### Test Application Locally with Wrangler
Source: https://neon.com/docs/guides/cloudflare-pages
Use the Wrangler CLI to start a local server that simulates the Cloudflare environment for testing.
```bash
npx wrangler pages dev -- npm run dev
```
--------------------------------
### Express Server Setup with Sequelize
Source: https://neon.com/docs/guides/sequelize
Sets up an Express server, configures Sequelize to connect to a Neon database using environment variables, and defines models for authors and books. This code creates API endpoints for fetching authors and books by author ID.
```javascript
// index.js
const express = require('express');
const { Sequelize, DataTypes } = require('sequelize');
const { config } = require('dotenv');
config();
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is not set');
}
const sequelize = new Sequelize(process.env.DATABASE_URL, {
dialectOptions: { ssl: { require: true } },
});
// Set up the models
const Author = require('./models/author')(sequelize, DataTypes);
const Book = require('./models/book')(sequelize, DataTypes);
// Create a new Express application
const app = express();
const port = process.env.PORT || 3000;
app.get('/', async (req, res) => {
res.send('Hello World! This is a book catalog.');
});
app.get('/authors', async (req, res) => {
try {
const authors = await Author.findAll();
res.json(authors);
} catch (error) {
console.error('Error fetching authors:', error);
res.status(500).send('Error fetching authors');
}
});
app.get('/books/:author_id', async (req, res) => {
const authorId = parseInt(req.params.author_id);
try {
const books = await Book.findAll({
where: {
authorId: authorId,
},
});
res.json(books);
} catch (error) {
console.error('Error fetching books for author:', error);
res.status(500).send('Error fetching books for author');
}
});
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
```
--------------------------------
### Start Local Development Server
Source: https://neon.com/docs/compute/functions/get-started
Use `neonctl dev` to serve functions locally with hot reload. It automatically injects necessary environment variables from your linked Neon branch.
```bash
neonctl dev
```
--------------------------------
### Example API Response for Available Libraries
Source: https://neon.com/docs/extensions/pg-extensions
This JSON response details available preloaded libraries, including their names, descriptions, default status, experimental status, and versions.
```json
{
"libraries": [
{
"library_name": "timescaledb",
"description": "Enables scalable inserts and complex queries for time-series data.",
"is_default": true,
"is_experimental": false,
"version": "2.17.1"
},
{
"library_name": "pg_cron",
"description": "pg_cron is a cron-like job scheduler for PostgreSQL.",
"is_default": true,
"is_experimental": false,
"version": "1.6.4"
},
{
"library_name": "pg_partman_bgw",
"description": "pg_partman_bgw is a background worker for pg_partman.",
"is_default": true,
"is_experimental": false,
"version": "5.1.0"
},
{
"library_name": "rag_bge_small_en_v15,rag_jina_reranker_v1_tiny_en",
"description": "Shared libraries for pgrag extensions",
"is_default": true,
"is_experimental": true,
"version": "0.0.0"
},
{
"library_name": "pgx_ulid",
"description": "pgx_ulid is a PostgreSQL extension for ULID generation.",
"is_default": false,
"is_experimental": false,
"version": "0.2.0"
},
{
"library_name": "pg_mooncake",
"description": "Columnstore Table in Postgres",
"is_default": false,
"is_experimental": false,
"version": "0.1.1"
},
{
"library_name": "pg_search",
"description": "Deprecated. Full text search using BM25. Not for new projects; see Neon pg_search extension docs.",
"is_default": false,
"is_experimental": false,
"version": "0.15.12"
},
{
"library_name": "anon",
"description": "Anonymization & Data Masking for PostgreSQL",
"is_default": false,
"is_experimental": false,
"version": "2.5.1"
}
]
}
```
--------------------------------
### Full Stack R2 Upload and Neon Metadata Example
Source: https://neon.com/docs/guides/cloudflare-r2
This comprehensive JavaScript example uses Hono, AWS SDK, and Neon to handle file uploads to R2 via presigned URLs and store metadata in Neon. It includes endpoints for generating upload URLs and confirming metadata saves.
```javascript
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { neon } from '@neondatabase/serverless';
import 'dotenv/config';
import { randomUUID } from 'crypto';
const R2_ENDPOINT = `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`;
const R2_BUCKET = process.env.R2_BUCKET_NAME;
const R2_PUBLIC_BASE_URL = process.env.R2_PUBLIC_BASE_URL; // Ensure no trailing '/'
const s3 = new S3Client({
region: 'auto',
endpoint: R2_ENDPOINT,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
},
});
const sql = neon(process.env.DATABASE_URL);
const app = new Hono();
// Replace this with your actual user authentication logic, by validating JWTs/Headers, etc.
const authMiddleware = async (c, next) => {
c.set('userId', 'user_123'); // Example: Get user ID after validation
await next();
};
// 1. Generate Presigned URL for Upload
app.post('/presign-upload', authMiddleware, async (c) => {
try {
const { fileName, contentType } = await c.req.json();
if (!fileName || !contentType) throw new Error('fileName and contentType required');
const objectKey = `${randomUUID()}-${fileName}`;
const publicFileUrl = R2_PUBLIC_BASE_URL ? `${R2_PUBLIC_BASE_URL}/${objectKey}` : null;
const command = new PutObjectCommand({
Bucket: R2_BUCKET,
Key: objectKey,
ContentType: contentType,
});
const presignedUrl = await getSignedUrl(s3, command, { expiresIn: 300 });
return c.json({ success: true, presignedUrl, objectKey, publicFileUrl });
} catch (error) {
console.error('Presign Error:', error.message);
return c.json({ success: false, error: 'Failed to prepare upload' }, 500);
}
});
// 2. Save Metadata after Client Upload Confirmation
app.post('/save-metadata', authMiddleware, async (c) => {
try {
const { objectKey, publicFileUrl } = await c.req.json();
const userId = c.get('userId');
if (!objectKey) throw new Error('objectKey required');
const finalFileUrl =
publicFileUrl ||
(R2_PUBLIC_BASE_URL ? `${R2_PUBLIC_BASE_URL}/${objectKey}` : 'URL not available');
await sql`
INSERT INTO r2_files (object_key, file_url, user_id)
VALUES (${objectKey}, ${finalFileUrl}, ${userId})
`;
console.log(`Metadata saved for R2 object: ${objectKey}`);
return c.json({ success: true });
} catch (error) {
console.error('Metadata Save Error:', error.message);
return c.json({ success: false, error: 'Failed to save metadata' }, 500);
}
});
const port = 3000;
serve({ fetch: app.fetch, port }, (info) => {
console.log(`Server running at http://localhost:${info.port}`);
});
```
--------------------------------
### Install Node-Postgres Driver and Dotenv
Source: https://neon.com/docs/guides/express
Installs the pg (node-postgres) driver for traditional Node.js servers and dotenv for environment variable management.
```shell
npm install pg dotenv
```
--------------------------------
### Connect to Database with User Credentials
Source: https://neon.com/docs/manage/database-access
This is an example of how to connect to a Neon database using the psql command-line tool with a specific user and password. It demonstrates a successful connection and a sample INSERT query.
```bash
psql postgresql://readwrite_user1:AbC123dEf@ep-cool-darkness-123456.us-west-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
psql (15.2 (Ubuntu 15.2-1.pgdg22.04+1), server 15.3)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.
dbname=> INSERT INTO (col1, col2) VALUES (1, 2);
```
--------------------------------
### Install Neon CLI in GitHub Actions (Binary)
Source: https://neon.com/docs/cli/install
Download and install the latest Neon CLI binary for Linux x64 within a GitHub Actions workflow. This method ensures the CLI is available in the PATH.
```yaml
- name: Install Neon CLI
run: |
curl -L https://github.com/neondatabase/neon-pkgs/releases/latest/download/neonctl-linux-x64 -o /usr/local/bin/neonctl
chmod +x /usr/local/bin/neonctl
```
--------------------------------
### Table Output Example for Branches
Source: https://neon.com/docs/cli/branches
Example of the table output when listing branches, showing essential information like branch ID, name, creation, and update timestamps.
```text
┌────────────────────────┬──────────────────────────┬──────────────────────┬──────────────────────┐
│ Id │ Name │ Created At │ Updated At │
├────────────────────────┼──────────────────────────┼──────────────────────┼──────────────────────┤
│ br-small-meadow-878874 │ production [default] │ 2023-07-06T13:15:12Z │ 2023-07-06T14:26:32Z │
├────────────────────────┼──────────────────────────┼──────────────────────┼──────────────────────┤
│ br-round-queen-335380 │ development [current] │ 2023-07-06T14:45:50Z │ 2023-07-06T14:45:50Z │
└────────────────────────┴──────────────────────────┴──────────────────────┴──────────────────────┘
```
--------------------------------
### Install PostgreSQL Driver and dotenv
Source: https://neon.com/docs/guides/django
Install the `psycopg` (psycopg3) driver for PostgreSQL and `python-dotenv` for managing environment variables using pip.
```bash
pip install "psycopg[binary]" python-dotenv
```
--------------------------------
### Bootstrap mastra Template
Source: https://neon.com/docs/ai-gateway/overview
Use this command to bootstrap the mastra starter template, a personal assistant that leverages AI Gateway for LLM calls.
```bash
neonctl bootstrap --template mastra
```
--------------------------------
### CopyPrompt Component Example
Source: https://neon.com/docs/community/component-guide
Component for displaying a copyable LLM prompt from a file. Requires the `src` prop pointing to the prompt file in `public/prompts/`.
```mdx
```
--------------------------------
### Install Drizzle and Neon Serverless Driver
Source: https://neon.com/docs/guides/drizzle
Installs Drizzle ORM, the Neon serverless HTTP driver, dotenv for environment variables, and Drizzle Kit for migrations. Suitable for serverless environments.
```bash
npm install drizzle-orm @neondatabase/serverless dotenv
npm install -D drizzle-kit
```
--------------------------------
### Run Prisma CRUD Example
Source: https://neon.com/docs/guides/prisma
Executes the TypeScript script that demonstrates Prisma Client's CRUD operations.
```bash
npx tsx src/main.ts
```
--------------------------------
### Add synchronous postgres dependencies
Source: https://neon.com/docs/guides/rust
Add the `postgres`, `postgres-openssl`, and `dotenvy` crates for a synchronous setup.
```bash
cargo add postgres postgres-openssl openssl dotenvy
```
--------------------------------
### Example pg_dump command for Neon
Source: https://neon.com/docs/guides/export-neon-postgres-compatible
An example of the `pg_dump` command with a specific Neon connection string and output file name. The `-Fc` flag creates a custom-format archive, `-v` enables verbose output, `-d` specifies the connection string, and `-f` sets the output file.
```bash
pg_dump -Fc -v -d "postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/neondb?sslmode=require&channel_binding=require" -f mydatabase.bak
```
--------------------------------
### Example Read Replica Connection String
Source: https://neon.com/docs/guides/read-replica-adhoc-queries
A typical connection string format for a Neon read replica. Ensure to replace placeholders with your actual credentials and endpoint details.
```bash
postgresql://user:password@ep-read-replica-123456.us-east-2.aws.neon.tech/dbname?sslmode=require&channel_binding=require
```
--------------------------------
### Create a Neon Project using CLI
Source: https://neon.com/docs/manage/projects
Use the neonctl CLI to create a new project. Specify the project name and region ID. The output will include the project ID and default connection string.
```bash
neon projects create --name myproject --region-id aws-us-east-2
```
--------------------------------
### Run Rails Server
Source: https://neon.com/docs/guides/rails-migrations
Start the Rails development server to make the application accessible via a web browser.
```bash
rails server
```
--------------------------------
### Install Neon CLI with Homebrew (macOS)
Source: https://neon.com/docs/cli/install
Use Homebrew to install the Neon CLI on macOS. This is a common method for macOS users.
```bash
brew install neonctl
```
--------------------------------
### Mermaid Sequence Diagram Example
Source: https://neon.com/docs/community/mermaid-diagrams
Illustrates a sequence diagram for client-proxy-compute-storage interactions, showing connection requests and data flow.
```mermaid
sequenceDiagram
participant Client
participant Proxy
participant Compute
participant Storage
Client->>Proxy: Connection Request
Proxy->>Compute: Wake Up
Compute->>Storage: Load Data
Storage-->>Compute: Data Ready
Compute-->>Proxy: Ready
Proxy-->>Client: Connected
```
--------------------------------
### Create and Populate Books Table
Source: https://neon.com/docs/data-types/integer
Creates a 'books' table using INTEGER for book_id and SMALLINT for copies_in_stock, then inserts sample data.
```sql
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
copies_in_stock SMALLINT
);
INSERT INTO books (book_id, title, copies_in_stock)
VALUES
(1, 'War and Peach', 50),
(2, 'The Great Gatsby', 20),
(3, 'The Catcher in the Rye', 100);
```
--------------------------------
### Connection String Example
Source: https://neon.com/docs/get-started/connect-neon
A standard PostgreSQL connection string format used to connect to Neon. It includes role, password, hostname, and database.
```text
postgresql://alex:AbC123dEf@ep-cool-darkness-a1b2c3d4.us-east-2.aws.neon.tech/dbname?sslmode=require
```
--------------------------------
### Add Neon MCP Server to Claude Desktop (OAuth)
Source: https://neon.com/docs/ai/connect-mcp-clients-to-neon
Install the Neon MCP server for Claude Desktop using this command. A restart of Claude Desktop is required after installation.
```bash
npx add-mcp https://mcp.neon.tech/mcp -a claude-desktop
```
--------------------------------
### React/Vite Client SDK Setup
Source: https://neon.com/docs/auth/overview
Initialize the Neon Auth client-side SDK for React or Vite applications. The VITE_NEON_AUTH_URL environment variable must be configured.
```typescript
import { createAuthClient } from '@neondatabase/neon-js/auth';
export const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL);
```
--------------------------------
### CLI Connection Response
Source: https://neon.com/docs/guides/schema-diff-tutorial
Example output from the Neon CLI after successfully connecting to a database branch via psql.
```bash
INFO: Connecting to the database using psql...
psql (16.1, server 16.2)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.
people=>
```
--------------------------------
### Organization Response Example
Source: https://neon.com/docs/manage/orgs-api-consumption
Example JSON response when listing organizations. The `id` field is the `org_id` required for subsequent consumption queries.
```json
{
"organizations": [
{
"id": "org-morning-bread-81040908",
"name": "Morning Bread Organization",
"handle": "morning-bread-organization-org-morning-bread-81040908",
"plan": "free_v2",
"created_at": "2025-04-30T14:43:00Z",
"managed_by": "console",
"updated_at": "2025-04-30T14:46:22Z"
},
{
"id": "org-super-grass-41324851",
"name": "Super Org Inc",
"handle": "super-org-inc-org-super-grass-41324851",
"plan": "scale_v2",
"created_at": "2025-06-02T16:56:18Z",
"managed_by": "console",
"updated_at": "2025-06-02T16:56:18Z"
}
]
}
```
--------------------------------
### Node.js Example with Neon Driver
Source: https://neon.com/docs/serverless/serverless-driver
Basic usage of the Neon serverless driver within a Node.js environment for fetching data.
```javascript
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
const posts = await sql`SELECT * FROM posts WHERE id = ${postId}`;
// or using query() for parameterized queries
const posts = await sql.query('SELECT * FROM posts WHERE id = $1', [postId]);
// `posts` is now [{ id: 1, title: 'My post', ... }] (or undefined)
```
--------------------------------
### Get Connection String, Connect with psql, and Run Query
Source: https://neon.com/docs/cli/connection-string
Generate a connection string, connect using psql, and execute a specific SQL query.
```bash
neonctl connection-string --psql -- -c "SELECT version()"
```
--------------------------------
### Example Backend Response for Signature Generation
Source: https://neon.com/docs/guides/cloudinary
This is an example of the JSON response your backend should provide when generating upload signatures and parameters for Cloudinary.
```json
{
"success": true,
"signature": "a1b2c3d4e5f6...",
"timestamp": 1713999600,
"api_key": "YOUR_CLOUDINARY_API_KEY"
}
```
--------------------------------
### Schema Comparison Diff Output Example
Source: https://neon.com/docs/guides/schema-diff
This is an example of the diff output from the compare_schema endpoint, highlighting added and removed lines in the schema.
```diff
--- a/neondb
+++ b/neondb
@@ -27,7 +27,8 @@
CREATE TABLE public.playing_with_neon (
id integer NOT NULL,
name text NOT NULL,
- value real
+ value real,
+ created_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP
);
```
--------------------------------
### Install Neon CLI in GitHub Actions (Homebrew)
Source: https://neon.com/docs/cli/install
Install or upgrade the Neon CLI in a GitHub Actions workflow using Homebrew. Homebrew automatically fetches the latest version.
```yaml
- name: Install Neon CLI
run: brew install neonctl || brew upgrade neonctl
```
--------------------------------
### Example Liquibase Changelog Output
Source: https://neon.com/docs/guides/liquibase-workflow
An example of a Liquibase changelog file generated by the `generateChangeLog` command, detailing database schema changes.
```xml
```
--------------------------------
### Example pgloader Migration Output
Source: https://neon.com/docs/import/migrate-mssql
This is an example of the output you might see when running the pgloader migration command. It includes a summary of tables, errors, data read, imported rows, bytes transferred, and time taken for various stages of the migration.
```plaintext
2024-09-12T10:46:54.307953Z LOG report summary reset
table name errors read imported bytes total time read write
------------------------ --------- --------- --------- --------- -------------- --------- ---------
fetch meta data 0 65 65 0.280s
Create Schemas 0 0 0 0.116s
Create SQL Types 0 0 0 0.232s
Create tables 0 26 26 9.120s
Set Table OIDs 0 13 13 0.120s
------------------------ --------- --------- --------- --------- -------------- --------- ---------
dbo.customercustomerdemo 0 0 0 1.300s 0.124s
dbo.categories 0 8 8 64.4 kB 1.224s 0.144s 0.004s
dbo.customers 0 91 91 11.3 kB 2.520s 0.140s
dbo.customerdemographics 0 0 0 2.152s 0.088s
dbo.employees 0 9 9 76.0 kB 3.088s 0.136s 0.004s
dbo.employeeterritories 0 49 49 0.4 kB 3.112s 0.096s
dbo.orders 0 830 830 118.5 kB 3.656s 1.380s 0.060s
dbo."Order Details" 0 2155 2155 44.0 kB 3.268s 1.372s 0.008s
dbo.region 0 4 4 0.2 kB 2.832s 0.132s
dbo.products 0 77 77 4.2 kB 2.660s 0.132s
dbo.suppliers 0 29 29 3.9 kB 3.508s 0.120s
dbo.shippers 0 3 3 0.1 kB 2.892s 0.104s
dbo.territories 0 53 53 3.1 kB 3.568s 0.108s
------------------------ --------- --------- --------- --------- -------------- --------- ---------
COPY Threads Completion 0 4 4 5.576s
Create Indexes 0 39 39 14.252s
Index Build Completion 0 39 39 3.072s
Reset Sequences 0 6 6 1.500s
Primary Keys 0 13 13 5.024s
Create Foreign Keys 0 13 13 5.016s
Create Triggers 0 0 0 0.256s
Install Comments 0 0 0 0.000s
------------------------ --------- --------- --------- --------- -------------- --------- ---------
Total import time ✓ 3308 3308 326.0 kB 34.696s
2024-09-12T10:46:54.339953Z INFO Stopping monitor
```
--------------------------------
### Get Neon Project Command Syntax
Source: https://neon.com/docs/cli/projects
This is the general syntax for the `neonctl projects get` command. Replace `` with the actual project ID and `[options]` with any desired command-line options.
```bash
neonctl projects get [options]
```
--------------------------------
### List Available Tools with Filters
Source: https://neon.com/docs/ai/neon-mcp-server
Use `curl` to verify which tools are active for a given configuration without authenticating. This example filters for read-only querying tools.
```bash
curl "https://mcp.neon.tech/api/list-tools?readonly=true&category=querying"
```
--------------------------------
### Example Prisma Client Usage
Source: https://neon.com/docs/guides/prisma
Demonstrates basic CRUD operations (CREATE, READ, UPDATE, DELETE) using the Prisma Client instance connected to Neon.
```typescript
import { prisma } from './db'
async function main() {
// CREATE
const newUser = await prisma.user.create({
data: { name: 'Alice', email: `alice-${Date.now()}@example.com` },
})
console.log('Created user:', newUser)
// READ
const foundUser = await prisma.user.findUnique({ where: { id: newUser.id } })
console.log('Found user:', foundUser)
// UPDATE
const updatedUser = await prisma.user.update({
where: { id: newUser.id },
data: { name: 'Alice Smith' },
})
console.log('Updated user:', updatedUser)
// DELETE
await prisma.user.delete({ where: { id: newUser.id } })
console.log('Deleted user.')
}
main()
.catch((error) => {
console.error(error)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
```
--------------------------------
### Create and Insert Product Sales Data
Source: https://neon.com/docs/extensions/tablefunc
Sets up the sample product_sales_long table and populates it with initial data for demonstrating the crosstab function.
```sql
CREATE TABLE product_sales_long (
product TEXT,
quarter TEXT,
sales INT
);
INSERT INTO product_sales_long (product, quarter, sales) VALUES
('Apple', 'Q1', 100),
('Apple', 'Q2', 120),
('Banana', 'Q1', 80),
('Apple', 'Q3', 110),
('Banana', 'Q2', 95);
```
--------------------------------
### Example Test Branch Name
Source: https://neon.com/docs/get-started/workflow-primer
An example of a test branch name using an epoch UNIX timestamp for the time of test execution.
```bash
test/feat/new-login-loginPageFunctionality-1a2b3c4d-20240211T1530
```
--------------------------------
### AWS Cognito Example JWKS URL
Source: https://neon.com/docs/data-api/custom-authentication-providers
An example of an AWS Cognito JWKS URL with specific region and user pool ID.
```bash
https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX/.well-known/jwks.json
```
--------------------------------
### Scaffold a new Exograph project
Source: https://neon.com/docs/guides/exograph
Use the `exo new` command to create a new Exograph project and `cd` into its directory.
```bash
exo new todo
cd todo
```
--------------------------------
### Deploy to a specific branch
Source: https://neon.com/docs/cli/config
Example of deploying configurations to a specific branch named 'feature/auth'.
```bash
neonctl deploy --branch feature/auth
```
--------------------------------
### Extract a Subarray from Start Index to End
Source: https://neon.com/docs/extensions/intarray
Extracts a portion of an integer array from a specified starting index (1-based) to the end of the array.
```sql
SELECT subarray('{1,2,3,4,5}'::integer[], 3);
-- Result: {3,4,5}
```
--------------------------------
### Pooled Connection String Example
Source: https://neon.com/docs/connect/choose-connection
This is an example of a connection string for a pooled connection to Neon. Pooled connections route traffic through PgBouncer for efficient connection management, suitable for serverless apps and high-concurrency workloads.
```text
postgresql://user:pass@ep-cool-rain-123456-pooler.us-east-2.aws.neon.tech/neondb?sslmode=require&channel_binding=require
```
--------------------------------
### Get Function Status (API)
Source: https://neon.com/docs/compute/functions/deploy
Retrieve details about a specific function, including its invocation URL, using a GET request to the API.
```text
GET /projects/{project_id}/branches/{branch_id}/functions/{slug}
```
--------------------------------
### Create a New Project and Link
Source: https://neon.com/docs/cli/link
This command creates a new Neon project with the specified name and region, then links the current directory to it.
```bash
neonctl link --org-id org-abc123 --project-name my-app --region-id aws-us-east-2
```
--------------------------------
### Retrieve Neon Database Connection String
Source: https://neon.com/docs/guides/deno
Example format of a Neon database connection string. Ensure to replace placeholders with your actual credentials and endpoint.
```bash
postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/neondb?sslmode=require&channel_binding=require
```
--------------------------------
### Create a Basic Subscription
Source: https://neon.com/docs/guides/logical-replication-manage
Creates a subscription named 'my_subscription' that connects to a specified database and subscribes to 'my_publication'. Replace connection details with your Neon database string.
```sql
CREATE SUBSCRIPTION my_subscription
CONNECTION 'postgresql://username:password@host:port/dbname'
PUBLICATION my_publication;
```
--------------------------------
### Displaying Version Information
Source: https://neon.com/docs/extensions/pg_repack
The --version option displays the currently installed version of the pg_repack tool.
```bash
pg_repack --version
```
--------------------------------
### Run Node.js Application
Source: https://neon.com/docs/guides/sequelize
Command to execute the Node.js application. Ensure you have Node.js installed.
```bash
node index.js
```
--------------------------------
### Run Neon CLI Binary (Windows)
Source: https://neon.com/docs/cli/install
Execute the Neon CLI after downloading the Windows binary. Replace `` and `[options]` with your desired arguments.
```bash
neonctl-win-x64.exe [options]
```
--------------------------------
### Install Dependencies for Backend RLS
Source: https://neon.com/docs/guides/rls-query-execution
Install the necessary Node.js packages for using Drizzle ORM with the Neon serverless driver and JWT verification.
```bash
npm install drizzle-orm @neondatabase/serverless jose
```
--------------------------------
### Configure Consumption Limits
Source: https://neon.com/docs/guides/embedded-postgres
Set consumption limits for compute time, storage, and data transfer when creating a project. This example sets limits for a 'starter' tier user and requires a Neon API key.
```bash
curl --request POST \
--url https://console.neon.tech/api/v2/projects \
--header 'Accept: application/json' \
--header "Authorization: Bearer $NEON_API_KEY" \
--header 'Content-Type: application/json' \
--data '{ \
"project": { \
"settings": { \
"quota": { \
"active_time_seconds": 36000, \
"compute_time_seconds": 9000, \
"written_data_bytes": 1000000000, \
"data_transfer_bytes": 500000000, \
"logical_size_bytes": 100000000 \
} \
}, \
"name": "starter-tier-user", \
"pg_version": 16 \
} \
}'
```
--------------------------------
### Install Neon Serverless Driver using npm
Source: https://neon.com/docs/changelog/2024-04-19
Install the Neon serverless driver package from the JavaScript Registry (JSR) using npm. This package is compatible with npm and works across various JavaScript runtimes.
```bash
npm install @neon/serverless
```
--------------------------------
### Run Laravel Development Server
Source: https://neon.com/docs/guides/laravel-migrations
Start the development server using Artisan. Access your application at `http://localhost:8000`.
```bash
php artisan serve
```
--------------------------------
### Install Neon Serverless Driver and Dotenv
Source: https://neon.com/docs/guides/express
Installs the @neondatabase/serverless driver for edge and serverless platforms, along with dotenv for environment variable management.
```shell
npm install @neondatabase/serverless dotenv
```
--------------------------------
### Mermaid State Diagram Example
Source: https://neon.com/docs/community/mermaid-diagrams
Demonstrates a state diagram for managing connection states (Idle, Active, Suspended) with transitions.
```mermaid
stateDiagram-v2
[*] --> Idle
Idle --> Active: Connection
Active --> Idle: Timeout
Active --> Suspended: Manual Suspend
Suspended --> Active: Resume
Idle --> [*]: Delete
```
--------------------------------
### Create Project Directory
Source: https://neon.com/docs/guides/reflex
Create a new directory for your Reflex project and navigate into it.
```bash
mkdir with_reflex
cd with_reflex
```
--------------------------------
### Verify Migration with Application Queries
Source: https://neon.com/docs/import/migrate-from-railway
Example SQL queries to run against your Neon database to verify data integrity after migration.
```sql
SELECT * FROM lego_inventory_parts ORDER BY quantity DESC LIMIT 5;
SELECT parent_id, COUNT(name) FROM lego_themes GROUP BY parent_id;
```
--------------------------------
### Install Postgres Extensions with SQL
Source: https://neon.com/docs/changelog/2026-02-06
Use these SQL commands to install the newly supported pg_graphql and pgx_ulid extensions in your Neon Postgres database.
```sql
CREATE EXTENSION pg_graphql;
CREATE EXTENSION pgx_ulid;
```
--------------------------------
### Download Neon CLI Binary (Windows)
Source: https://neon.com/docs/cli/install
Download the Windows standalone binary for the Neon CLI. No installation is required; you can run it directly from the download directory.
```bash
curl -sL -O https://github.com/neondatabase/neon-pkgs/releases/latest/download/neonctl-win-x64.exe
```
--------------------------------
### Dump and restore a database with pg_dump and pg_restore
Source: https://neon.com/docs/import/migrate-from-postgres
This example demonstrates dumping a PostgreSQL database to a file using `pg_dump` and then restoring it to a Neon database with `pg_restore`. Ensure the target Neon database exists before restoring.
```bash
~$ cd mydump
~/mydump$ pg_dump -Fc -v -d postgresql://[user]:[password]@[neon_hostname]/pagila -f mydumpfile.bak
```
```bash
~/mydump$ ls
mydumpfile.bak
```
```bash
~/mydump$ pg_restore -v -d postgresql://[user]:[password]@[neon_hostname]/pagila mydumpfile.bak
```
--------------------------------
### Verify Neon Plugin Installation
Source: https://neon.com/docs/ai/ai-claude-code-plugin
After installation, verify that the neon-postgres skill is accessible to Claude Code. This confirms the plugin is active and ready for use.
```text
which skills do you have access to?
```
--------------------------------
### Initialize Prisma Client with Read Replicas
Source: https://neon.com/docs/guides/read-replica-integrations
Extend your Prisma Client instance with the read replicas extension. Provide the read replica connection string in the `url` option. Read operations go to the replica, and write operations go to the primary.
```javascript
import { PrismaClient } from '@prisma/client';
import { readReplicas } from '@prisma/extension-read-replicas';
const prisma = new PrismaClient().$extends(
readReplicas({
url: process.env.DATABASE_URL_REPLICA,
})
);
// Query is run against the database replica
await prisma.post.findMany();
// Query is run against the primary database
await prisma.post.create({
data: {
/** */
},
});
```
--------------------------------
### SQL Result Example for Masking Rules
Source: https://neon.com/docs/workflows/data-anonymization
This is an example result set from querying the `anon.pg_masking_rules` view, showing the details of applied masking rules.
```text
relnamespace | relname | attname | masking_function | masking_value
--------------+---------+---------+-------------------------------+---------------
public | users | address | | 'CONFIDENTIAL'
public | users | email | anon.dummy_free_email() |
public | users | phone | anon.partial(phone, 2, 'XXX-XXXX', 2) |
```
--------------------------------
### Steps Component Example
Source: https://neon.com/docs/community/component-guide
Use the Steps component to create numbered, step-by-step instructions. Each step is defined by an h2 heading within the component.
```mdx
## Get a Glass
Take a clean glass from the cabinet or dish rack.
## Turn on Tap
Adjust the faucet to your preferred temperature and flow rate.
## Fill and Drink
Fill the glass to desired level and enjoy your water.
```
--------------------------------
### Example Reset Branch from Parent with Project ID using CLI
Source: https://neon.com/docs/guides/reset-from-parent
An example of resetting the 'development' branch from its parent within the 'noisy-pond-12345678' project.
```bash
neon branches reset development --parent --project-id noisy-pond-12345678
```
--------------------------------
### Insert initial data into 'favorite_coffee_blends' table
Source: https://neon.com/docs/guides/netlify-functions
SQL command to populate the coffee blends table with sample data.
```sql
INSERT INTO favorite_coffee_blends (name, origin, notes)
VALUES
('Morning Joy', 'Ethiopia', 'Citrus, Honey, Floral'),
('Dark Roast Delight', 'Colombia', 'Rich, Chocolate, Nutty'),
('Arabica Aroma', 'Brazil', 'Smooth, Caramel, Fruity'),
('Robusta Revolution', 'Vietnam', 'Strong, Bold, Bitter');
```
--------------------------------
### Create Neon Project with Neon CLI
Source: https://neon.com/docs/get-started/full-backend-quickstart
Use the Neon CLI to authenticate and create a new Neon project named 'my-backend'. The connection string will be outputted.
```bash
npx neonctl@latest auth
npx neonctl@latest projects create --name my-backend
```
--------------------------------
### Save Metadata Response Example
Source: https://neon.com/docs/guides/aws-s3
This is an example of a successful JSON response from the save-metadata endpoint, confirming that the file's metadata has been saved to the database.
```json
{
"success": true
}
```
--------------------------------
### Example Output of index.js
Source: https://neon.com/docs/guides/express
This is the expected JSON output when running the `index.js` script and accessing `http://localhost:4242`.
```shell
{ version: 'PostgreSQL 16.0 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit' }
```
--------------------------------
### .NET Connection Strings
Source: https://neon.com/docs/get-started/connect-neon
Examples of connection strings for .NET applications connecting to Neon, including basic, SSL-enabled, and Entity Framework configurations.
```csharp
# .NET example
## Connection string
"Host=ep-cool-darkness-123456.us-east-2.aws.neon.tech;Database=dbname;Username=alex;Password=AbC123dEf"
## with SSL
"Host=ep-cool-darkness-123456.us-east-2.aws.neon.tech;Database=dbname;Username=alex;Password=AbC123dEf;SSL Mode=Require;Trust Server Certificate=true"
## Entity Framework (appsettings.json)
{
...
"ConnectionStrings": {
"DefaultConnection": "Host=ep-cool-darkness-123456.us-east-2.aws.neon.tech;Database=dbname;Username=alex;Password=AbC123dEf;SSL Mode=Require;Trust Server Certificate=true"
},
...
}
```
--------------------------------
### Example JSON response from Hono app
Source: https://neon.com/docs/guides/hono
This is an example of the JSON response you will receive when accessing your Hono application after successfully connecting to Neon Postgres.
```json
{
"version": "PostgreSQL 17.4 on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit"
}
```
--------------------------------
### Download Neon CLI Binary (Linux x64)
Source: https://neon.com/docs/cli/install
Download the Linux x64 standalone binary for the Neon CLI. No installation is required; you can run it directly from the download directory.
```bash
curl -sL https://github.com/neondatabase/neon-pkgs/releases/latest/download/neonctl-linux-x64 -o neonctl
```
--------------------------------
### libsql/client Data Insertion and Querying
Source: https://neon.com/docs/import/migrate-from-turso
Shows how to insert and query data using the libsql/client, including argument binding.
```javascript
// Inserting data
await db.execute({
sql: "INSERT INTO users (username) VALUES (?)",
args: ["alice"],
});
// Querying data
const rs = await db.execute("SELECT * FROM users");
const users = rs.rows;
```
--------------------------------
### Neon Postgres Connection String Example
Source: https://neon.com/docs/guides/draxlr
This is an example of a Neon Postgres connection string. Use this format when connecting Draxlr to your Neon database.
```text
postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require
```
--------------------------------
### Creating a User Profiles Table with JSONB
Source: https://neon.com/docs/data-types/json
Shows how to create a table with a JSONB column and insert semi-structured user profile data.
```sql
CREATE TABLE user_profiles (
id SERIAL PRIMARY KEY,
profile JSONB NOT NULL
);
INSERT INTO user_profiles (profile)
VALUES
('{"name": "Alice", "age": 30, "interests": ["music", "travel"], "settings": {"privacy": "public", "notifications": true, "theme": "light"}}'),
('{"name": "Bob", "age": 25, "interests": ["photography", "cooking"], "settings": {"privacy": "private", "notifications": false}, "city": "NYC"}'),
('{"name": "Charlie", "interests": ["music", "cooking"], "settings": {"privacy": "private", "notifications": true, "language": "English"}}');
```
--------------------------------
### Create and link a new Netlify Site
Source: https://neon.com/docs/guides/netlify-functions
Commands to create a new Netlify project directory and link it to a new Netlify Site. Follow the prompts to name your site.
```bash
mkdir neon-netlify-example && cd neon-netlify-example
netlify sites:create
```
--------------------------------
### Create a bucket using Neon API
Source: https://neon.com/docs/storage/buckets
Create a bucket programmatically using the Neon API. Requires project ID, branch ID, and an API key.
```bash
curl -X POST "https://console.neon.tech/api/v2/projects/{project_id}/branches/{branch_id}/buckets" \
-H "Authorization: Bearer $NEON_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "my-bucket", "access_level": "private"}'
```
--------------------------------
### Example PostgreSQL Connection String Format
Source: https://neon.com/docs/community/contribution-guide
This is the general format for a PostgreSQL connection string. Ensure all placeholders are replaced with actual values.
```text
postgresql://[user]:[password]@[neon_hostname]/[dbname]
```
--------------------------------
### View Default Branch Status
Source: https://neon.com/docs/cli/branches
Example output after setting a default branch, showing the branch details and its default status.
```text
┌────────────────────┬──────────┬─────────┬──────────────────────┬──────────────────────┐
│ Id │ Name │ Default │ Created At │ Updated At │
├────────────────────┼──────────┼─────────┼──────────────────────┼──────────────────────┤
│ br-odd-frog-703504 │ mybranch │ true │ 2023-07-11T12:22:12Z │ 2023-07-11T12:22:59Z │
└────────────────────┴──────────┴─────────┴──────────────────────┴──────────────────────┘
```
--------------------------------
### Initialize Neon MCP Server with npx
Source: https://neon.com/docs/changelog/2025-12-19
Use this command to authenticate via OAuth, create a Neon API key, and configure AI editors like Cursor, VS Code, or Claude Code CLI to connect to Neon. It automates manual configuration steps and API key management for existing and new users.
```bash
npx neonctl@latest init
```
--------------------------------
### Google Authorized Redirect URI Example
Source: https://neon.com/docs/auth/guides/setup-oauth
Example of an authorized redirect URI for Google. This format must be registered with Google Cloud Console.
```text
https://ep-example.neonauth.us-east-2.aws.neon.tech/neondb/auth/callback/google
```
--------------------------------
### Start anonymization
Source: https://neon.com/docs/workflows/data-anonymization-api
Starts or restarts the anonymization process for branches in `initialized`, `error`, or `anonymized` state. This action applies all defined masking rules.
```APIDOC
## POST /projects/{project_id}/branches/{branch_id}/anonymize
### Description
Starts or restarts the anonymization process for branches in `initialized`, `error`, or `anonymized` state. Applies all defined masking rules.
### Method
POST
### Endpoint
/projects/{project_id}/branches/{branch_id}/anonymize
### Parameters
#### Path Parameters
- **project_id** (string) - Required - The ID of the project.
- **branch_id** (string) - Required - The ID of the branch.
### Response
#### Success Response (200)
- **branch_id** (string) - The ID of the branch.
- **project_id** (string) - The ID of the project.
- **state** (string) - The state of the branch after the anonymization process.
- **status_message** (string) - A message describing the result of the anonymization process.
- **created_at** (string) - Timestamp when the anonymization process was initiated.
- **updated_at** (string) - Timestamp when the anonymization process was last updated.
### Response Example
{
"branch_id": "br-shiny-butterfly-w4393738",
"project_id": "wild-sky-00366102",
"state": "anonymized",
"status_message": "Anonymization completed successfully (2 tables, 3 masking rules applied)",
"created_at": "2025-11-01T14:01:39Z",
"updated_at": "2025-11-01T14:01:41Z"
}
```
--------------------------------
### Code Tabs Example
Source: https://neon.com/docs/community/contribution-guide
Shows how to use code tabs to display multiple code snippets for different environments or languages.
```markdown
```shell
npm install pg
```
```shell
npm install postgres
```
```
--------------------------------
### Add Repo to Supervision Tree
Source: https://neon.com/docs/guides/elixir-ecto
Ensure `Friends.Repo` is included in the `children` list within the `start` function of `lib/friends/application.ex` to start the Ecto process.
```elixir
children = [
Friends.Repo,
]
```
--------------------------------
### Extract a Subarray with Start Index and Length
Source: https://neon.com/docs/extensions/intarray
Extracts a portion of an integer array, specifying the starting index (1-based) and the number of elements to include.
```sql
SELECT subarray('{1,2,3,4,5}'::integer[], 2, 3);
-- Result: {2,3,4}
```
--------------------------------
### Install Firebase Admin and Psycopg
Source: https://neon.com/docs/import/migrate-from-firebase
Install the necessary Python packages for interacting with Firebase and Neon Postgres. Ensure you are using Python 3.10 or later.
```bash
pip install firebase-admin "psycopg[binary,pool]"
```
--------------------------------
### Load Data with Neon CLI (Create Project)
Source: https://neon.com/docs/import/import-sample-data
Load a SQL file into a newly created Neon project using the Neon CLI and psql. The `--psql` flag ensures psql is used for execution.
```bash
neon projects create --psql -- -f periodic_table.sql
```
--------------------------------
### Enable Experimental Extensions
Source: https://neon.com/docs/extensions/pg-extensions
To use experimental extensions, set this session variable to 'true' before installing the extension. Use with caution as these are not recommended for production.
```sql
SET neon.allow_unstable_extensions = 'true';
```
--------------------------------
### Install lakebase_vector Extension
Source: https://neon.com/docs/extensions/lakebase-vector
Enables the lakebase_vector extension and its dependencies. Requires Lakebase Search to be enabled on your Neon project.
```sql
CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
```
--------------------------------
### Sign up with Email and Password
Source: https://neon.com/docs/auth/reference/nextjs-server
Creates a new user account with the provided email, password, and name. This is the standard method for new user registration.
```typescript
const { data, error } = await auth.signUp.email({
email: 'user@example.com',
password: 'secure-password',
name: 'John Doe',
});
```
--------------------------------
### Enable pgcrypto Extension
Source: https://neon.com/docs/extensions/pgcrypto
Enables the pgcrypto extension if it is not already installed. This is the first step before using any pgcrypto functions.
```sql
CREATE EXTENSION IF NOT EXISTS pgcrypto;
```
--------------------------------
### Install Postgres.js Driver and Dotenv
Source: https://neon.com/docs/guides/express
Installs the postgres.js driver, suitable for both serverless and traditional Node.js environments, along with dotenv for environment variable management.
```shell
npm install postgres dotenv
```
--------------------------------
### Mermaid Git Graph Example
Source: https://neon.com/docs/community/mermaid-diagrams
Shows a basic Git graph with commits, branching, and merging operations.
```mermaid
gitGraph
commit id: "Initial"
branch development
checkout development
commit id: "Feature A"
checkout main
merge development
commit id: "Release"
```
--------------------------------
### Analyze Data with Hyperfunctions
Source: https://neon.com/docs/extensions/timescaledb
Demonstrates using hyperfunctions for data analysis. Ensure TimescaleDB is installed and the hyperfunctions extension is enabled.
```sql
SELECT
time_bucket('1 hour', ts) AS hour,
hyperloglog_agg(user_id) AS distinct_users
FROM
user_sessions
WHERE
ts >= NOW() - INTERVAL '1 day'
GROUP BY
hour
ORDER BY
hour DESC;
```
--------------------------------
### Deno Server Script with Neon
Source: https://neon.com/docs/guides/deno
This script sets up a Deno server that connects to a Neon database, creates a 'books' table if it doesn't exist, inserts initial data, and serves book data from the '/books' endpoint.
```typescript
// server.ts
import { neon } from '@neon/serverless';
const databaseUrl = Deno.env.get('DATABASE_URL')!;
const sql = neon(databaseUrl);
// Create the books table and insert initial data if it doesn't exist
await sql`
CREATE TABLE IF NOT EXISTS books (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL
)
`;
// Check if the table is empty
const { count } = await sql`SELECT COUNT(*)::INT as count FROM books`.then((rows) => rows[0]);
if (count === 0) {
// The table is empty, insert the book records
await sql`
INSERT INTO books (title, author) VALUES
('The Hobbit', 'J. R. R. Tolkien'),
('Harry Potter and the Philosopher\'s Stone', 'J. K. Rowling'),
('The Little Prince', 'Antoine de Saint-Exupéry')
`;
}
// Start the server
Deno.serve(async (req) => {
const url = new URL(req.url);
if (url.pathname !== '/books') {
return new Response('Not Found', { status: 404 });
}
try {
switch (req.method) {
case 'GET': {
const books = await sql`SELECT * FROM books`;
return new Response(JSON.stringify(books, null, 2), {
headers: { 'content-type': 'application/json' },
});
}
default:
return new Response('Method Not Allowed', { status: 405 });
}
} catch (err) {
console.error(err);
return new Response(`Internal Server Error\n\n${err.message}`, {
status: 500,
});
}
});
```
--------------------------------
### Install Drizzle and postgres.js Driver
Source: https://neon.com/docs/guides/drizzle
Installs Drizzle ORM, the lightweight postgres.js driver, dotenv, and Drizzle Kit. A modern option for Node.js applications.
```bash
npm install drizzle-orm postgres dotenv
npm install -D drizzle-kit
```
--------------------------------
### Connect to Database and Create Schema (API)
Source: https://neon.com/docs/guides/schema-diff-tutorial
Connects to the 'people' database using the retrieved connection string and applies the initial schema.
```bash
psql 'postgresql://alex:*********@ep-green-surf-a5yaumj3-pooler.us-east-2.aws.neon.tech/people?sslmode=require&channel_binding=require'
```
```sql
CREATE TABLE person (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
```
--------------------------------
### Create a project with the API
Source: https://neon.com/docs/manage/projects
This section demonstrates how to create a new project using the Neon API. It includes a cURL command for the API request and explains the response structure. For detailed attribute definitions, refer to the Neon API Reference.
```APIDOC
## POST /projects
### Description
Creates a new project in Neon.
### Method
POST
### Endpoint
/projects
### Request Body
- **project** (object) - Required - Contains project details.
- **name** (string) - Required - The name of the project to be created.
### Request Example
```bash
curl 'https://console.neon.tech/api/v2/projects' \
-H 'Accept: application/json' \
-H "Authorization: Bearer $NEON_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"project": {
"name": "myproject"
}
}' | jq
```
### Response
#### Success Response (200)
- **role** (string) - Description of the role.
- **database** (object) - Information about the database.
- **default_branch** (object) - Information about the default branch.
- **primary_read_write_compute** (object) - Information about the primary read-write compute.
```
--------------------------------
### Initialize Claimable Postgres with SDK and Seed SQL
Source: https://neon.com/docs/reference/claimable-postgres
Provision a database using the instantPostgres SDK and apply an initial SQL script using the seed option. Specify the path to your SQL script.
```javascript
const result = await instantPostgres({
referrer: 'your-app-name',
seed: { type: 'sql-script', path: './schema.sql' },
});
```
--------------------------------
### List Neon Projects
Source: https://neon.com/docs/reference/typescript-sdk
This example demonstrates how to list all Neon projects associated with your account. It first retrieves the organization ID and then uses it to fetch the list of projects.
```APIDOC
## List Projects
This operation retrieves a list of all Neon projects within a specified organization.
### Method
`apiClient.listProjects(params: { org_id: string }): Promise `
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { createApiClient } from '@neondatabase/api-client';
const apiClient = createApiClient({
apiKey: process.env.NEON_API_KEY!,
});
async function listNeonProjects() {
try {
// Get the user's organizations
const orgsResponse = await apiClient.getCurrentUserOrganizations();
const orgId = orgsResponse.data.organizations[0].id;
// List projects within the org
const response = await apiClient.listProjects({ org_id: orgId });
console.log(response.data.projects);
} catch (error) {
console.error('Error listing projects:', error);
}
}
listNeonProjects();
```
### Response
#### Success Response (200)
Returns a list of project objects.
- **data.projects** (Array) - An array of Neon project objects.
#### Response Example
```json
[
{
"id": "wandering-heart-70814840",
"platform_id": "aws",
"region_id": "aws-sa-east-1",
"name": "test-project",
"provisioner": "k8s-neonvm",
"default_endpoint_settings": {
"autoscaling_limit_min_cu": 0.25,
"autoscaling_limit_max_cu": 0.25,
"suspend_timeout_seconds": 0
},
"settings": {
"allowed_ips": [Object],
"enable_logical_replication": false,
"maintenance_window": [Object],
"block_public_connections": false,
"block_vpc_connections": false
},
"pg_version": 16,
"proxy_host": "sa-east-1.aws.neon.tech",
"branch_logical_size_limit": 512,
"branch_logical_size_limit_bytes": 536870912,
"store_passwords": true,
"active_time": 304,
"cpu_used_sec": 78,
"creation_source": "console",
"created_at": "2025-02-28T07:14:35Z",
"updated_at": "2025-02-28T07:54:53Z",
"synthetic_storage_size": 34149464,
"quota_reset_at": "2025-03-01T00:00:00Z",
"owner_id": "91cbdacd-06c2-49f5-bacf-78b9463c81ca",
"compute_last_active_at": "2025-02-28T07:54:49Z"
}
]
```
```
--------------------------------
### Install Previous pgvector Version
Source: https://neon.com/docs/changelog/2025-01-31
Use this command to install a specific previous version of the pgvector extension if needed. Ensure the version number is correct.
```sql
CREATE EXTENSION vector VERSION '0.7.4';
```
--------------------------------
### Create Phoenix Project
Source: https://neon.com/docs/guides/phoenix
Use the mix phx.new command to create a new Phoenix project. You can choose to not install dependencies immediately.
```bash
# install phx.new if you haven't already
# mix archive.install hex phx_new
mix phx.new hello
```
--------------------------------
### Run Encore application locally
Source: https://neon.com/docs/guides/encore
Start your Encore application locally. Encore automatically provisions a local PostgreSQL database.
```bash
encore run
```
--------------------------------
### Example Heroku Postgres Database Name Retrieval
Source: https://neon.com/docs/import/migrate-from-heroku
An example output of the `heroku pg:links` command, showing the name of the Heroku Postgres database.
```shell
$ heroku pg:links --app thawing-wave-57227
=== postgresql-trapezoidal-48645
```
--------------------------------
### Create Neon Project with API
Source: https://neon.com/docs/get-started/full-backend-quickstart
Create a new Neon project named 'my-backend' using the Neon API. Ensure your NEON_API_KEY is exported. The connection string is returned in the API response.
```bash
export NEON_API_KEY=neon_...
curl -X POST https://console.neon.tech/api/v2/projects \
-H "Authorization: Bearer $NEON_API_KEY" \
-H "Content-Type: application/json" \
-d '{"project": {"name": "my-backend"}}'
```
--------------------------------
### Create Table and Insert Data in Go
Source: https://neon.com/docs/guides/go
This Go script connects to a Neon database, creates a 'books' table, inserts a single record using parameterized queries, and then performs a bulk insert of multiple records using CopyFrom for efficiency. It handles environment variable loading for the connection string and includes error checking for each database operation.
```go
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5"
"github.com/joho/godotenv"
)
func main() {
// Load environment variables from .env file
err := godotenv.Load()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading .env file: %v\n", err)
os.Exit(1)
}
// Get the connection string from the environment variable
connString := os.Getenv("DATABASE_URL")
if connString == ""
{
fmt.Fprintf(os.Stderr, "DATABASE_URL not set\n")
os.Exit(1)
}
ctx := context.Background()
// Connect to the database
conn, err := pgx.Connect(ctx, connString)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(ctx)
fmt.Println("Connection established")
// Drop the table if it already exists
_, err = conn.Exec(ctx, "DROP TABLE IF EXISTS books;")
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to drop table: %v\n", err)
os.Exit(1)
}
fmt.Println("Finished dropping table (if it existed).")
// Create a new table
_, err = conn.Exec(ctx, `
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255),
publication_year INT,
in_stock BOOLEAN DEFAULT TRUE
);
`)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to create table: %v\n", err)
os.Exit(1)
}
fmt.Println("Finished creating table.")
// Insert a single book record
_, err = conn.Exec(
ctx,
"INSERT INTO books (title, author, publication_year, in_stock) VALUES ($1, $2, $3, $4);",
"The Catcher in the Rye", "J.D. Salinger", 1951, true,
)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to insert single row: %v\n", err)
os.Exit(1)
}
fmt.Println("Inserted a single book.")
// Data to be inserted
booksToInsert := [][]interface{}{
{"The Hobbit", "J.R.R. Tolkien", 1937, true},
{"1984", "George Orwell", 1949, true},
{"Dune", "Frank Herbert", 1965, false},
}
// Use CopyFrom for efficient bulk insertion
copyCount, err := conn.CopyFrom(
ctx,
pgx.Identifier{"books"},
[]string{"title", "author", "publication_year", "in_stock"},
pgx.CopyFromRows(booksToInsert),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to copy rows: %v\n", err)
os.Exit(1)
}
fmt.Printf("Inserted %d rows of data.\n", copyCount)
}
```
--------------------------------
### Bootstrap Application in Agent Mode
Source: https://neon.com/docs/cli/bootstrap
Use the `--agent` flag with `neonctl bootstrap` to initiate an application setup with a specific template. This mode outputs a JSON object for AI agent consumption, indicating the next step in a state-machine.
```bash
neonctl bootstrap my-app --template hono --agent
```
--------------------------------
### Wrangler Deployment Output
Source: https://neon.com/docs/guides/cloudflare-workers
Example output from the 'npm run deploy' command, showing upload details and the published Worker URL.
```text
❯ npm run deploy
⛅️ wrangler 3.28.1
-------------------
Total Upload: 189.98 KiB / gzip: 49.94 KiB
Uploaded my-neon-worker (4.03 sec)
Published my-neon-worker (5.99 sec)
https://my-neon-worker.anandishan2.workers.dev
Current Deployment ID: de8841dd-46e4-436d-b2c4-569e91f54c72
```
--------------------------------
### Configure Hono with Neon serverless driver
Source: https://neon.com/docs/guides/hono
Set up a Hono application to connect to Neon using the Neon serverless driver. This example demonstrates fetching the PostgreSQL version.
```typescript
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { neon } from '@neondatabase/serverless';
const app = new Hono();
app.get('/', async (c) => {
try {
const sql = neon(process.env.DATABASE_URL);
const response = await sql`SELECT version()`;
return c.json({ version: response[0]?.version });
} catch (error) {
console.error('Database query failed:', error);
return c.text('Failed to connect to database', 500);
}
});
serve(app);
```
--------------------------------
### Load Database Version with Node-postgres
Source: https://neon.com/docs/guides/sveltekit
Example load function for a SvelteKit route using node-postgres to fetch the database version.
```typescript
import { pool } from '../db.server';
export async function load() {
const client = await pool.connect();
try {
const { rows } = await client.query('SELECT version()');
const { version } = rows[0];
return {
version,
};
} finally {
client.release();
}
}
```
--------------------------------
### DetailIconCards Usage Example
Source: https://neon.com/docs/community/component-icon-guide
This example demonstrates how to use the DetailIconCards component with anchor tags, specifying href, title, description, and icon attributes for each link.
```mdx
OpenAI Integration
LangChain Integration
```
--------------------------------
### Clone Sample Project
Source: https://neon.com/docs/guides/rls-tutorial
Clone the sample application repository to follow along with the tutorial. This application integrates Neon Data API with Neon Auth.
```bash
git clone https://github.com/neondatabase-labs/neon-data-api-neon-auth.git
```
--------------------------------
### Callout Component Example
Source: https://neon.com/docs/community/component-guide
Use the Callout component for supplementary information like tips or best practices. This example includes a custom title and content.
```mdx
Make sure you have Node.js 18+ installed.
```
--------------------------------
### Local Development Server Output with .dev.vars
Source: https://neon.com/docs/guides/cloudflare-workers
Example output when running `npm run dev` after configuring `.dev.vars`, showing environment variables are loaded.
```bash
❯ npm run dev
⛅️ wrangler 3.28.1
-------------------
Using vars defined in .dev.vars
Your worker has access to the following bindings:
- Vars:
- DATABASE_URL: "(hidden)"
⎔ Starting local server...
[wrangler:inf] Ready on http://localhost:8787
```
--------------------------------
### Update SDK Initialization (After)
Source: https://neon.com/docs/auth/migrate/from-legacy-auth
Example of creating a Neon Auth client instance using the Neon Auth URL. This replaces the Stack Auth client app initialization.
```tsx
// src/auth.ts
import { createAuthClient } from '@neondatabase/auth';
export const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL);
const { useSession } = authClient;
```
--------------------------------
### Install Neon agent skills directly
Source: https://neon.com/docs/cli/init
Command to add Neon agent skills to a project, used internally by `neonctl init`.
```bash
npx skills add neondatabase/agent-skills --skill neon-postgres --agent
```
--------------------------------
### Create a bucket using neonctl
Source: https://neon.com/docs/storage/buckets
Use neonctl to create a new bucket. Specify the bucket name and optionally the access level.
```bash
neonctl bucket create my-bucket
```
```bash
neonctl bucket create my-public-bucket --access-level public_read
```
--------------------------------
### Direct HTTP Request - SELECT (GET)
Source: https://neon.com/docs/data-api/get-started
Query the Data API directly using a GET request. Include your JWT token in the Authorization header.
```APIDOC
## Example: SELECT (GET)
```bash
curl -X GET 'https://your-data-api-endpoint/rest/v1/posts?is_published=eq.true&order=created_at.desc' \
-H 'Authorization: Bearer YOUR_JWT_TOKEN' \
-H 'Content-Type: application/json'
```
```
--------------------------------
### Configure Hono with node-postgres
Source: https://neon.com/docs/guides/hono
Set up a Hono application to connect to Neon using the node-postgres driver. This example demonstrates fetching the PostgreSQL version.
```typescript
import { Pool } from 'pg';
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
const app = new Hono();
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
app.get('/', async (c) => {
const client = await pool.connect();
try {
const { rows } = await client.query('SELECT version()');
return c.json({ version: rows[0].version });
} catch (error) {
console.error('Database query failed:', error);
return c.text('Failed to connect to database', 500);
} finally {
client.release();
}
});
serve(app);
```
--------------------------------
### List Plugin Configurations
Source: https://neon.com/docs/cli/neon-auth
Lists all plugin configurations for a given project and branch. This command helps in understanding the active plugins and their settings.
```bash
neonctl neon-auth plugins list
```
--------------------------------
### Sign-up Server Action
Source: https://neon.com/docs/get-started/full-backend-quickstart
This server action handles the sign-up logic. It calls `auth.signUp.email()` with form data and redirects to `/posts` on success or returns an error message. Ensure the authentication library is correctly imported from `@/lib/auth/server`.
```typescript
'use server';
import { auth } from '@/lib/auth/server';
import { redirect } from 'next/navigation';
export async function signUpWithEmail(
_prev: { error: string } | null,
formData: FormData,
) {
const { error } = await auth.signUp.email({
name: formData.get('name') as string,
email: formData.get('email') as string,
password: formData.get('password') as string,
});
if (error) return { error: error.message || 'Failed to create account' };
redirect('/posts');
}
```
--------------------------------
### Install Codex CLI with Homebrew
Source: https://neon.com/docs/ai/ai-codex-plugin
Install the Codex CLI using Homebrew on macOS. This command ensures the Codex CLI is available in your system's PATH.
```bash
brew install --cask codex
codex
```
--------------------------------
### Run SolidStart App and View Database Version
Source: https://neon.com/docs/guides/solid-start
Execute 'npm run dev' to start your SolidStart application. Access localhost:3000 to view the PostgreSQL version information retrieved from your Neon database.
```shell
npm run dev
```
```text
PostgreSQL 16.0 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
```
--------------------------------
### Developer Isolation with Branching
Source: https://neon.com/docs/auth/branching-authentication
Shows a command-line example for creating a new branch, enabling individual developers to work in isolated authentication environments without interfering with each other.
```bash
psql "postgresql://user:password@host:port/database?sslmode=require" \
-c "CREATE BRANCH preview_branch FROM main;"
```
--------------------------------
### Schema Diff Output Example (API)
Source: https://neon.com/docs/guides/schema-diff-tutorial
This is an example of the diff output obtained from the `compare-schema` API, detailing schema changes like new tables and sequences.
```diff
--- a/people
+++ b/people
@@ -21,6 +21,44 @@
SET default_table_access_method = heap;
--
+-- Name: address; Type: TABLE; Schema: public; Owner: alex
+--
+
+CREATE TABLE public.address (
id integer NOT NULL,
person_id integer NOT NULL,
street text NOT NULL,
city text NOT NULL,
state text NOT NULL,
zip_code text NOT NULL
);
+ALTER TABLE public.address OWNER TO alex;
+
+--
+-- Name: address_id_seq; Type: SEQUENCE; Schema: public; Owner: alex
+--
+
+CREATE SEQUENCE public.address_id_seq
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+ALTER SEQUENCE public.address_id_seq OWNER TO alex;
+
+--
+-- Name: address_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alex
+--
+
+ALTER SEQUENCE public.address_id_seq OWNED BY public.address.id;
+
+
--
-- Name: person; Type: TABLE; Schema: public; Owner: alex
--
@@ -56,6 +94,13 @@
--
+-- Name: address id; Type: DEFAULT; Schema: public; Owner: alex
+--
+
```
--------------------------------
### Create and Apply Initial Prisma Migration
Source: https://neon.com/docs/guides/prisma-migrations
Generates the initial SQL migration files and applies them to the Neon database. This command also generates the Prisma Client based on the schema.
```bash
npx prisma migrate dev --name init
```
--------------------------------
### Run Flask Application
Source: https://neon.com/docs/guides/backblaze-b2
Starts the Flask development server, listening on port 3000 by default or a port specified by the PORT environment variable.
```python
if __name__ == "__main__":
port = int(os.environ.get("PORT", 3000))
app.run(host="0.0.0.0", port=port, debug=True)
```
--------------------------------
### Initialize Sequelize CLI
Source: https://neon.com/docs/guides/sequelize
Initializes the Sequelize CLI, creating configuration, migration, model, and seeder directories.
```bash
npx sequelize init
```
--------------------------------
### Run pgloader Migration
Source: https://neon.com/docs/import/migrate-mysql
Initiate the database migration process by executing the pgloader command with a configuration file.
```shell
pgloader config.load
```
--------------------------------
### Create Python Project Directory and Virtual Environment
Source: https://neon.com/docs/guides/python
Sets up a new project directory and a virtual environment for isolating Python dependencies. Activate the virtual environment before installing libraries.
```bash
mkdir neon-python-quickstart
cd neon-python-quickstart
```
```bash
# Create a virtual environment
python3 -m venv venv
# Activate the virtual environment
source venv/bin/activate
```
```bash
# Create a virtual environment
python -m venv venv
# Activate the virtual environment
.\venv\Scripts\activate
```
--------------------------------
### Download Neon CLI Binary (Linux ARM64)
Source: https://neon.com/docs/cli/install
Download the Linux ARM64 standalone binary for the Neon CLI. No installation is required; you can run it directly from the download directory.
```bash
curl -sL https://github.com/neondatabase/neon-pkgs/releases/latest/download/neonctl-linux-arm64 -o neonctl
```
--------------------------------
### JSON Output Example for Branches
Source: https://neon.com/docs/cli/branches
Example of the detailed JSON output when listing branches, showing properties like ID, name, state, size, and timestamps.
```json
[
{
"id": "br-wild-boat-648259",
"project_id": "solitary-leaf-288182",
"name": "production",
"current_state": "ready",
"logical_size": 29515776,
"creation_source": "console",
"default": true,
"cpu_used_sec": 78,
"compute_time_seconds": 78,
"active_time_seconds": 312,
"written_data_bytes": 107816,
"data_transfer_bytes": 0,
"created_at": "2023-07-09T17:01:34Z",
"updated_at": "2023-07-09T17:15:13Z"
},
{
"id": "br-shy-cake-201321",
"project_id": "solitary-leaf-288182",
"parent_id": "br-wild-boat-648259",
"parent_lsn": "0/1E88838",
"name": "development",
"current_state": "ready",
"creation_source": "console",
"default": false,
"cpu_used_sec": 0,
"compute_time_seconds": 0,
"active_time_seconds": 0,
"written_data_bytes": 0,
"data_transfer_bytes": 0,
"created_at": "2023-07-09T17:37:10Z",
"updated_at": "2023-07-09T17:37:10Z"
}
]
```
--------------------------------
### Create Employees Database and Schema
Source: https://neon.com/docs/import/import-sample-data
Initial SQL commands to create the 'employees' database and its schema.
```sql
CREATE DATABASE employees;
\c employees
CREATE SCHEMA employees;
```
--------------------------------
### OpenAI Embeddings API Response Example
Source: https://neon.com/docs/ai/ai-concepts
This is an example of the JSON response you can expect from the OpenAI Embeddings API, containing the generated embedding vector and usage information.
```json
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": [
-0.006929283495992422,
-0.005336422007530928,
... (omitted for spacing)
-4.547132266452536e-05,
-0.024047505110502243
],
}
],
"model": "text-embedding-3-small",
"usage": {
"prompt_tokens": 5,
"total_tokens": 5
}
}
```
--------------------------------
### Consume Neon data in a TanStack Start application
Source: https://neon.com/docs/guides/tanstack-start
Fetch and display data from a Neon database within a TanStack Start application's route component.
```typescript
import { createFileRoute } from "@tanstack/react-router";
import { getData } from "../data/get-neon-data.ts";
export const Route = createFileRoute("/")({
loader: async () => {
return getData();
},
component: RouteComponent,
});
export default function RouteComponent() {
const data = Route.useLoaderData();
return <>{data}>;
}
```
--------------------------------
### Development Branch Naming Convention Example
Source: https://neon.com/docs/get-started/workflow-primer
Recommended naming conventions for development branches in Neon, using prefixes like 'dev/' or 'dev/'.
```bash
dev/alice
dev/new-onboarding
```
--------------------------------
### Get Project Details with Neon CLI
Source: https://neon.com/docs/cli
Use the 'projects get ' command to retrieve detailed information about a specific Neon project using its ID.
```bash
neonctl projects get
```
--------------------------------
### Neon Community Guides RSS Feed URL
Source: https://neon.com/docs/reference/feeds
Subscribe to the Neon Community Guides RSS feed to receive the latest tips, tutorials, and best practices.
```bash
https://neon.com/guides/rss.xml
```
--------------------------------
### Using psql Meta-commands in Neon SQL Editor
Source: https://neon.com/docs/changelog/2024-04-19
Examples of psql meta-commands that can be used in the Neon SQL Editor for quick database information retrieval. Use `\?` to see supported commands.
```bash
\dt
```
```bash
\d [table_name]
```
```bash
\l
```
```bash
\?
```
```bash
\h [NAME]
```
```bash
\h SELECT
```
--------------------------------
### Set up Neon Database Schema and Table
Source: https://neon.com/docs/guides/postgrest
Creates an 'api' schema, a 'students' table within it, inserts sample data, and configures an 'anonymous' role with read access to the schema.
```sql
CREATE SCHEMA api;
CREATE TABLE api.students (
id SERIAL PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL
);
INSERT INTO api.students (first_name, last_name) VALUES
('Ada', 'Lovelace'),
('Alan', 'Turing');
CREATE ROLE anonymous NOLOGIN;
GRANT anonymous TO neondb_owner;
GRANT USAGE ON SCHEMA api TO anonymous;
GRANT SELECT ON ALL TABLES IN SCHEMA api TO anonymous;
ALTER DEFAULT PRIVILEGES IN SCHEMA api GRANT SELECT ON TABLES TO anonymous;
```
--------------------------------
### Install Prisma Pulse Extension
Source: https://neon.com/docs/guides/logical-replication-prisma-pulse
Install the latest version of the Prisma Pulse extension into your existing TypeScript project. This package enables real-time data streaming from your database.
```bash
npm install @prisma/extension-pulse@latest
```
--------------------------------
### Install Kysely with Neon WebSocket Driver
Source: https://neon.com/docs/guides/kysely
Installs Kysely core, the Neon WebSocket driver, ws, and dotenv. Supports transactions and persistent connections for serverless environments.
```bash
npm install kysely @neondatabase/serverless ws dotenv
npm install -D @types/ws
```
--------------------------------
### Initialize and Add Neon Postgres to Stripe Projects
Source: https://neon.com/docs/changelog/2026-03-27
Use the Stripe CLI to initialize your project, browse available services, and provision a Neon Postgres database.
```bash
stripe projects init my-app
stripe projects catalog
stripe projects add neon/postgres
```
--------------------------------
### Neon Database Connection String Format
Source: https://neon.com/docs/serverless/serverless-driver
Example format for a Neon database connection string, typically assigned to DATABASE_URL environment variable.
```shell
DATABASE_URL=postgresql://[user]:[password]@[neon_hostname]/[dbname]
```
--------------------------------
### Install Kysely with Neon Serverless (HTTP) Driver
Source: https://neon.com/docs/guides/kysely
Installs Kysely core, the Neon HTTP serverless driver, and dotenv for environment variables. Suitable for edge environments.
```bash
npm install kysely kysely-neon @neondatabase/serverless dotenv
```
--------------------------------
### Deploy Site and Function to Netlify
Source: https://neon.com/docs/guides/netlify-functions
Command to deploy the project, including site and functions, to Netlify for production.
```bash
netlify deploy --prod
```
--------------------------------
### TwoColumnLayout with Step and Block
Source: https://neon.com/docs/community/component-guide
Demonstrates a two-column layout for tutorials using Step and Block components. Add `layout: wide` to frontmatter for optimal display. Requires installation of `@neondatabase/neon-js`.
```mdx
Install the required packages.
```bash
npm install @neondatabase/neon-js
```
```
--------------------------------
### Define Neon Project Configuration
Source: https://neon.com/docs/reference/neon-ts
Configure Neon services and branch policies using defineConfig. This example sets up the auth service and defines TTL for non-default branches.
```typescript
import { defineConfig } from "@neondatabase/config/v1";
export default defineConfig({
// Services: what exists on every branch
auth: true,
// Branch policy: per-branch tuning
branch: (branch) => {
if (branch.isDefault) {
// Default branch: no overrides, uses project defaults
return {};
}
if (!branch.exists) {
// New non-default branches: auto-expire
return { ttl: "7d" };
}
// Existing branch: no changes
return {};
},
});
```
--------------------------------
### Connect to Embedded PostgreSQL
Source: https://neon.com/docs/guides/embedded-postgres
Provides an example of how to obtain connection details for a running embedded PostgreSQL instance. Use these details to establish a JDBC connection.
```java
DataSource dataSource = embeddedPostgres.getPostgresDatabase();
```
--------------------------------
### Run Neon CLI without Installation (bunx)
Source: https://neon.com/docs/cli/install
Execute the Neon CLI directly using bunx without a global installation. This is an alternative to npx for bun users.
```shell
bunx neonctl
```
--------------------------------
### Run Neon CLI without Installation (npx)
Source: https://neon.com/docs/cli/install
Execute the Neon CLI directly using npx without a global installation. This is useful for quick commands or testing.
```shell
npx neonctl
```
--------------------------------
### Install pgvector Extension
Source: https://neon.com/docs/ai/ai-google-colab
Installs the pgvector extension in your Neon database, enabling it to store and query vector embeddings. Use this before creating tables that will hold vector data.
```python
# Execute this query to install the pgvector extension
cursor.execute("CREATE EXTENSION IF NOT EXISTS vector;")
```
--------------------------------
### Install Neon Plugin in Claude Code
Source: https://neon.com/docs/ai/ai-claude-code-plugin
Install the Neon plugin using the Claude CLI. This command adds Neon's capabilities to your Claude Code environment.
```bash
claude plugin install neon@claude-plugins-official
```
--------------------------------
### Create Table and Insert Data (Async Rust)
Source: https://neon.com/docs/guides/rust
Utilize the `tokio-postgres` crate for asynchronous database operations. This example mirrors the sync version but uses async/await for non-blocking I/O.
```rust
use tokio_postgres;
use dotenvy::dotenv;
use openssl::ssl::{SslConnector, SslMethod};
use postgres_openssl::MakeTlsConnector;
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box> {
// Load environment variables from .env file
dotenv()?;
let conn_string = env::var("DATABASE_URL")?;
let builder = SslConnector::builder(SslMethod::tls())?;
let connector = MakeTlsConnector::new(builder.build());
let (mut client, connection) = tokio_postgres::connect(&conn_string, connector).await?;
println!("Connection established");
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
client.batch_execute("DROP TABLE IF EXISTS books;").await?;
println!("Finished dropping table (if it existed).");
client.batch_execute(
"CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255),
publication_year INT,
in_stock BOOLEAN DEFAULT TRUE
);"
).await?;
println!("Finished creating table.");
// Insert a single book record
client.execute(
"INSERT INTO books (title, author, publication_year, in_stock) VALUES ($1, $2, $3, $4)",
&[&"The Catcher in the Rye", &"J.D. Salinger", &1951, &true],
).await?;
println!("Inserted a single book.");
// Start a transaction
let transaction = client.transaction().await?;
println!("Starting transaction to insert multiple books...");
// Data to be inserted
let books_to_insert = [
("The Hobbit", "J.R.R. Tolkien", 1937, true),
("1984", "George Orwell", 1949, true),
("Dune", "Frank Herbert", 1965, false),
];
// Loop and insert within the transaction
for book in &books_to_insert {
transaction.execute(
"INSERT INTO books (title, author, publication_year, in_stock) VALUES ($1, $2, $3, $4)",
&[&book.0, &book.1, &book.2, &book.3],
).await?;
}
// Commit the transaction
transaction.commit().await?;
println!("Inserted 3 rows of data.");
Ok(())
}
```
--------------------------------
### Get Connection String, Connect with psql, and Run SQL File
Source: https://neon.com/docs/cli/connection-string
Obtain a connection string, connect via psql, and execute commands from a specified .sql file.
```bash
neonctl connection-string --psql -- -f dump.sql
```
--------------------------------
### Consumption API Response Example (Hourly)
Source: https://neon.com/docs/introduction/network-transfer
Example JSON response structure for hourly network transfer metrics, showing consumption data per project and period.
```json
{
"projects": [
{
"project_id": "delicate-dawn-54854667",
"periods": [
{
"period_id": "90c7f107-3fe7-4652-b1da-c61f71043128",
"period_plan": "launch",
"period_start": "2026-02-02T18:04:52Z",
"consumption": [
{
"timeframe_start": "2026-02-04T00:00:00Z",
"timeframe_end": "2026-02-04T01:00:00Z",
"metrics": [
{
"metric_name": "public_network_transfer_bytes",
"value": 8347291
}
]
},
{
"timeframe_start": "2026-02-04T01:00:00Z",
"timeframe_end": "2026-02-04T02:00:00Z",
"metrics": [
{
"metric_name": "public_network_transfer_bytes",
"value": 1203477
}
]
}
]
}
]
}
],
"pagination": {
"cursor": "delicate-dawn-54854667"
}
}
```
--------------------------------
### Configure Environment Variables
Source: https://neon.com/docs/data-api/demo
Set up the .env file with necessary URLs for the Neon Data API and Neon Auth, as well as the database connection string for migrations.
```env
# Neon Data API URL
# Find this in Neon Console → Data API page → "Data API URL"
VITE_NEON_DATA_API_URL=https://your-project-id.data-api.neon.tech
# Neon Auth Base URL
# Find this in Neon Console → Auth page → "Auth Base URL"
VITE_NEON_AUTH_URL=https://your-project-id.auth.neon.tech
# Database Connection String (for migrations)
# Find this in Neon Console → Dashboard → Connection string (select "Pooled connection")
DATABASE_URL=postgresql://user:password@your-project-id.pooler.region.neon.tech/neondb?sslmode=require
```
--------------------------------
### Create .env File
Source: https://neon.com/docs/guides/auth-clerk
Create a .env file at the root of your project to store sensitive connection parameters for Neon and Clerk.
```bash
touch .env
```
--------------------------------
### List Objects with neonctl
Source: https://neon.com/docs/storage/objects
Demonstrates listing objects using the neonctl command-line tool, with options for folder-collapsed views, prefix filtering, and recursive flat listings.
```APIDOC
## List Objects with neonctl
### Description
Demonstrates listing objects using the neonctl command-line tool, with options for folder-collapsed views, prefix filtering, and recursive flat listings.
### Commands
* **Default (folder-collapsed):** `neonctl bucket object list my-bucket`
* **With prefix:** `neonctl bucket object list my-bucket/images/`
* **Recursive flat listing:** `neonctl bucket object list my-bucket --recursive`
```
--------------------------------
### S3 Upload Response Example
Source: https://neon.com/docs/guides/aws-s3
This is an example of the JSON response you should receive after requesting a presigned URL. It contains the presigned URL, object key, and the public file URL.
```json
{
"success": true,
"presignedUrl": "https://.s3.us-east-1.amazonaws.com/.....&x-id=PutObject",
"objectKey": "",
"publicFileUrl": "https://.s3.us-east-1.amazonaws.com/"
}
```
--------------------------------
### Instantiate Prisma Client with Neon Adapter
Source: https://neon.com/docs/guides/prisma-migrations
Sets up Prisma Client in src/db.ts using the Neon adapter and the pooled DATABASE_URL for application runtime connections.
```typescript
import 'dotenv/config'
import { PrismaClient } from './generated/prisma'
import { PrismaNeon } from '@prisma/adapter-neon'
const adapter = new PrismaNeon({
connectionString: process.env.DATABASE_URL!,
})
export const prisma = new PrismaClient({ adapter })
```
--------------------------------
### Example Application Planets Endpoint Response
Source: https://neon.com/docs/guides/koyeb
This JSON output represents the expected response from the /planets endpoint of the deployed example application, showing a list of planets from the database.
```json
[
{
"id": 1,
"name": "Mercury"
},
{
"id": 2,
"name": "Venus"
},
{
"id": 3,
"name": "Mars"
}
]
```
--------------------------------
### Create, Query, and Delete Postgres Database with Neon Toolkit
Source: https://neon.com/docs/changelog/2024-09-27
Use this snippet to create a new Postgres project, execute SQL queries, and then delete the project. Ensure the API_KEY environment variable is set.
```javascript
import { NeonToolkit } from "@neondatabase/toolkit";
const toolkit = new NeonToolkit(process.env.API_KEY!);
const project = await toolkit.createProject();
await toolkit.sql(
project,
`
CREATE TABLE IF NOT EXISTS
users (
id UUID PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
`,
);
await toolkit.sql(
project,
`
INSERT INTO users (id, name) VALUES (gen_random_uuid(), 'Sam Altman');
`,
);
console.log(
await toolkit.sql(
project,
`
SELECT name FROM users;
`,
),
);
await toolkit.deleteProject(project);
```
--------------------------------
### Create Web Application with API Endpoints
Source: https://neon.com/docs/guides/entity-migrations
Sets up a basic ASP.NET Core web application with Entity Framework and defines API endpoints for fetching authors and books.
```csharp
# Program.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using GuideNeonEF;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext();
var app = builder.Build();
app.UseRouting();
app.MapGet("/authors", async (ApplicationDbContext db) =>
await db.Authors.ToListAsync());
app.MapGet("/books/{authorId}", async (int authorId, ApplicationDbContext db) =>
await db.Books.Where(b => b.AuthorId == authorId).ToListAsync());
app.Run();
```
--------------------------------
### Create hobbies table and insert sample data
Source: https://neon.com/docs/functions/json_extract_path_text
Creates a 'hobbies' table with hobby details and inserts sample data.
```sql
CREATE TABLE hobbies (
hobby_id SERIAL PRIMARY KEY,
hobby_name VARCHAR(255),
difficulty_level VARCHAR(50),
average_cost VARCHAR(50)
);
INSERT INTO hobbies (hobby_name, difficulty_level, average_cost)
VALUES
('Reading', 'Easy', 'Low'),
('Cycling', 'Moderate', 'Medium'),
('Gaming', 'Variable', 'High'),
('Cooking', 'Variable', 'Low');
```
--------------------------------
### Configure Database Connection String
Source: https://neon.com/docs/guides/entity-migrations
Sets up the .env file to store the Neon Postgres connection string, which will be used by the application.
```bash
DATABASE_URL=NEON_POSTGRES_CONNECTION_STRING
```
--------------------------------
### Create New Hono.js Project
Source: https://neon.com/docs/guides/drizzle-migrations
Initializes a new Node.js project using the Hono.js framework. This command sets up the basic project structure and dependencies.
```bash
npm create hono@latest neon-drizzle-guide
```
--------------------------------
### Apply Entity Framework Migrations
Source: https://neon.com/docs/guides/dotnet-entity-framework
Use the .NET CLI to create and apply the initial database migration. This command generates the necessary SQL to create your database schema.
```bash
dotnet ef migrations add InitialCreate
dotnet ef database update
```
--------------------------------
### Configure Neon Auth Middleware
Source: https://neon.com/docs/get-started/full-backend-quickstart
Implement middleware to protect routes and redirect unauthenticated users. This example protects '/posts' routes and redirects to '/auth/sign-in'.
```typescript
import { auth } from '@/lib/auth/server';
export default auth.middleware({
loginUrl: '/auth/sign-in',
});
export const config = {
matcher: ['/posts/:path*'],
};
```
--------------------------------
### Create Book Controller with REST Endpoints
Source: https://neon.com/docs/guides/micronaut-kotlin
Exposes REST endpoints for book management (GET all, GET by ID, POST new). Uses @ExecuteOn for IO-bound tasks.
```kotlin
// src/main/kotlin/com/example/controller/BookController.kt
package com.example.controller
import com.example.entity.Book
import com.example.repository.BookRepository
import io.micronaut.http.annotation.*
import io.micronaut.scheduling.TaskExecutors
import io.micronaut.scheduling.annotation.ExecuteOn
@Controller("/books")
class BookController(private val bookRepository: BookRepository) {
@Get
@ExecuteOn(TaskExecutors.IO)
fun getAll(): List = bookRepository.findAll().toList()
@Get("/{id}")
@ExecuteOn(TaskExecutors.IO)
fun getById(id: Long): Book? = bookRepository.findById(id).orElse(null)
@Post
@ExecuteOn(TaskExecutors.IO)
fun save(@Body book: Book): Book = bookRepository.save(book)
}
```
--------------------------------
### Complete App.jsx Example with Auth Flows
Source: https://neon.com/docs/auth/guides/email-verification
A full React component demonstrating sign-up, sign-in, and email verification using the Neon auth client. It manages user sessions, messages, and the current UI step (authentication or verification).
```jsx
import { useState, useEffect } from 'react';
import { authClient } from './auth';
import './App.css';
export default function App() {
const [session, setSession] = useState(null);
const [user, setUser] = useState(null);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(true);
const [message, setMessage] = useState('');
const [step, setStep] = useState('auth'); // 'auth' or 'verify'
const [code, setCode] = useState('');
const [isSignUp, setIsSignUp] = useState(true);
useEffect(() => {
authClient.getSession().then((result) => {
if (result.data?.session && result.data?.user) {
setSession(result.data.session);
setUser(result.data.user);
}
setLoading(false);
});
}, []);
const handleSignUp = async (e) => {
e.preventDefault();
setMessage('');
const { data, error } = await authClient.signUp.email({
email,
password,
name: email.split('@')[0] || 'User',
});
if (error) {
setMessage(error.message);
return;
}
if (data?.user && !data.user.emailVerified) {
setMessage('Check your email for a verification code');
setStep('verify'); // Switch to verification form
} else {
const sessionResult = await authClient.getSession();
if (sessionResult.data?.session && sessionResult.data?.user) {
setSession(sessionResult.data.session);
setUser(sessionResult.data.user);
}
}
};
const handleSignIn = async (e) => {
e.preventDefault();
setMessage('');
const { data, error } = await authClient.signIn.email({ email, password });
if (error) {
setMessage(error.message);
return;
}
if (data?.session && data?.user) {
setSession(data.session);
setUser(data.user);
}
};
const handleVerify = async (e) => {
e.preventDefault();
setMessage('');
try {
const { data, error } = await authClient.emailOtp.verifyEmail({
email,
otp: code,
});
if (error) throw error;
if (data?.session) {
setSession(data.session);
setUser(data.session.user);
setStep('auth');
} else {
setMessage('Email verified! You can now sign in.');
setStep('auth');
setIsSignUp(false);
setCode('');
}
} catch (error) {
setMessage(error?.message || 'An error occurred');
}
};
const handleSignOut = async () => {
await authClient.signOut();
setSession(null);
setUser(null);
};
if (loading) return
Loading...
;
if (session && user) {
return (
Logged in as {user.email}
);
}
if (step === 'verify') {
return (
{' '}
Verify Your Email
Enter the code sent to {email}
{' '}
{message &&
{message}
}
);
}
return (
{isSignUp ? 'Sign Up' : 'Sign In'}
{message &&
{message}
}
);
}
```
--------------------------------
### Create and Populate products Table
Source: https://neon.com/docs/functions/jsonb_extract_path
Creates a 'products' table with an ID and a JSONB 'attributes' column, then inserts sample data with nested structures.
```sql
CREATE TABLE products (
id INT,
attributes JSONB
);
INSERT INTO products (id, attributes)
VALUES
(1, '{"name": "Laptop", "specs": {"brand": "Dell", "RAM": "16GB", "storage": {"type": "SSD", "capacity": "512GB"}}, "tags": ["pc"]}'),
(2, '{"name": "Smartphone", "specs": {"brand": "Google", "RAM": "8GB", "storage": {"type": "UFS", "capacity": "256GB"}}, "tags": ["android",
"pixel"]'),
(3, '{"name": "Smartphone", "specs": {"brand": "Apple", "RAM": "8GB", "storage": {"type": "UFS", "capacity": "128GB"}}, "tags": ["ios", "iphone"]}');
```
--------------------------------
### Install a Previous Version of pgvector
Source: https://neon.com/docs/extensions/pgvector
Install a specific previous version of the pgvector extension by providing the version number. This is useful if you need compatibility with older applications or specific features.
```sql
CREATE EXTENSION vector VERSION '0.7.4';
```
--------------------------------
### Configure Environment Variables
Source: https://neon.com/docs/guides/cloudinary
Set up your Cloudinary credentials and Neon database connection string in a .env file.
```env
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
DATABASE_URL=your_neon_database_connection_string
```
--------------------------------
### Create and Insert Data for Organizations and Users Tables
Source: https://neon.com/docs/functions/jsonb_array_elements
Sets up the necessary tables and inserts sample data for demonstrating JSONB array processing.
```sql
CREATE TABLE organizations (
id SERIAL PRIMARY KEY,
members JSONB
);
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
);
INSERT INTO organizations (members) VALUES
('[{ "id": 23, "role": "admin" }, { "id": 24, "role": "default" }]'),
('[{ "id": 23, "role": "user" }]'),
('[{ "id": 24, "role": "admin" }, { "id": 25, "role": "default" }]'),
('[{ "id": 25, "role": "user" }]');
INSERT INTO users (id, name, email) VALUES
(23, 'Max', 'max@gmail.com'),
(24, 'Joe', 'joe@gmail.com'),
(25, 'Alice', 'alice@gmail.com');
```
--------------------------------
### Install pg_search Extension
Source: https://neon.com/docs/extensions/pg_search
Use this SQL statement to install the pg_search extension in Neon. Ensure you are connected to your Neon database via the SQL Editor or a client like psql.
```sql
CREATE EXTENSION IF NOT EXISTS pg_search;
```
--------------------------------
### Create Database Utility with postgres.js
Source: https://neon.com/docs/guides/astro
Set up a reusable database client using the postgres.js driver in an Astro project.
```typescript
import postgres from 'postgres';
export const sql = postgres(import.meta.env.DATABASE_URL, { ssl: 'require' });
```
--------------------------------
### Insert Data into an HSTORE Column
Source: https://neon.com/docs/extensions/hstore
Populates the 'product' table with sample data, demonstrating how to insert key-value pairs into the HSTORE 'attributes' column.
```sql
INSERT INTO product (name, attributes)
VALUES
('Desktop', 'brand => HP, price => 900, processor => "Intel Core i5", storage => "1TB HDD"'),
('Tablet', 'brand => Apple, price => 500, os => iOS, screen_size => 10.5'),
('Smartwatch', 'brand => Garmin, price => 250, water_resistant => true, battery_life => "7 days"'),
('Camera', 'brand => Nikon, price => 1200, megapixels => 24, video_resolution => "4K"'),
('Laptop', 'brand => Dell, price => 1200, screen_size => 15.6'),
('Smartphone', 'brand => Samsung, price => 800, os => Android'),
('Headphones', 'brand => Sony, price => 150, wireless => true, color => "Black"');
```
--------------------------------
### Create a Database with SQL
Source: https://neon.com/docs/manage/databases
Use the `CREATE DATABASE` statement to create a new database. Most standard PostgreSQL parameters are supported, except for `TABLESPACE`.
```sql
CREATE DATABASE testdb;
```
--------------------------------
### Preview Branch Naming Convention Example
Source: https://neon.com/docs/get-started/workflow-primer
Recommended naming convention for preview branches in Neon, using prefixes like 'preview/pr--'.
```bash
preview/pr-123-feat/new-login-screen
```
--------------------------------
### Install Neon Agent Skills Globally
Source: https://neon.com/docs/ai/agent-skills
Use this command to install agent skills globally, making them available across all your projects. The `-y` flag automatically confirms prompts.
```bash
npx skills add neondatabase/agent-skills -y -g
```
--------------------------------
### Create New Project with Context
Source: https://neon.com/docs/cli/set-context
Use the `--set-context` flag during project creation to automatically set the context for the new project. This creates a hidden `.neon` file with the project's ID.
```bash
neonctl projects create --name MyLatest --set-context
```
--------------------------------
### Install Agent Skills for Other AI Tools
Source: https://neon.com/docs/ai/ai-claude-code-plugin
Install the Neon Agent Skills for use with AI tools other than Claude Code. This command adds the neon-postgres skill to your agent skills.
```bash
npx skills add neondatabase/agent-skills -s neon-postgres
```
--------------------------------
### Create HNSW Index with Custom Build Options
Source: https://neon.com/docs/extensions/pgvector
This example shows how to create an HNSW index with custom 'm' and 'ef_construction' parameters. Adjust these values to tune index build performance and recall.
```sql
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WITH (m = 16, ef_construction = 64);
```
--------------------------------
### Create and Populate Product Categories Table
Source: https://neon.com/docs/extensions/tablefunc
Sets up a sample table to demonstrate hierarchical data. This table defines categories and their parent-child relationships.
```sql
CREATE TABLE product_categories (
category_id INT PRIMARY KEY,
category_name TEXT,
parent_category_id INT
);
INSERT INTO product_categories (category_id, category_name, parent_category_id) VALUES
(1, 'Electronics', NULL),
(2, 'Computers', 1),
(3, 'Laptops', 2),
(4, 'Desktops', 2),
(5, 'Phones', 1),
(6, 'Smartphones', 5),
(7, 'Books', NULL),
(8, 'Fiction', 7);
```
--------------------------------
### Verify Table Size Reduction After pg_repack
Source: https://neon.com/docs/extensions/pg_repack
Compares table size before and after running pg_repack to confirm bloat removal. This example shows a reduction from 8MB to 4MB.
```text
Schema | Name | Type | Owner | Persistence | Access method | Size | Description
--------+-----------------+-------+--------------+-------------+---------------+----------+-------------
public | bloated_table | table | neondb_owner | permanent | heap | 8192 kB |
(1 row)
```
```text
Schema | Name | Type | Owner | Persistence | Access method | Size | Description
--------+-----------------+-------+--------------+-------------+---------------+----------+-------------
public | bloated_table | table | neondb_owner | permanent | heap | 4096 kB |
(1 row)
```
--------------------------------
### Initialize Grafbase Project
Source: https://neon.com/docs/guides/grafbase
Initialize a new Grafbase project and navigate into its directory.
```bash
npx grafbase init grafbase-neon
cd grafbase-neon
```
--------------------------------
### Create a Neon Project
Source: https://neon.com/docs/workflows/claimable-database-integration
Use the Neon create project API to provision a new project. The minimum request body is project: {} as all settings are optional.
```http
POST https://console.neon.tech/api/v2/projects
```
```bash
curl -X POST 'https://console.neon.tech/api/v2/projects' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {your_api_key_here}' \
--header 'Content-Type: application/json' \
--data '{ \
"project": { \
"name": "new-project-name", \
"region_id": "aws-us-east-1", \
"pg_version": 17, \
"org_id": "org-cool-breeze-12345678" \
} \
}'
```
--------------------------------
### Get Authentication Parameters from Backend
Source: https://neon.com/docs/guides/imagekit
Use this `curl` command to send a GET request to your backend's `/generate-auth-params` endpoint to obtain necessary authentication parameters for uploading files.
```bash
curl -X GET http://localhost:3000/generate-auth-params
```
--------------------------------
### Get Connection String for Time Travel (CLI)
Source: https://neon.com/docs/guides/time-travel-assist
Use this command to get a connection string for a specific branch and timestamp or LSN. This is useful for connecting to a historical state of your database.
```bash
neon connection-string @
```
--------------------------------
### Create Lambda Project Directory
Source: https://neon.com/docs/guides/aws-lambda
Creates a new directory for the Lambda project and navigates into it.
```bash
mkdir neon-lambda
cd neon-lambda
```
--------------------------------
### Install Drizzle and node-postgres Driver
Source: https://neon.com/docs/guides/drizzle
Installs Drizzle ORM, the node-postgres driver, dotenv, and Drizzle Kit. Includes @types/pg for PostgreSQL type definitions. A stable choice for Node.js applications.
```bash
npm install drizzle-orm pg dotenv
npm install -D drizzle-kit @types/pg
```
--------------------------------
### Initialize Next.js Project
Source: https://neon.com/docs/guides/auth-auth0
Creates a new Next.js project with TypeScript, ESLint, Tailwind CSS, npm, and App Router configuration.
```bash
npx create-next-app guide-neon-next-auth0 --typescript --eslint --tailwind --use-npm --no-src-dir --app --import-alias "@/*"
```
--------------------------------
### Install Neon Agent Skills Plugin
Source: https://neon.com/docs/changelog/2026-01-30
Install the Neon agent skills as a Claude Code plugin. This bundles the skills and the Neon MCP Server for natural language database management.
```bash
/plugin marketplace add neondatabase/agent-skills
/plugin install using-neon@neon-agent-skills
```
--------------------------------
### Neon Project Creation Response
Source: https://neon.com/docs/workflows/claimable-database-integration
This is an abbreviated example of the response from the Neon project creation API. It shows key fields like project ID and connection URI.
```json
{
"project": {
"id": "your-project-id",
"name": "new-project-name",
"owner_id": "org-the-owner-id",
"org_id": "org-the-owner-id"
},
"connection_uris": [
{
"connection_uri": "postgresql://neondb_owner:{password}@ep-cool-shape-123456.us-east-1.aws.neon.tech/neondb?sslmode=require&channel_binding=require"
}
],
"branch": {},
"databases": [{}],
"endpoints": [{}],
"operations": [{}],
"roles": [{}]
}
```
--------------------------------
### Connect to Neon using Rust
Source: https://neon.com/docs/get-started/connect-neon
Connect to your Neon database using the `postgres` and `openssl` crates in Rust. This example loads the connection string from a .env file.
```rust
# Rust example
use postgres::Client;
use openssl::ssl::{SslConnector, SslMethod};
use postgres_openssl::MakeTlsConnector;
use std::error;
use std::env;
use dotenv::dotenv;
fn main() -> Result<(), Box> {
// Load environment variables from .env file
dotenv().ok();
// Get the connection string from the environment variable
let conn_str = env::var("DATABASE_URL")?;
let builder = SslConnector::builder(SslMethod::tls())?;
let connector = MakeTlsConnector::new(builder.build());
let mut client = Client::connect(&conn_str, connector)?;
for row in client.query("select version()", &[])? {
let ret: String = row.get(0);
println!("Result = {}", ret);
}
Ok(())
}
```
--------------------------------
### Install Specific Neon Agent Skill
Source: https://neon.com/docs/ai/agent-skills
Install a specific skill, such as 'neon-postgres', by using the `-s` flag. Repeat the flag for multiple skills. The `-y` flag bypasses interactive prompts.
```bash
npx skills add neondatabase/agent-skills -s neon-postgres -y
```
--------------------------------
### Neon Audit Log Record Example
Source: https://neon.com/docs/security/hipaa
An example of a raw audit log record generated by Neon for a CREATE SCHEMA command. It includes various metadata about the execution context and the command itself.
```ini
2025-05-05 20:23:01.277 <134>May 6 00:23:01 vm-compute-shy-waterfall-w2cn1o3t-b6vmn young-recipe-29421150/ep-calm-da 2025-05-06 00:23:01.277 GMT,neondb_owner,neondb,1405,10.6.42.155:13702,68195665.57d,1,CREATE SCHEMA, 2025-05-06 00:23:01 GMT,16/2,767,00000,SESSION,1,1,DDL,CREATE SCHEMA,,,CREATE SCHEMA IF NOT EXISTS healthcare,,,,,,,,,,neon-internal-sql-editor
```
--------------------------------
### Neon Hyperdrive connection string example
Source: https://neon.com/docs/guides/cloudflare-workers
Example of a direct connection string for Neon, intended for use with Cloudflare Hyperdrive. Ensure 'Pooled connection' is unchecked when generating this string in Neon.
```bash
postgres://hyperdrive-user:PASSWORD@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname
```
--------------------------------
### Get all size and color combinations for a product
Source: https://neon.com/docs/functions/json_array_elements
Demonstrates using nested json_array_elements() calls to generate all combinations of sizes and colors for a specific product from its JSON details.
```sql
SELECT
id,
name,
size,
color
FROM products AS p,
json_array_elements(p.details -> 'sizes') AS size,
json_array_elements(p.details -> 'colors') AS color
WHERE name = 'T-Shirt';
```
--------------------------------
### Admonition Component Example
Source: https://neon.com/docs/community/component-guide
Use the Admonition component to display callouts for notes, warnings, tips, info, and coming soon messages. This example shows a 'warning' type with a custom title.
```mdx
Critical information requiring immediate attention.
```
--------------------------------
### Configure Neon Database Connection String
Source: https://neon.com/docs/guides/sqlalchemy-migrations
Sets up the DATABASE_URL environment variable in a .env file using the direct Neon Postgres connection string.
```bash
# .env
DATABASE_URL=NEON_POSTGRES_CONNECTION_STRING
```
--------------------------------
### Run pgloader migration command
Source: https://neon.com/docs/import/migrate-from-planetscale
Initiate the database migration from PlanetScale to Neon using the pgloader command-line tool. Ensure you have the 'planetscale_to_neon.load' configuration file ready.
```shell
pgloader planetscale_to_neon.load
```
--------------------------------
### Install Drizzle and Neon WebSocket Driver
Source: https://neon.com/docs/guides/drizzle
Installs Drizzle ORM, the Neon WebSocket driver, dotenv, and Drizzle Kit. Includes @types/ws for WebSocket type definitions. Recommended for long-running applications.
```bash
npm install drizzle-orm @neondatabase/serverless ws dotenv
npm install -D drizzle-kit @types/ws
```
--------------------------------
### Install Latest Neon CLI in GitHub Actions
Source: https://neon.com/docs/changelog/2024-12-20
Install the latest Neon CLI version in a GitHub Actions workflow using npm. This ensures you are using the most up-to-date version for CI/CD processes.
```yaml
- name: Install Neon CLI
run: npm install -g neonctl@latest
```
--------------------------------
### Create Project and Set Context
Source: https://neon.com/docs/cli/projects
Use the --set-context flag to create a new project and automatically configure the Neon CLI to use this project as the current context.
```bash
neonctl projects create --set-context
```
--------------------------------
### Install Neon Plugin within Claude Code
Source: https://neon.com/docs/ai/ai-claude-code-plugin
Alternatively, install the Neon plugin directly from within a Claude Code session. This is a convenient way to add the plugin without leaving the IDE.
```text
/plugin install neon@claude-plugins-official
```
--------------------------------
### Auth0 JWKS URL Example
Source: https://neon.com/docs/data-api/custom-authentication-providers
This example shows how to construct the JWKS URL for Auth0 by replacing the placeholder with your actual Auth0 domain. This URL is used to fetch public keys for verifying JWTs.
```bash
https://{YOUR_AUTH0_DOMAIN}/.well-known/jwks.json
```
```bash
https://dev-abc123.us.auth0.com/.well-known/jwks.json
```
--------------------------------
### Install Neon Plugin in Cursor
Source: https://neon.com/docs/ai/agent-skills
Install the Neon plugin within Cursor chat to bundle core Postgres skills and the Neon MCP Server. This provides enhanced integration for AI coding assistance.
```text
/add-plugin neon-postgres
```
--------------------------------
### Isolated Environments Example
Source: https://neon.com/docs/auth/branching-authentication
Demonstrates the operational independence of production and preview branches after branching. This includes separate user data, session management, configuration settings, and unique Auth API endpoints.
```text
Production Branch Preview Branch
├── New user: alice@co.com ├── New user: test@co.com
├── Alice's sessions ├── Test user's sessions
├── Config: email with links ├── Config: testing email codes
└── ep-abc123.neonauth... └── ep-xyz789.neonauth...
(production endpoint) (preview endpoint)
```
--------------------------------
### Initialize Git Repository and Configure Ignore Files
Source: https://neon.com/docs/guides/heroku
Initialize a new Git repository in your project folder. Configures .gitignore to exclude node_modules and .env files, and sets the main branch to 'main'.
```bash
git init && echo "node_modules" > .gitignore && echo ".env" >> .gitignore
git branch -m main
git add . && git commit -m "Initial commit"
```
--------------------------------
### Neon API Audit Log Record Example
Source: https://neon.com/docs/security/hipaa
This is an example of a raw audit log record generated by Neon for a 'List project branches' operation. It shows the structure and fields captured for API events.
```ini
fb7c2e2f-cb09-4405-b543-dbe1b88614b6 2025-05-25 10:18:45.340 +0000 `{ "changes": [], "sync_id": 57949 }` e640c32c-0387-4fc2-8ca5-f823f7ebc4b6 GET `{}` /projects/misty-breeze-49601234/branches a92b3088-7f92-4871-bf91-0aac64edc4b6 b8c58a4b-0a33-4d54-987e-4155e95a64b6 2025-05-24 15:42:39.088 +0000 misty-breeze-49601234 keycloak 200 `{}` ListProjectBranches 0
```
--------------------------------
### Claimable Postgres API Response Example
Source: https://neon.com/docs/reference/claimable-postgres
This JSON object details the newly provisioned database, including its ID, status, connection string, and a URL to claim it to a Neon account.
```json
{
"id": "01abc123-def4-5678-9abc-def012345678",
"status": "UNCLAIMED",
"neon_project_id": "cool-breeze-12345678",
"connection_string": "postgresql://neondb_owner:npg_xxxx@ep-cool-breeze-pooler...",
"claim_url": "https://neon.new/claim/01abc123-def4-5678-9abc-def012345678",
"expires_at": "2026-02-01T12:00:00.000Z",
"created_at": "2026-01-29T12:00:00.000Z",
"updated_at": "2026-01-29T12:00:00.000Z"
}
```
--------------------------------
### Example API Response for Role Creation
Source: https://neon.com/docs/guides/logical-replication-clickhouse
This is an example of the JSON response received after creating a role via the Neon API. The 'password' field within the 'role' object is crucial for configuring your ClickPipes connection.
```json
{
"role": {
"branch_id": "br-spring-base-aqftsqpm",
"name": "replication_user",
"password": "your_password",
"protected": false,
"authentication_method": "password",
"created_at": "2026-05-08T06:20:28Z",
"updated_at": "2026-05-08T06:20:28Z"
},
"operations": [
{
"id": "0390cd9d-7e69-4bb5-b06c-2b88371d1d55",
"project_id": "holy-heart-14531142",
"branch_id": "br-spring-base-aqftsqpm",
"endpoint_id": "ep-autumn-glitter-aqi3gmt4",
"action": "apply_config",
"status": "running",
"failures_count": 0,
"created_at": "2026-05-08T06:20:28Z",
"updated_at": "2026-05-08T06:20:28Z",
"total_duration_ms": 0
}
]
}
```
--------------------------------
### Insert sample data into plant_care_log
Source: https://neon.com/docs/guides/railway
SQL command to insert sample plant care records into the created table.
```sql
INSERT INTO plant_care_log (plant_name, care_date)
VALUES
('Monstera', '2024-01-10'),
('Fiddle Leaf Fig', '2024-01-15'),
('Snake Plant', '2024-01-20'),
('Spider Plant', '2024-01-25'),
('Pothos', '2024-01-30');
```
--------------------------------
### Turso Serverless Data Insertion and Querying
Source: https://neon.com/docs/import/migrate-from-turso
Demonstrates data insertion and querying using prepared statements with the Turso serverless client.
```javascript
// Inserting data
const insertUser = db.prepare("INSERT INTO users (username) VALUES (?)");
await insertUser.run("alice");
// Querying data
const stmt = db.prepare("SELECT * FROM users");
const users = await stmt.all();
```
--------------------------------
### Extract Numeric Part of User ID
Source: https://neon.com/docs/functions/substring
Extracts the numeric part of a user ID string starting from the 6th character. Use when the desired substring starts at a known position and extends to the end of the string.
```sql
WITH users AS (
SELECT 'user_123' AS user_id
UNION ALL
SELECT 'user_482892' AS user_id
)
SELECT substring(user_id from 6) AS numeric_id
FROM users;
```
--------------------------------
### View Branches using Neon API
Source: https://neon.com/docs/manage/branches
This example shows how to list all branches within a Neon project using the Neon API. Replace $NEON_PROJECT_ID and $NEON_API_KEY with your actual project ID and API key.
```bash
curl --request GET \
--url https://console.neon.tech/api/v2/projects/$NEON_PROJECT_ID/branches \
--header "Authorization: Bearer $NEON_API_KEY" \
--header "accept: application/json"
```
--------------------------------
### Create a bucket using Boto3 for Python
Source: https://neon.com/docs/storage/buckets
Create a bucket using the Boto3 library in Python. Environment variables for region, endpoint, and AWS credentials must be configured.
```python
import boto3, os
client = boto3.client(
's3',
region_name=os.environ['AWS_REGION'],
endpoint_url=os.environ['AWS_ENDPOINT_URL_S3'],
aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'],
)
client.create_bucket(Bucket='my-bucket')
```
--------------------------------
### Create Lakebase Search Extensions
Source: https://neon.com/docs/changelog/2026-06-26
Install the `lakebase_vector` and `lakebase_text` extensions to enable vector and keyword search capabilities within Postgres. Ensure shared preload libraries are enabled and compute is restarted prior to installation.
```sql
CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
CREATE EXTENSION IF NOT EXISTS lakebase_text CASCADE;
```
--------------------------------
### Create Database Utility with Neon Serverless Driver
Source: https://neon.com/docs/guides/astro
Set up a reusable database client using the Neon serverless driver in an Astro project.
```typescript
import { neon } from '@neondatabase/serverless';
export const sql = neon(import.meta.env.DATABASE_URL);
```
--------------------------------
### PostgreSQL Index Creation and Management
Source: https://neon.com/docs/postgresql/query-reference
Examples for creating various types of indexes, including basic, unique, composite, partial, expression-based, GIN, and concurrent indexes, as well as dropping and reindexing.
```sql
-- Create a basic index on a single column
CREATE INDEX idx_user_email ON users(email);
-- Create a unique index to enforce uniqueness and improve lookup performance
CREATE UNIQUE INDEX idx_unique_username ON users(username);
-- Create a composite index on multiple columns
CREATE INDEX idx_name_date ON events(name, event_date);
-- Create a partial index for a subset of rows that meet a certain condition
CREATE INDEX idx_active_users ON users(email) WHERE active = TRUE;
-- Create an index on an expression (function-based index)
CREATE INDEX idx_lower_email ON users(LOWER(email));
-- Drop an index
DROP INDEX idx_user_email;
-- Create a GIN index on a jsonb column to improve search performance on keys or values within the JSON document
CREATE INDEX idx_user_preferences ON users USING GIN (preferences);
-- Reindex an existing index to rebuild it, useful for improving index performance or reducing physical size
REINDEX INDEX idx_user_email;
-- Create a CONCURRENTLY index, which allows the database to be accessed normally during the indexing operation
CREATE INDEX CONCURRENTLY idx_concurrent_email ON users(email);
```
--------------------------------
### Install Python Postgres Libraries
Source: https://neon.com/docs/guides/python
Installs the necessary Python libraries for connecting to Neon Postgres: psycopg (v3), psycopg2-binary (legacy), asyncpg (asyncio), and python-dotenv for environment variables. Choose the library that best fits your project's needs.
```bash
pip install "psycopg[binary]" psycopg2-binary asyncpg python-dotenv
```
--------------------------------
### Query Data API with Direct HTTP GET Request
Source: https://neon.com/docs/data-api/get-started
Perform a SELECT query on the Data API using a direct HTTP GET request. Include your JWT token in the Authorization header. Ensure the token has a `sub` claim for RLS.
```bash
curl -X GET 'https://your-data-api-endpoint/rest/v1/posts?is_published=eq.true&order=created_at.desc' \
-H 'Authorization: Bearer YOUR_JWT_TOKEN' \
-H 'Content-Type: application/json'
```
--------------------------------
### Schema Diff GitHub Action Example
Source: https://neon.com/docs/changelog/2024-11-29
This diff shows an example of a schema change detected by the Schema Diff GitHub Action, highlighting the addition of a 'deleted_at' column and adjustments to migration table defaults. It is useful for reviewing database schema modifications in pull requests.
```diff
Index: neondb-schema.sql
===================================================================
--- neondb-schema.sql Branch main
+++ neondb-schema.sql Branch preview/pr-9-feat/add-soft-delete
@@ -111,9 +111,10 @@
title text NOT NULL,
content text NOT NULL,
user_id integer NOT NULL,
created_at timestamp without time zone DEFAULT now() NOT NULL,
- updated_at timestamp without time zone DEFAULT now() NOT NULL
+ updated_at timestamp without time zone DEFAULT now() NOT NULL,
+ deleted_at timestamp without time zone
);
ALTER TABLE public.posts OWNER TO neondb_owner;
@@ -180,5 +181,5 @@
--
-- Name: __drizzle_migrations id; Type: DEFAULT; Schema: drizzle; Owner: neondb_owner
--
-ALTER TABLE ONLY drizzle.__drizzle_migrations ALTER COLUMN id SET DEFAULT nextval('drizzle.__drizzle_m
\ No newline at end of file
+ALTER TABLE ONLY drizzle.__drizzle_migrations ALTER COLUMN
\ No newline at end of file
```
--------------------------------
### Full-Stack JavaScript Example for S3 Uploads with Neon
Source: https://neon.com/docs/guides/aws-s3
A complete Hono application demonstrating the presigned URL generation and metadata saving workflow. It includes S3 client initialization, Neon connection, and two API endpoints: `/presign-upload` and `/save-metadata`. Replace the placeholder authentication middleware with your actual user authentication logic.
```javascript
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { neon } from '@neondatabase/serverless';
import 'dotenv/config';
import { randomUUID } from 'crypto';
const S3_BUCKET = process.env.S3_BUCKET_NAME;
const AWS_REGION = process.env.AWS_REGION;
const s3 = new S3Client({
region: AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});
const sql = neon(process.env.DATABASE_URL);
const app = new Hono();
// Replace this with your actual user authentication logic, by validating JWTs/Headers, etc.
const authMiddleware = async (c, next) => {
c.set('userId', 'user_123');
await next();
};
// 1. Generate Presigned URL for Upload
app.post('/presign-upload', authMiddleware, async (c) => {
try {
const { fileName, contentType } = await c.req.json();
if (!fileName || !contentType) throw new Error('fileName and contentType required');
const objectKey = `${randomUUID()}-${fileName}`;
const publicFileUrl = `https://${S3_BUCKET}.s3.${AWS_REGION}.amazonaws.com/${objectKey}`;
const command = new PutObjectCommand({
Bucket: S3_BUCKET,
Key: objectKey,
ContentType: contentType,
});
const presignedUrl = await getSignedUrl(s3, command, { expiresIn: 300 });
return c.json({ success: true, presignedUrl, objectKey, publicFileUrl });
} catch (error) {
console.error('Presign Error:', error.message);
return c.json({ success: false, error: 'Failed to prepare upload' }, 500);
}
});
// 2. Save Metadata after Client Upload Confirmation
app.post('/save-metadata', authMiddleware, async (c) => {
try {
const { objectKey, publicFileUrl } = await c.req.json();
const userId = c.get('userId');
if (!objectKey) throw new Error('objectKey required');
await sql`
INSERT INTO s3_files (object_key, file_url, user_id)
VALUES (${objectKey}, ${publicFileUrl}, ${userId})
`;
console.log(`Metadata saved for S3 object: ${objectKey}`);
return c.json({ success: true });
} catch (error) {
console.error('Metadata Save Error:', error.message);
return c.json({ success: false, error: 'Failed to save metadata' }, 500);
}
});
const port = 3000;
serve({ fetch: app.fetch, port }, (info) => {
console.log(`Server running at http://localhost:${info.port}`);
});
```
--------------------------------
### Seed Database with Initial Data
Source: https://neon.com/docs/guides/rails-migrations
Populate the database with sample authors and books using a Ruby script. The script uses find_or_create_by to prevent data duplication.
```ruby
# db/seeds.rb
# Find or create authors
authors_data = [
{
name: "J.R.R. Tolkien",
bio: "The creator of Middle-earth and author of The Lord of the Rings."
},
{
name: "George R.R. Martin",
bio: "The author of the epic fantasy series A Song of Ice and Fire."
},
{
name: "J.K. Rowling",
bio: "The creator of the Harry Potter series."
}
]
authors_data.each do |author_attrs|
Author.find_or_create_by(name: author_attrs[:name]) do |author|
author.bio = author_attrs[:bio]
end
end
# Find or create books
books_data = [
{ title: "The Fellowship of the Ring", author_name: "J.R.R. Tolkien" },
{ title: "The Two Towers", author_name: "J.R.R. Tolkien" },
{ title: "The Return of the King", author_name: "J.R.R. Tolkien" },
{ title: "A Game of Thrones", author_name: "George R.R. Martin" },
{ title: "A Clash of Kings", author_name: "George R.R. Martin" },
{ title: "Harry Potter and the Philosopher's Stone", author_name: "J.K. Rowling" },
{ title: "Harry Potter and the Chamber of Secrets", author_name: "J.K. Rowling" }
]
books_data.each do |book_attrs|
author = Author.find_by(name: book_attrs[:author_name])
Book.find_or_create_by(title: book_attrs[:title], author: author)
end
```
--------------------------------
### Admonition with Title Example
Source: https://neon.com/docs/community/contribution-guide
Demonstrates how to add a custom title to an admonition.
```markdown
This is a very important note.
```
--------------------------------
### Paginate Books with First and After
Source: https://neon.com/docs/extensions/pg_graphql
Fetches a single book using 'first: 1' and demonstrates how to use the 'cursor' for subsequent pagination with the 'after' argument.
```sql
SELECT graphql.resolve($$
query PaginateBooks {
bookCollection(first: 1) { # Get the first book
edges {
cursor # Use this cursor for the 'after' argument next time
node {
title
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
$$);
```
--------------------------------
### Get organization details
Source: https://neon.com/docs/changelog/2024-11-08
Retrieves details for a specific organization in Neon.
```APIDOC
## GET /organizations/{organizationId}
### Description
Retrieves details for a specific organization in Neon.
### Method
GET
### Endpoint
/organizations/{organizationId}
### Parameters
#### Path Parameters
- **organizationId** (string) - Required - The unique identifier of the organization.
```
--------------------------------
### Connect, Create Table, and Insert Data with asyncpg
Source: https://neon.com/docs/guides/python
This Python script connects to a Neon database using a connection string from a .env file. It then proceeds to drop an existing 'books' table, create a new one, and insert both single and multiple records using parameterized queries.
```python
from dotenv import load_dotenv
import os
import asyncio
import asyncpg
load_dotenv()
async def run():
conn_string = os.getenv("DATABASE_URL")
conn = None
try:
conn = await asyncpg.connect(conn_string)
print("Connection established")
await conn.execute("DROP TABLE IF EXISTS books;")
print("Finished dropping table (if it existed).")
await conn.execute("""
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255),
publication_year INT,
in_stock BOOLEAN DEFAULT TRUE
);
""")
print("Finished creating table.")
await conn.execute(
"INSERT INTO books (title, author, publication_year, in_stock) VALUES ($1, $2, $3, $4);",
"The Catcher in the Rye",
"J.D. Salinger",
1951,
True,
)
print("Inserted a single book.")
books_to_insert = [
("The Hobbit", "J.R.R. Tolkien", 1937, True),
("1984", "George Orwell", 1949, True),
("Dune", "Frank Herbert", 1965, False),
]
await conn.executemany(
"INSERT INTO books (title, author, publication_year, in_stock) VALUES ($1, $2, $3, $4);",
books_to_insert,
)
print("Inserted 3 rows of data.")
except Exception as e:
print("Connection failed.")
print(e)
finally:
if conn:
await conn.close()
asyncio.run(run())
```
--------------------------------
### Create and Populate books Table
Source: https://neon.com/docs/functions/jsonb_extract_path
Creates a 'books' table with an ID and a JSONB 'info' column, then inserts sample data.
```sql
CREATE TABLE books (
id INT,
info JSONB
);
INSERT INTO books (id, info)
VALUES
(1, '{"title": "The Catcher in the Rye", "author": "J.D. Salinger", "year": 1951}'),
(2, '{"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960}'),
(3, '{"title": "1984", "author": "George Orwell", "year": 1949}');
```
--------------------------------
### Create Sign Up Action
Source: https://neon.com/docs/auth/quick-start/nextjs-api-only
This server action handles user sign-up using email and password. It includes optional logic to restrict sign-ups based on email domains and redirects to the homepage upon successful creation.
```typescript
'use server';
import { auth } from '@/lib/auth/server';
import { redirect } from 'next/navigation';
export async function signUpWithEmail(
_prevState: { error: string } | null,
formData: FormData
) {
const email = formData.get('email') as string;
if (!email) {
return { error: "Email address must be provided." }
}
// Optionally restrict sign ups based on email address
// if (!email.trim().endsWith("@my-company.com")) {
// return { error: 'Email must be from my-company.com' };
// }
const { error } = await auth.signUp.email({
email,
name: formData.get('name') as string,
password: formData.get('password') as string,
});
if (error) {
return { error: error.message || 'Failed to create account' };
}
redirect('/');
}
```
--------------------------------
### Create ASP.NET Core Web API Project
Source: https://neon.com/docs/guides/dotnet-entity-framework
Use this command to create a new ASP.NET Core Web API project and navigate into its directory.
```bash
dotnet new webapi -n NeonEfExample
cd NeonEfExample
```
--------------------------------
### Install TimescaleDB Extension
Source: https://neon.com/docs/changelog/2026-02-27
Enable the TimescaleDB extension on a PostgreSQL 18 database.
```sql
CREATE EXTENSION timescaledb;
```
--------------------------------
### Initialize Alembic Migrations
Source: https://neon.com/docs/guides/sqlalchemy-migrations
Initializes Alembic in the project to manage database migrations. Creates an 'alembic' directory with necessary configuration files.
```bash
alembic init alembic
```
--------------------------------
### Output of Deleting a Function
Source: https://neon.com/docs/cli/functions
This is an example of the output you can expect after successfully deleting a function.
```text
INFO: Function hello deleted from branch br-cool-darkness-123456
```
--------------------------------
### Create and Insert Developer Data
Source: https://neon.com/docs/functions/jsonb_array_elements
Sets up a 'developers' table and populates it with sample data, including a JSONB column for skills.
```sql
CREATE TABLE developers (
id INT PRIMARY KEY,
name TEXT,
skills JSONB
);
INSERT INTO developers (id, name, skills) VALUES
(1, 'Alice', '["Java", "Python", "SQL"]'),
(2, 'Bob', '["C++", "JavaScript"]'),
(3, 'Charlie', '["HTML", "CSS", "React"]);
```
--------------------------------
### Start Anonymization
Source: https://neon.com/docs/workflows/data-anonymization
Initiates the data anonymization process for a specified project and branch.
```APIDOC
## POST /projects/{project_id}/branches/{branch_id}/anonymize
### Description
Initiates the data anonymization process for a specified project and branch.
### Method
POST
### Endpoint
/projects/{project_id}/branches/{branch_id}/anonymize
### Parameters
#### Path Parameters
- **project_id** (string) - Required - The ID of the project.
- **branch_id** (string) - Required - The ID of the branch.
```
--------------------------------
### Create and Insert Data into Neon Database Table
Source: https://neon.com/docs/guides/heroku
Initializes a 'music_albums' table and inserts sample data. This is the first step in setting up your Neon database for the application.
```sql
CREATE TABLE music_albums (
album_id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
artist VARCHAR(255) NOT NULL
);
INSERT INTO music_albums (title, artist)
VALUES
('Rumours', 'Fleetwood Mac'),
('Abbey Road', 'The Beatles'),
('Dark Side of the Moon', 'Pink Floyd'),
('Thriller', 'Michael Jackson');
```
--------------------------------
### Add Neon Serverless Driver Dependency
Source: https://neon.com/docs/guides/bun
Installs the @neondatabase/serverless driver for your Bun project.
```shell
bun add @neondatabase/serverless
```
--------------------------------
### Create and Populate Table
Source: https://neon.com/docs/extensions/pg_prewarm
Creates a table named 't_test' and populates it with one million rows.
```sql
CREATE TABLE t_test AS
SELECT * FROM generate_series(1, 1000000) AS id;
```
--------------------------------
### Deploy Function with Environment Variable
Source: https://neon.com/docs/compute/functions/deploy
Deploy a function named 'hello' from the current directory and set the 'RESEND_API_KEY' environment variable.
```bash
neonctl functions deploy hello --src . --env RESEND_API_KEY=re_...
```
--------------------------------
### Scaffold project into a specific directory
Source: https://neon.com/docs/cli/bootstrap
Creates a new project in the './my-app' directory using an interactively chosen template.
```bash
neonctl bootstrap my-app
```
--------------------------------
### GraphQL Delete Response
Source: https://neon.com/docs/extensions/pg_graphql
Example JSON response after deleting a record using `deleteFromBookCollection`.
```json
{
"data": {
"deleteFromBookCollection": {
"records": [{ "id": 1, "title": "The Great Gatsby (Revised Edition)" }],
"affectedCount": 1
}
}
}
```
--------------------------------
### Run Neon CLI Binary (macOS)
Source: https://neon.com/docs/cli/install
Execute the Neon CLI after downloading the macOS binary. Replace `` and `[options]` with your desired arguments.
```bash
neonctl [options]
```
--------------------------------
### GraphQL Update Response
Source: https://neon.com/docs/extensions/pg_graphql
Example JSON response after updating a record using `updateBookCollection`.
```json
{
"data": {
"updateBookCollection": {
"records": [{ "id": 1, "title": "The Great Gatsby (Revised Edition)" }],
"affectedCount": 1
}
}
}
```
--------------------------------
### Configuration for createNeonAuth
Source: https://neon.com/docs/auth/migrate/from-auth-v0.1
Example of configuring `createNeonAuth` with essential options like `baseUrl` and `cookies.secret`.
```typescript
import { createNeonAuth } from '@neondatabase/auth/next/server';
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: {
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
},
});
```
--------------------------------
### Get masking rules
Source: https://neon.com/docs/workflows/data-anonymization-api
Retrieves all masking rules defined for the specified anonymized branch.
```APIDOC
## GET /projects/{project_id}/branches/{branch_id}/masking_rules
### Description
Retrieves all masking rules defined for the specified anonymized branch.
### Method
GET
### Endpoint
/projects/{project_id}/branches/{branch_id}/masking_rules
### Parameters
#### Path Parameters
- **project_id** (string) - Required - The ID of the project.
- **branch_id** (string) - Required - The ID of the branch.
### Response
#### Success Response (200)
- **masking_rules** (array) - A list of masking rules.
- **database_name** (string) - The name of the database.
- **schema_name** (string) - The name of the schema.
- **table_name** (string) - The name of the table.
- **column_name** (string) - The name of the column.
- **masking_function** (string) - The masking function to apply.
### Response Example
{
"masking_rules": [
{
"database_name": "neondb",
"schema_name": "public",
"table_name": "users",
"column_name": "age",
"masking_function": "anon.random_int_between(25,65)"
},
{
"database_name": "neondb",
"schema_name": "public",
"table_name": "users",
"column_name": "email",
"masking_function": "anon.dummy_free_email()"
}
]
}
```
--------------------------------
### Get member details
Source: https://neon.com/docs/manage/orgs-api
Retrieves information about a specific member using their member ID.
```APIDOC
## GET /organizations/{org_id}/members/{member_id}
### Description
Retrieves information about a specific member using their member ID.
### Method
GET
### Endpoint
/organizations/{org_id}/members/{member_id}
### Parameters
#### Path Parameters
- **org_id** (string) - Required - The organization ID.
- **member_id** (string) - Required - The member ID.
### Response
#### Success Response (200)
- **id** (string) - Member ID.
- **user_id** (string) - User ID.
- **org_id** (string) - Organization ID.
- **role** (string) - Organization role.
- **joined_at** (string) - Join date.
```
--------------------------------
### Get organization invitation details
Source: https://neon.com/docs/changelog/2024-11-08
Retrieves details for a specific invitation within an organization.
```APIDOC
## GET /organizations/{organizationId}/invitations/{invitationId}
### Description
Retrieves details for a specific invitation within an organization.
### Method
GET
### Endpoint
/organizations/{organizationId}/invitations/{invitationId}
### Parameters
#### Path Parameters
- **organizationId** (string) - Required - The unique identifier of the organization.
- **invitationId** (string) - Required - The unique identifier of the invitation.
```
--------------------------------
### Get organization members
Source: https://neon.com/docs/changelog/2024-11-08
Retrieves a list of members associated with a specific organization in Neon.
```APIDOC
## GET /organizations/{organizationId}/members
### Description
Retrieves a list of members associated with a specific organization in Neon.
### Method
GET
### Endpoint
/organizations/{organizationId}/members
### Parameters
#### Path Parameters
- **organizationId** (string) - Required - The unique identifier of the organization.
```
--------------------------------
### Get Specific Invitation Details
Source: https://neon.com/docs/auth/guides/plugins/organization
Retrieves details of a specific invitation using its ID.
```typescript
const { data, error } = await authClient.organization.getInvitation({
query: {
id: 'invitation-id',
},
});
```
--------------------------------
### Get Webhook Configuration
Source: https://neon.com/docs/auth/guides/webhooks
Retrieves the current webhook configuration for a specific project and branch.
```APIDOC
## GET /projects/{project_id}/branches/{branch_id}/auth/webhooks
### Description
Retrieves the current webhook configuration for a specific project and branch.
### Method
GET
### Endpoint
/projects/{project_id}/branches/{branch_id}/auth/webhooks
### Response
#### Success Response (200)
- **enabled** (boolean) - Indicates if webhooks are enabled.
- **webhook_url** (string) - The configured HTTPS webhook URL.
- **enabled_events** (string[]) - The list of event types for which webhooks are enabled.
- **timeout_seconds** (integer) - The configured per-attempt timeout in seconds.
#### Response Example
```json
{
"enabled": true,
"webhook_url": "https://your-app.com/webhooks/neon-auth",
"enabled_events": [
"send.otp",
"send.magic_link",
"user.before_create",
"user.created",
"phone_number.verified"
],
"timeout_seconds": 5
}
```
```
--------------------------------
### Create a new database with neon-new CLI
Source: https://neon.com/docs/reference/claimable-postgres
Use the neon-new CLI to create a new database. This command writes connection credentials to your .env file.
```bash
npx neon-new
```
```bash
yarn dlx neon-new
```
```bash
pnpm dlx neon-new
```
```bash
bunx neon-new
```
```bash
deno run -A neon-new
```
--------------------------------
### Get Auth Configuration
Source: https://neon.com/docs/auth/guides/manage-auth-api
Retrieve the current Neon Auth configuration for a specific branch.
```APIDOC
## Get Auth Configuration
### Description
Retrieve the current Neon Auth configuration for a branch.
### Method
GET
### Endpoint
`/api/v2/projects/{project_id}/branches/{branch_id}/auth`
### Parameters
#### Path Parameters
- **project_id** (string) - Required - The ID of the Neon project.
- **branch_id** (string) - Required - The ID of the branch.
### Response
#### Success Response (200 OK)
- **auth_provider** (string) - The authentication provider used.
- **auth_provider_project_id** (string) - The project ID for the authentication provider.
- **branch_id** (string) - The ID of the branch.
- **db_name** (string) - The name of the database.
- **created_at** (string) - The timestamp when the configuration was created.
- **owned_by** (string) - The owner of the configuration.
- **jwks_url** (string) - The URL for JSON Web Key Set.
- **base_url** (string) - The base URL for the authentication service.
- **name** (string) - The application name.
### Response Example
```json
{
"auth_provider": "better_auth",
"auth_provider_project_id": "cab6949a-10e3-4d25-a879-512beed281e3",
"branch_id": "br-example-abc123",
"db_name": "neondb",
"created_at": "2026-02-26T04:29:05Z",
"owned_by": "neon",
"jwks_url": "https://ep-example.neonauth.us-east-1.aws.neon.tech/neondb/auth/.well-known/jwks.json",
"base_url": "https://ep-example.neonauth.us-east-1.aws.neon.tech/neondb/auth",
"name": "My App"
}
```
```
--------------------------------
### Array Size Enforcement Example
Source: https://neon.com/docs/data-types/array
Demonstrates that Postgres does not enforce defined array sizes during insertion.
```sql
CREATE TABLE test_size (
id SERIAL PRIMARY KEY,
arr1 INTEGER[3]
);
INSERT INTO test_size (arr1)
VALUES (ARRAY[1,2,3]), (ARRAY[1,2]);
```
--------------------------------
### Create Database Connection with Neon Serverless Driver
Source: https://neon.com/docs/guides/nuxt
Use the Neon serverless driver and `useRuntimeConfig` to establish a database connection and execute a query. Ensure the handler is async and configure caching appropriately.
```javascript
import { neon } from '@neondatabase/serverless';
export default defineCachedEventHandler(
async (event) => {
const { databaseUrl } = useRuntimeConfig();
const db = neon(databaseUrl);
const result = await db`SELECT version()`;
return result;
},
{
maxAge: 60 * 60 * 24, // cache it for a day
}
);
```
--------------------------------
### FeatureList with Icons
Source: https://neon.com/docs/community/component-guide
Example of using the `icons` prop with the FeatureList component to display associated icons.
```mdx
```
```
--------------------------------
### Configure OpenAI Client with AI Gateway Token (Python)
Source: https://neon.com/docs/ai-gateway/authentication
Initialize the OpenAI client in Python using `NEON_AI_GATEWAY_TOKEN` and `NEON_AI_GATEWAY_BASE_URL` environment variables. Ensure the `base_url` includes the correct path for the AI Gateway.
```python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ["NEON_AI_GATEWAY_TOKEN"],
base_url=f"{os.environ['NEON_AI_GATEWAY_BASE_URL']}/ai-gateway/mlflow/v1",
)
```
--------------------------------
### Get Database
Source: https://neon.com/docs/reference/claimable-postgres
Retrieves the details of a specific unclaimed PostgreSQL database instance using its ID.
```APIDOC
## GET /api/v1/database/:id
### Description
Retrieves the details of a specific unclaimed PostgreSQL database instance by its ID. The response schema is the same as the 'Create database' endpoint.
### Method
GET
### Endpoint
https://neon.new/api/v1/database/:id
### Parameters
#### Path Parameters
- **id** (string) - Required - The unique identifier of the database to retrieve.
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the database.
- **status** (string) - The current status of the database (e.g., "UNCLAIMED").
- **neon_project_id** (string) - The Neon project ID associated with the database.
- **connection_string** (string) - The connection string to access the database.
- **claim_url** (string) - The URL to claim the database to a Neon account.
- **expires_at** (string) - The timestamp when the database will expire.
- **created_at** (string) - The timestamp when the database was created.
- **updated_at** (string) - The timestamp when the database was last updated.
#### Response Example
```json
{
"id": "01abc123-def4-5678-9abc-def012345678",
"status": "UNCLAIMED",
"neon_project_id": "cool-breeze-12345678",
"connection_string": "postgresql://neondb_owner:npg_xxxx@ep-cool-breeze-pooler...",
"claim_url": "https://neon.new/claim/01abc123-def4-5678-9abc-def012345678",
"expires_at": "2026-02-01T12:00:00.000Z",
"created_at": "2026-01-29T12:00:00.000Z",
"updated_at": "2026-01-29T12:00:00.000Z"
}
```
```
--------------------------------
### Get Organization Details
Source: https://neon.com/docs/manage/orgs-api
Retrieves information about your organization, including its name, plan, and creation date.
```APIDOC
## Get Organization Details
### Description
Retrieves detailed information about your organization, such as its name, current plan, and when it was created.
### Method
GET
### Endpoint
/organizations/{org_id}
### Parameters
#### Path Parameters
- **org_id** (string) - Required - The ID of the organization.
### Response
#### Success Response (200 OK)
- **id** (string) - The unique identifier of the organization.
- **name** (string) - The name of the organization.
- **handle** (string) - The handle or slug of the organization.
- **plan** (string) - The current subscription plan of the organization.
- **created_at** (string) - The timestamp when the organization was created.
- **managed_by** (string) - Indicates how the organization is managed (e.g., 'console').
- **updated_at** (string) - The timestamp when the organization details were last updated.
### Response Example
```json
{
"id": "org-example-12345678",
"name": "Example Organization",
"handle": "example-organization-org-example-12345678",
"plan": "business",
"created_at": "2024-01-01T12:00:00Z",
"managed_by": "console",
"updated_at": "2024-01-01T12:00:00Z"
}
```
```
--------------------------------
### Access Koyeb Deployment Logs
Source: https://neon.com/docs/guides/koyeb
Execute this command to track the app deployment and visualize build logs on Koyeb.
```bash
koyeb service logs express-neon/express-neon -t build
```
--------------------------------
### Get Array Length
Source: https://neon.com/docs/data-types/array
Use `array_length` to find the number of elements in a specific dimension of an array.
```sql
SELECT name, array_length(categories, 1) as category_count
FROM products;
```
--------------------------------
### Get organization member details
Source: https://neon.com/docs/changelog/2024-11-08
Retrieves detailed information about a specific member within an organization.
```APIDOC
## GET /organizations/{organizationId}/members/{memberId}
### Description
Retrieves detailed information about a specific member within an organization.
### Method
GET
### Endpoint
/organizations/{organizationId}/members/{memberId}
### Parameters
#### Path Parameters
- **organizationId** (string) - Required - The unique identifier of the organization.
- **memberId** (string) - Required - The unique identifier of the member.
```
--------------------------------
### Get Active Member Role
Source: https://neon.com/docs/auth/guides/plugins/organization
Retrieves the current user's role(s) in the active organization.
```APIDOC
## Get Active Member Role
### Description
Gets the current user's role(s) in the active organization.
### Method
GET (assumed based on operation)
### Endpoint
/organization/members/me/roles (assumed based on operation)
### Parameters
This method does not take any parameters.
### Request Example
```ts
const { data, error } = await authClient.organization.getActiveMemberRole();
```
```
--------------------------------
### Connect to Database via psql
Source: https://neon.com/docs/changelog/2026-06-05
Use the `neon psql` command to connect to your database using `psql`. Arguments after `--` are passed directly to `psql`.
```bash
neon psql production -- -c "SELECT version()"
```
--------------------------------
### Get Active Member
Source: https://neon.com/docs/auth/guides/plugins/organization
Retrieves the current user's membership details for the active organization.
```APIDOC
## Get Active Member
### Description
Gets the current user's membership details for the active organization.
### Method
GET (assumed based on operation)
### Endpoint
/organization/members/me (assumed based on operation)
### Parameters
This method does not take any parameters.
### Request Example
```ts
const { data, error } = await authClient.organization.getActiveMember();
```
```
--------------------------------
### Initialize Client with Different Adapter
Source: https://neon.com/docs/reference/javascript-sdk
Initializes the client using a different authentication adapter, such as `BetterAuthReactAdapter`.
```APIDOC
## Initialize Client with Different Adapter
Configure the client to use a specific authentication adapter by passing it within the `auth` options.
### Example
```typescript
import { createClient } from '@neondatabase/neon-js';
import { BetterAuthReactAdapter } from '@neondatabase/neon-js/auth/react/adapters';
const client = createClient({
auth: {
adapter: BetterAuthReactAdapter(),
url: import.meta.env.VITE_NEON_AUTH_URL,
},
dataApi: {
url: import.meta.env.VITE_NEON_DATA_API_URL,
},
});
```
```
--------------------------------
### Apply Migrations
Source: https://neon.com/docs/guides/laravel-migrations
Command to execute all pending migration files and create the corresponding database tables.
```bash
php artisan migrate
```
--------------------------------
### Add Liquibase to PATH (zsh)
Source: https://neon.com/docs/guides/liquibase
Append the Liquibase installation directory to your PATH environment variable in zsh.
```bash
echo 'export PATH=$PATH:/path/to/liquibase' >> ~/.zshrc
source ~/.zshrc
```
--------------------------------
### Create Liquibase Project Directory
Source: https://neon.com/docs/guides/liquibase
Create a new directory for your Liquibase project files.
```bash
mkdir blogdb
```
--------------------------------
### Add Liquibase to PATH (profile)
Source: https://neon.com/docs/guides/liquibase
Append the Liquibase installation directory to your PATH environment variable in profile.
```bash
echo 'export PATH=$PATH:/path/to/liquibase' >> ~/.profile
source ~/.profile
```
--------------------------------
### Add Liquibase to PATH (bashrc)
Source: https://neon.com/docs/guides/liquibase
Append the Liquibase installation directory to your PATH environment variable in bashrc.
```bash
echo 'export PATH=$PATH:/path/to/liquibase' >> ~/.bashrc
source ~/.bashrc
```
--------------------------------
### Run PostgREST with Docker on Linux
Source: https://neon.com/docs/guides/postgrest
Starts a PostgREST Docker container on Linux, connecting to a Neon database using an unpooled connection string and specifying the schema and anonymous role.
```bash
docker run --rm --net=host \
-e PGRST_DB_URI="" \
-e PGRST_DB_SCHEMA="api" \
-e PGRST_DB_ANON_ROLE="anonymous" \
postgrest/postgrest
```
--------------------------------
### Configure Postgres.js Client
Source: https://neon.com/docs/guides/sveltekit
Set up the postgres client for connecting to Neon using postgres.js. Loads connection string from environment variables and requires SSL.
```typescript
import 'dotenv/config';
import postgres from 'postgres';
const connectionString: string = process.env.DATABASE_URL as string;
const sql = postgres(connectionString, { ssl: 'require' });
export { sql };
```
--------------------------------
### Enable TimescaleDB Extension
Source: https://neon.com/docs/extensions/timescaledb
Install the TimescaleDB extension on your Neon project. This enables time-series data capabilities.
```sql
CREATE EXTENSION IF NOT EXISTS timescaledb;
```
--------------------------------
### Verify JWT in Go
Source: https://neon.com/docs/auth/guides/plugins/jwt
This Go example shows how to verify a Neon Auth JWT. It requires the NEON_AUTH_BASE_URL environment variable and uses the 'keyfunc' library to manage JWKS.
```go
package main
import (
"fmt"
"log"
"net/url"
"os"
"github.com/MicahParks/keyfunc/v3"
"github.com/golang-jwt/jwt/v5"
)
func ValidateNeonToken(tokenString string) (jwt.MapClaims, error) {
baseURL := os.Getenv("NEON_AUTH_BASE_URL")
if baseURL == "" {
return nil, fmt.Errorf("NEON_AUTH_BASE_URL is not set")
}
jwksURL := fmt.Sprintf("%s/.well-known/jwks.json", baseURL)
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("failed to parse base URL: %w", err)
}
expectedIssuer := fmt.Sprintf("%s://%s", u.Scheme, u.Host)
jwks, err := keyfunc.NewDefault([]string{jwksURL})
if err != nil {
return nil, fmt.Errorf("failed to create JWKS from resource at %s: %w", jwksURL, err)
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return jwks.Keyfunc(token)
},
jwt.WithIssuer(expectedIssuer),
jwt.WithValidMethods([]string{"EdDSA"}),
)
if err != nil {
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return nil, fmt.Errorf("invalid token")
}
return claims, nil
}
```
--------------------------------
### Enable the hstore Extension
Source: https://neon.com/docs/extensions/hstore
Enables the hstore extension if it is not already installed. This is a prerequisite for using hstore functionality.
```sql
CREATE EXTENSION IF NOT EXISTS hstore;
```
--------------------------------
### Connect to Lego Database
Source: https://neon.com/docs/import/import-sample-data
Connect to the 'lego' database using the psql command-line tool. Ensure your connection string is correct.
```bash
psql postgresql://[user]:[password]@[neon_hostname]/lego
```
--------------------------------
### Enable dblink Extension
Source: https://neon.com/docs/extensions/dblink
Enables the dblink extension if it is not already installed. This is a prerequisite for using dblink functionalities.
```sql
CREATE EXTENSION IF NOT EXISTS dblink;
```
--------------------------------
### Upgrade Neon CLI with npm
Source: https://neon.com/docs/cli/install
Update the Neon CLI to the latest version if it was installed using npm.
```shell
npm update -g neonctl
```
--------------------------------
### Display Python Kernel Information
Source: https://neon.com/docs/ai/ai-azure-notebooks
View the version and installation path of the active Python kernel in your notebook.
```python
import os
import sys
print(sys.version_info)
print(os.path.dirname(sys.executable))
```
--------------------------------
### Example Response for Disabled Transfer Requests
Source: https://neon.com/docs/workflows/claimable-database-integration
This JSON indicates that project transfer requests are not enabled for the account.
```json
{
"request_id": "cb1e1228-19f9-4904-8bd5-2dbf17d911a2",
"code": "",
"message": "project transfer requests are not enabled for this account"
}
```
--------------------------------
### Create React Router Project
Source: https://neon.com/docs/guides/react-router
Use this command to create a new React Router project. The `--yes` flag accepts all defaults.
```shell
npx create-react-router@latest with-react-router --yes
cd with-react-router
```
--------------------------------
### Environment Variables for Database Connections
Source: https://neon.com/docs/guides/rls-query-execution
Example .env file structure for managing separate database connection strings for authenticated access (RLS enforced) and administrative tasks (RLS bypassed).
```bash
# Connects with 'authenticated_backend' - enforce RLS, used by user-facing backend APIs
DATABASE_AUTHENTICATED_URL="postgresql://authenticated_backend:xxx@ep-cool-snowflake-12345.us-east-2.aws.neon.tech/neondb?sslmode=require"
# Connects with 'neondb_owner' - bypass RLS, used for setup, migrations, and cron administrative tasks
DATABASE_URL="postgresql://neondb_owner:xxx@ep-cool-snowflake-12345.us-east-2.aws.neon.tech/neondb?sslmode=require"
```
--------------------------------
### Delete Compute Response Body
Source: https://neon.com/docs/manage/computes
Example JSON response body when a compute resource is successfully deleted.
```json
{
"endpoint": {
"host": "ep-misty-morning-a1pfa4ez.ap-southeast-1.aws.neon.tech",
"id": "ep-misty-morning-a1pfa4ez",
"project_id": "autumn-lake-30024670",
"branch_id": "br-raspy-pine-a1hspnzv",
"autoscaling_limit_min_cu": 1,
"autoscaling_limit_max_cu": 2,
"region_id": "aws-ap-southeast-1",
"type": "read_write",
"current_state": "idle",
"settings": {},
"pooler_enabled": false,
"pooler_mode": "transaction",
"disabled": false,
"passwordless_access": true,
"last_active": "2025-08-03T17:40:20Z",
"creation_source": "console",
"created_at": "2025-08-03T17:40:19Z",
"updated_at": "2025-08-03T17:52:39Z",
"suspended_at": "2025-08-03T17:45:24Z",
"proxy_host": "ap-southeast-1.aws.neon.tech",
"suspend_timeout_seconds": 0,
"provisioner": "k8s-neonvm"
},
"operations": []
}
```
--------------------------------
### Turso/SQLite Case-Insensitive LIKE
Source: https://neon.com/docs/import/migrate-from-turso
Example of case-insensitive string matching using the LIKE operator in Turso (SQLite).
```sql
SELECT * FROM users WHERE username LIKE '%alice%';
```
--------------------------------
### Deploy to Production with Encore
Source: https://neon.com/docs/guides/encore
Use this command to deploy your Encore application to the production environment. Encore automatically handles Neon database creation, migrations, and application deployment.
```bash
git push encore
```
--------------------------------
### Create Initial Schema (Console)
Source: https://neon.com/docs/guides/schema-diff-tutorial
Applies the initial schema to the 'people' database using the Neon Console's SQL Editor.
```sql
CREATE TABLE person (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
```
--------------------------------
### Unschedule a Job by Name
Source: https://neon.com/docs/extensions/pg_cron
Removes a scheduled job using its name. This example unschedules the 'archive-old-orders' job.
```sql
SELECT cron.unschedule('archive-old-orders');
```
--------------------------------
### tsvector Syntax Example
Source: https://neon.com/docs/data-types/tsvector
Illustrates the general syntax of a tsvector value, showing lexemes, positions, and weights.
```sql
'a':1A 'cat':2 'sat':3 'on':4 'the':5 'mat':6
```
--------------------------------
### Basic pgloader migration from Turso to Neon
Source: https://neon.com/docs/import/migrate-from-turso
Run pgloader directly from the command line for a straightforward migration. Ensure the Postgres connection string is enclosed in quotes.
```shell
pgloader sqlite://turso_export.db "postgresql://alex:endpoint=ep-cool-darkness-123456;AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require"
```
--------------------------------
### SQL Code Block Example
Source: https://neon.com/docs/community/contribution-guide
Illustrates how to embed a SQL code block with language highlighting in Markdown.
```sql
SELECT * FROM posts ORDER BY id;
```
--------------------------------
### Run Go Script
Source: https://neon.com/docs/guides/go
This command executes the Go program to create a table and insert data into your Neon database.
```bash
go run create_table.go
```
--------------------------------
### Markdown Comment Examples
Source: https://neon.com/docs/community/contribution-guide
Shows how to use single-line and multi-line comments in Markdown, including JSX-style comments.
```markdown
[comment]: <> (Single line comment.)
[comment]: <> (
Multiline comment.
You can't use line breaks or () parentheses here.
)
```
```markdown
{/*
content
*/}
```
--------------------------------
### Initialize Terraform
Source: https://neon.com/docs/guides/logical-replication-clickhouse
Initializes the Terraform working directory to download the necessary ClickHouse provider.
```bash
terraform init
```
--------------------------------
### Replace React Hooks (Before)
Source: https://neon.com/docs/auth/migrate/from-legacy-auth
Example of using the legacy Stack Auth `useUser` hook in a React component.
```tsx
import { useUser } from '@stackframe/stack';
export function MyComponent() {
const user = useUser();
return
;
```
--------------------------------
### Get Anonymization Status
Source: https://neon.com/docs/workflows/data-anonymization
Retrieves the current status of the data anonymization job for a given project and branch.
```APIDOC
## GET /projects/{project_id}/branches/{branch_id}/anonymized_status
### Description
Retrieves the current status of the data anonymization job for a given project and branch.
### Method
GET
### Endpoint
/projects/{project_id}/branches/{branch_id}/anonymized_status
### Parameters
#### Path Parameters
- **project_id** (string) - Required - The ID of the project.
- **branch_id** (string) - Required - The ID of the branch.
```
--------------------------------
### Initialize NeonAPI Client
Source: https://neon.com/docs/reference/python-sdk
Initialize the NeonAPI client with your API key.
```python
from neon_api import NeonAPI
# Initialize the client.
neon = NeonAPI(api_key='your_api_key')
```
--------------------------------
### Add Sample Data to Neon Database
Source: https://neon.com/docs/guides/wundergraph
Run these SQL statements to create and populate the Users and Messages tables in your Neon database.
```sql
create table if not exists Users (
id serial primary key not null,
email text not null,
name text not null,
unique (email)
);
create table if not exists Messages (
id serial primary key not null,
user_id int not null references Users(id),
message text not null
);
insert into Users (email, name) VALUES ('Jens@wundergraph.com','Jens@WunderGraph');
insert into Messages (user_id, message) VALUES ((select id from Users where email = 'Jens@wundergraph.com'),'Hey, welcome to the WunderGraph!');
insert into Messages (user_id, message) VALUES ((select id from Users where email = 'Jens@wundergraph.com'),'This is WunderGraph!');
insert into Messages (user_id, message) VALUES ((select id from Users where email = 'Jens@wundergraph.com'),'WunderGraph!');
alter table Users add column updatedAt timestamptz not null default now();
alter table Users add column lastLogin timestamptz not null default now();
```
--------------------------------
### Get Function Invocation URL
Source: https://neon.com/docs/compute/functions/get-started
Retrieve the public invocation URL for a deployed function using its slug.
```bash
neonctl functions get hello
```
--------------------------------
### Get Data API Details
Source: https://neon.com/docs/data-api/manage
Retrieve the current status and configuration of the Data API for a specified database.
```bash
neon data-api get --database neondb
```
--------------------------------
### Start Neon MCP Server for Older Clients
Source: https://neon.com/docs/ai/neon-mcp-server
Use this command when prompted if your client does not support JSON for MCP server configuration, such as older versions of Cursor. Replace with your actual Neon API key.
```bash
npx -y @neondatabase/mcp-server-neon start
```
--------------------------------
### Get Default Connection String
Source: https://neon.com/docs/cli/quickstart
Retrieve the connection string for the default branch of your current Neon project.
```bash
neonctl connection-string
```
--------------------------------
### Sign in with Vercel
Source: https://neon.com/docs/auth/guides/setup-oauth
Initiates the Vercel OAuth sign-in flow. Ensure `authClient` is imported from your authentication setup.
```jsx
import { authClient } from './auth';
const handleVercelSignIn = async () => {
try {
await authClient.signIn.social({
provider: "vercel",
callbackURL: window.location.origin,
});
} catch (error) {
console.error("Vercel sign-in error:", error);
}
};
```
--------------------------------
### Sign in with GitHub
Source: https://neon.com/docs/auth/guides/setup-oauth
Initiates the GitHub OAuth sign-in flow. Ensure `authClient` is imported from your authentication setup.
```jsx
import { authClient } from './auth';
const handleGitHubSignIn = async () => {
try {
await authClient.signIn.social({
provider: "github",
callbackURL: window.location.origin,
});
} catch (error) {
console.error("GitHub sign-in error:", error);
}
};
```
--------------------------------
### Create electronics_products Table
Source: https://neon.com/docs/functions/json_array_elements
Sets up the 'electronics_products' table with columns for ID, name, and JSON details. This table is used to demonstrate handling nested JSON arrays.
```sql
CREATE TABLE electronics_products (
id INTEGER PRIMARY KEY,
name TEXT,
details JSON
);
```
--------------------------------
### Sign in with Google
Source: https://neon.com/docs/auth/guides/setup-oauth
Initiates the Google OAuth sign-in flow. Ensure `authClient` is imported from your authentication setup.
```jsx
import { authClient } from './auth';
const handleGoogleSignIn = async () => {
try {
await authClient.signIn.social({
provider: "google",
callbackURL: window.location.origin,
});
} catch (error) {
console.error("Google sign-in error:", error);
}
};
```
--------------------------------
### List All Functions (CLI)
Source: https://neon.com/docs/compute/functions/deploy
Use the `neonctl functions list` command to retrieve a list of all deployed functions in the current project.
```bash
neonctl functions list
```
--------------------------------
### Enable pgvector Extension
Source: https://neon.com/docs/extensions/pgvector
Run this statement once in each database where you want to store vectors. The extension is installed per database.
```sql
CREATE EXTENSION IF NOT EXISTS vector;
```
--------------------------------
### Create and Populate Customers Table
Source: https://neon.com/docs/extensions/pgstattuple
This SQL script creates a 'customers' table and inserts 10,000 rows. It's used to simulate data and prepare for bloat analysis.
```sql
-- Create the customers table
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
first_name VARCHAR(100),
last_name VARCHAR(100),
email VARCHAR(255),
phone VARCHAR(20),
address VARCHAR(255),
city VARCHAR(100),
state VARCHAR(100),
zip_code VARCHAR(20),
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW()
);
-- Insert 10,000 rows into the customers table
INSERT INTO customers (first_name, last_name, email, phone, address, city, state, zip_code, created_at)
SELECT
CASE (i % 10) WHEN 0 THEN 'John' WHEN 1 THEN 'Jane' WHEN 2 THEN 'Peter' WHEN 3 THEN 'Mary' WHEN 4 THEN 'Robert' WHEN 5 THEN 'Patricia' WHEN 6 THEN 'Michael' WHEN 7 THEN 'Linda' WHEN 8 THEN 'William' ELSE 'Elizabeth' END || '_' || i::TEXT,
CASE (i % 10) WHEN 0 THEN 'Smith' WHEN 1 THEN 'Johnson' WHEN 2 THEN 'Williams' WHEN 3 THEN 'Jones' WHEN 4 THEN 'Brown' WHEN 5 THEN 'Davis' WHEN 6 THEN 'Miller' WHEN 7 THEN 'Wilson' WHEN 8 THEN 'Moore' ELSE 'Taylor' END || '_' || i::TEXT,
'customer' || i::TEXT || '@example.com',
'555-' || LPAD((i % 10000)::TEXT, 4, '0'),
(i * 10)::TEXT || ' Main St',
CASE (i % 5) WHEN 0 THEN 'New York' WHEN 1 THEN 'Los Angeles' WHEN 2 THEN 'Chicago' WHEN 3 THEN 'Houston' ELSE 'Phoenix' END,
CASE (i % 5) WHEN 0 THEN 'NY' WHEN 1 THEN 'CA' WHEN 2 THEN 'IL' WHEN 3 THEN 'TX' ELSE 'AZ' END,
LPAD((i % 99999)::TEXT, 5, '0'),
NOW() - (random() * INTERVAL '365 days')
FROM generate_series(1, 10000) AS s(i);
-- Delete half of the rows to create dead tuples
DELETE FROM customers WHERE customer_id % 2 = 0;
-- Check the table statistics before vacuuming
SELECT * FROM pgstattuple('customers');
```
--------------------------------
### Create Cube Values On-the-Fly
Source: https://neon.com/docs/extensions/cube
Demonstrates creating cube values directly within SELECT statements for points and intervals.
```sql
SELECT cube(array[1,2,3]) AS point_3d, cube(0,10) AS interval_1d;
```
--------------------------------
### Run JavaScript Script
Source: https://neon.com/docs/guides/javascript
Execute the Node.js script to delete data from your Neon database. Ensure you have Node.js installed.
```bash
node delete_data.js
```
--------------------------------
### Create a Role
Source: https://neon.com/docs/reference/typescript-sdk
This example demonstrates how to create a new Postgres role within a Neon branch using the SDK. It includes error handling and shows how to obtain necessary IDs.
```APIDOC
## Create a Role
You can use the SDK to create a new Postgres role within a Neon branch. Here's an example of how to create a role:
```typescript
import { createApiClient } from '@neondatabase/api-client';
const apiClient = createApiClient({
apiKey: process.env.NEON_API_KEY!,
});
async function createNeonRole(projectId: string, branchId: string, roleName: string) {
try {
const response = await apiClient.createProjectBranchRole(projectId, branchId, {
role: { name: roleName },
});
console.log('Role created:', response.data.role);
} catch (error) {
console.error('Error creating role:', error);
throw error;
}
}
// Example usage: In the project with ID "your-project-id", create a role named "new_user_role" in the branch with ID "your-branch-id"
createNeonRole('your-project-id', 'your-branch-id', 'new_user_role').catch((error) => {
console.error('Error creating role:', error.message);
});
```
#### Key points:
- `role.name`: Specifies the name of the Postgres role to be created.
- Branch & Project IDs: You can obtain these IDs from the [Neon Console](https://neon.com/docs/manage/branches#view-branches) or using SDK methods (for example, [listProjectBranches](https://neon.com/docs/reference/typescript-sdk#list-branches), [listProjects](https://neon.com/docs/reference/typescript-sdk#list-projects))
```
--------------------------------
### Seed Database with Initial Data
Source: https://neon.com/docs/guides/sqlalchemy-migrations
This Python script initializes the database with author and book records. It requires `database.py` and `models.py` to be defined.
```python
from database import SessionLocal
from models import Author, Book
def seed_data():
db = SessionLocal()
# Create authors
authors = [
Author(
name="J.R.R. Tolkien",
bio="The creator of Middle-earth and author of The Lord of the Rings."
),
Author(
name="George R.R. Martin",
bio="The author of the epic fantasy series A Song of Ice and Fire."
),
Author(
name="J.K. Rowling",
bio="The creator of the Harry Potter series."
),
]
db.add_all(authors)
db.commit()
# Create books
books = [
Book(title="The Fellowship of the Ring", author=authors[0]),
Book(title="The Two Towers", author=authors[0]),
Book(title="The Return of the King", author=authors[0]),
Book(title="A Game of Thrones", author=authors[1]),
Book(title="A Clash of Kings", author=authors[1]),
Book(title="Harry Potter and the Philosopher's Stone", author=authors[2]),
Book(title="Harry Potter and the Chamber of Secrets", author=authors[2]),
]
db.add_all(books)
db.commit()
print("Data seeded successfully.")
if __name__ == "__main__":
seed_data()
```
--------------------------------
### Check Available Extension Versions
Source: https://neon.com/docs/data-api/database-advisor
Query the pg_catalog.pg_available_extensions view to check the installed and default versions of a specific extension.
```sql
SELECT name, installed_version, default_version
FROM pg_catalog.pg_available_extensions
WHERE name = '';
```