DEV Community

Alex Spinov
Alex Spinov

Posted on

Neon Has a Free API That Gives You Serverless Postgres That Scales to Zero

Neon is serverless Postgres with branching, autoscaling, and a JavaScript SDK. Your database scales to zero when idle — you only pay for what you use.

Neon Serverless Driver

import { neon } from "@neondatabase/serverless";

const sql = neon(process.env.DATABASE_URL);

// Simple query
const products = await sql`SELECT * FROM products WHERE price < ${50} ORDER BY created_at DESC LIMIT 20`;

// Insert
await sql`INSERT INTO products (title, price, url) VALUES (${title}, ${price}, ${url})`;

// Transaction
const result = await sql.transaction([
  sql`INSERT INTO orders (user_id, total) VALUES (${userId}, ${total}) RETURNING id`,
  sql`UPDATE inventory SET stock = stock - ${qty} WHERE product_id = ${productId}`,
]);
Enter fullscreen mode Exit fullscreen mode

Works Everywhere: Edge, Serverless, Browser

// Cloudflare Workers
export default {
  async fetch(request, env) {
    const sql = neon(env.DATABASE_URL);
    const data = await sql`SELECT * FROM products`;
    return Response.json(data);
  },
};

// Vercel Edge Function
export const config = { runtime: "edge" };
export default async function handler() {
  const sql = neon(process.env.DATABASE_URL);
  const data = await sql`SELECT count(*) FROM products`;
  return Response.json(data);
}
Enter fullscreen mode Exit fullscreen mode

Drizzle ORM Integration

import { drizzle } from "drizzle-orm/neon-http";
import { neon } from "@neondatabase/serverless";

const sql = neon(process.env.DATABASE_URL);
const db = drizzle(sql);

const products = await db.select().from(productsTable).where(lt(productsTable.price, 50));
Enter fullscreen mode Exit fullscreen mode

Branching: Database Git

# Create a branch (instant copy of your database)
neonctl branches create --name feature/new-schema

# Each branch has its own connection string
# Perfect for: preview deployments, testing, development

# Reset branch to parent
neonctl branches reset feature/new-schema --parent

# Delete branch
neonctl branches delete feature/new-schema
Enter fullscreen mode Exit fullscreen mode

Neon API: Programmatic Control

// Create a project
const project = await fetch("https://console.neon.tech/api/v2/projects", {
  method: "POST",
  headers: { Authorization: `Bearer ${NEON_API_KEY}` },
  body: JSON.stringify({ project: { name: "my-project" } }),
}).then(r => r.json());

// Create a branch
const branch = await fetch(`https://console.neon.tech/api/v2/projects/${projectId}/branches`, {
  method: "POST",
  headers: { Authorization: `Bearer ${NEON_API_KEY}` },
  body: JSON.stringify({ branch: { name: "dev" } }),
}).then(r => r.json());
Enter fullscreen mode Exit fullscreen mode

Connection Pooling

import { Pool } from "@neondatabase/serverless";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const client = await pool.connect();

try {
  await client.query("BEGIN");
  await client.query("INSERT INTO products (title) VALUES ($1)", ["Widget"]);
  await client.query("COMMIT");
} catch (e) {
  await client.query("ROLLBACK");
  throw e;
} finally {
  client.release();
}
Enter fullscreen mode Exit fullscreen mode

Store scraped data in serverless Postgres? My Apify tools + Neon = scalable data storage.

Custom database solution? Email spinov001@gmail.com

Top comments (0)