0.1.0 • Published 8 months ago

@netlify/neon v0.1.0

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

@netlify/neon

npm version License

Netlify-optimized wrapper for @neondatabase/serverless with automatic environment configuration.

@neondatabase/serverless is Neon's PostgreSQL driver for JavaScript and TypeScript. It's:

  • Low-latency, thanks to message pipelining and other optimizations
  • Ideal for serverless/edge deployment, using https and WebSockets in place of TCP
  • A drop-in replacement for node-postgres, aka pg (on which it's based)

Netlify Integration

Automatically uses your Neon database connection via Netlify environment variables:

# Install package
npm install @netlify/neon

# Configure database (via Netlify CLI)
netlify db init

Basic Usage

import { neon } from '@netlify/neon'
const sql = neon() // automatically uses env NETLIFY_DATABASE_URL

const [post] = await sql`SELECT * FROM posts WHERE id = ${postId}`
// `post` is now { id: 12, title: 'My post', ... } (or undefined)

Usage with Drizzle-ORM

// ./src/db/index.ts
import { neon } from '@netlify/neon'
import { drizzle } from 'drizzle-orm/neon-http'
import { posts } from "./schema"

export const db = drizzle({
  schema,
  client: neon() // Uses NETLIFY_DATABASE_URL automatically
})

// ./src/db/schema.ts
import { integer, pgTable, varchar, text } from 'drizzle-orm/pg-core'

export const postsTable = pgTable('posts', {
    id: integer().primaryKey().generatedAlwaysAsIdentity(),
    title: varchar({ length: 255 }).notNull(),
    content: text().notNull().default('')
})

Querying with Drizzle

import { db } from "./db"
import { postsTable } from "./db/schema"

const posts = await db.select().from(postsTable)

Read more about using Drizzle-ORM with Neon: Get started

With additional options

The neon function imported from @netlify/neon also supports all of the same HTTP options as @neondatabase/serverless.

import { neon } from '@netlify/neon'

// automatically using connection string from env NETLIFY_DATABASE_URL 
const sql = neon({
    arrayMode: true,
    fetchOptions: { priority: 'high' }
})

// or when explicitly passing in a connection string override
const sql = neon("postgres://user:pass@host/db",{
    arrayMode: true,
    fetchOptions: { priority: 'high' }
})

Transactions

Supports all Neon transaction options:

import { neon } from '@netlify/neon'

const sql = neon() // automatically uses env NETLIFY_DATABASE_URL
const showLatestN = 10
const [posts, tags] = await sql.transaction(
  [sql`SELECT * FROM posts ORDER BY posted_at DESC LIMIT ${showLatestN}`, sql`SELECT * FROM tags`],
  {
    isolationLevel: 'RepeatableRead',
    readOnly: true,
  }
)

Documentation

šŸ“š Neon Serverless Driver Docs
šŸ“š Drizzle with Neon Postgres

0.1.0

8 months ago