The complete guide to serverless PostgreSQL — what Neon is, how it works under the hood, how to connect it to your app, and how it compares to every major alternative in 2026.
G-Tech Blog | 2026 | 18 min readIf you are building a web app, a side project, or learning backend development for the first time, one of the first decisions you face is choosing a database. Neon has emerged as one of the most compelling choices in the modern developer stack — a serverless PostgreSQL platform that removes the traditional friction of database management while giving you the full power of one of the world's most capable relational databases. This guide explains everything: what Neon is, how its serverless architecture actually works, how to connect it to your Node.js or Next.js app, how it compares to alternatives, and when it is and is not the right choice for your project.
Before understanding Neon, it helps to understand what PostgreSQL is and why it matters. PostgreSQL (commonly called Postgres) is a free, open-source relational database management system (RDBMS) that has been in active development since 1996. It's consistently ranked among the most popular and most trusted databases in the world by developers in the annual Stack Overflow Developer Survey.
PostgreSQL stores data in structured tables with rows and columns — similar to a spreadsheet, but much more powerful. You use a language called SQL (Structured Query Language) to interact with it: creating tables, inserting data, querying records, updating rows, and deleting entries. What distinguishes PostgreSQL from simpler databases is its depth: it supports advanced features like JSON columns, full-text search, geospatial queries (PostGIS), foreign key constraints, transactions, stored procedures, and complex joins that are key for real production applications.
Neon is a serverless PostgreSQL database platform founded in 2021 by several engineers who previously worked on PostgreSQL core development. The key word is serverless — Neon gives you a complete, fully-featured PostgreSQL database in the cloud without you ever having to provision, configure, maintain, or scale a server. You create a project, get a connection string, and start building. Everything else — the hardware, the backups, the scaling, the security patches — is Neon's responsibility.
Neon is not a different database that happens to look like PostgreSQL. It runs the actual PostgreSQL engine, which means every SQL command, every driver, every ORM (Prisma, Drizzle, SQLAlchemy, Sequelize), and every PostgreSQL-compatible tool works with Neon exactly as it would with a self-hosted PostgreSQL server. The serverless architecture is entirely transparent to your application code — you connect with a standard PostgreSQL connection string and write standard SQL.
Neon is PostgreSQL, fully managed, billed by usage, with instant branching, autoscaling, and a generous free tier — built for the way modern apps are developed and deployed.
Understanding the architecture makes Neon's capabilities and limitations much clearer. Traditional managed databases (like Amazon RDS) rent you a virtual machine running PostgreSQL 24/7 — you pay a fixed monthly price whether your database receives 1 query or 1 million queries. Neon's architecture is fundamentally different.
Neon separates the database into two distinct layers. The storage layer holds your actual data persistently — it never disappears, even when the database is idle. The compute layer is where your SQL queries execute — it is ephemeral and can be started and stopped dynamically. When your app makes a database query, Neon spins up a compute instance, processes the query against the storage layer, and returns the result. When there are no queries for a period, the compute scales down to zero.
When your database is idle (no queries for a configurable period, default ~5 minutes), Neon suspends the compute instance. Your data remains intact in storage. The next query wakes the compute up — this takes approximately 200—500ms, which is called a cold start. For production apps with regular traffic, the database stays warm and cold starts are never experienced. For development databases and infrequently accessed apps, cold starts are a trade-off for not paying for idle compute time.
Because standard PostgreSQL connections are persistent TCP connections (which do not work well with serverless
compute), Neon uses a proprietary proxy layer between your application and the database. The Neon Proxy manages
connection pooling, handles the compute wake-up transparently, and supports the WebSocket-based
@neondatabase/serverless driver that enables use from serverless environments like Vercel Edge
Functions and Cloudflare Workers where TCP connections are not available.
Create a new PostgreSQL database in under 120 milliseconds via the dashboard or API. No waiting for a server to spin up, no configuration wizard, no SSH setup. You get a connection string immediately and can start writing SQL right away.
Neon automatically adjusts the amount of CPU and RAM allocated to your database based on current load. Under heavy traffic, compute scales up. During quiet periods, it scales down. You set minimum and maximum compute sizes; Neon handles the transitions without restarts or downtime.
The @neondatabase/serverless npm package enables Neon connections from serverless environments
(Vercel Edge, Cloudflare Workers, AWS Lambda) that do not support persistent TCP connections. It uses HTTP
and WebSockets instead of the standard PostgreSQL wire protocol.
Neon includes PgBouncer-powered connection pooling out of the box. Serverless functions often create many short-lived database connections, which can exhaust PostgreSQL's connection limits. Neon's pooled connection string (`-pooler` suffix) handles this automatically at no extra cost.
Neon continuously backs up your data and lets you restore to any point in time within the last 7 days (free tier) or 30 days (paid). Accidentally deleted a table? You can restore to the exact second before it happened without losing any other data.
On paid plans, Neon supports read replicas — additional database endpoints that handle read-only queries, reducing load on the primary write endpoint. This pattern significantly improves performance for read-heavy applications.
Database branching is Neon's most distinctive and powerful feature — one that has no equivalent in traditional managed database services. The concept is borrowed directly from Git: just as you create a code branch to work on a feature without affecting the main codebase, you create a database branch to work on schema changes, test new features, or run experiments without affecting your production data.
Neon branches use copy-on-write technology, which means creating a branch is instantaneous regardless of database size. A branch starts as a logical pointer to the same underlying storage pages as its parent. When either the branch or the parent writes new data, those writes diverge. Reading unchanged data costs nothing extra — only new writes consume additional storage. This makes creating dozens of branches for development and testing essentially free.
my-first-app).eu-west-1 (Ireland) is currently the closest available region.After creation, Neon shows your connection details. You'll see two connection strings:
-pooler in the hostnameThe connection string looks like this:
postgresql://username:password@ep-cool-name-123456.eu-west-1.aws.neon.tech/neondb?sslmode=require
Copy this to your .env or .env.local file as DATABASE_URL. Never
commit this to Git — it contains your database password.
Neon's dashboard includes a built-in SQL Editor. You can run queries directly without installing any tools. Try creating your first table:
-- Create a users table
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Insert a test record
INSERT INTO users (name, email) VALUES ('Jane Mugo', 'jane@example.com');
-- Query the table
SELECT * FROM users;
Click Run — you will see your data appear in the results panel immediately.
For traditional Node.js servers (Express, Fastify, Hono), use the pg package (node-postgres) or
the official Neon serverless driver.
# Install node-postgres
npm install pg dotenv
// db.js — Database connection module
require('dotenv').config();
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }, // Required for Neon's SSL
});
module.exports = pool;
// server.js — Express example
const express = require('express');
const pool = require('./db');
const app = express();
app.use(express.json());
// GET all users
app.get('/users', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM users ORDER BY created_at DESC');
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Database error' });
}
});
// POST create a user
app.post('/users', async (req, res) => {
const { name, email } = req.body;
try {
const result = await pool.query(
'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',
[name, email]
);
res.status(201).json(result.rows[0]);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
npm install @neondatabase/serverless
// For Vercel Edge Functions, Cloudflare Workers, etc.
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
export async function GET() {
const users = await sql`SELECT * FROM users ORDER BY created_at DESC`;
return Response.json(users);
}
The Neon serverless driver uses HTTP/WebSockets instead of TCP, making it compatible with edge runtimes that block persistent connections.
Prisma is the most popular ORM for Next.js and TypeScript projects. It gives you type-safe database queries, automatic migration management, and an intuitive schema definition language. Combining Prisma with Neon gives you a best-in-class developer experience for full-stack Next.js applications.
# Install Prisma and the Neon adapter
npm install prisma @prisma/client @prisma/adapter-neon @neondatabase/serverless
npx prisma init
Update your prisma/schema.prisma:
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
}
Create and run your migration:
npx prisma migrate dev --name init
Create lib/prisma.ts — a singleton Prisma client for Next.js:
import { PrismaClient } from '@prisma/client';
import { PrismaNeon } from '@prisma/adapter-neon';
import { neonConfig, Pool } from '@neondatabase/serverless';
import ws from 'ws';
neonConfig.webSocketConstructor = ws;
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
export const prisma =
globalForPrisma.prisma ||
new PrismaClient({
adapter: new PrismaNeon(new Pool({ connectionString: process.env.DATABASE_URL })),
});
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
Use in a Next.js Server Component or API Route:
// app/users/page.tsx — Server Component
import { prisma } from '@/lib/prisma';
export default async function UsersPage() {
const users = await prisma.user.findMany({
orderBy: { createdAt: 'desc' },
include: { posts: true },
});
return (
<div>
{users.map(user => (
<div key={user.id}>
<h3>{user.name}</h3>
<p>{user.email}</p>
<p>{user.posts.length} posts</p>
</div>
))}
</div>
);
}
Python developers can connect to Neon using psycopg2 (synchronous) or asyncpg
(asynchronous). Both work identically to connecting to a self-hosted PostgreSQL instance — just use the Neon
connection string.
pip install psycopg2-binary python-dotenv
import psycopg2
from dotenv import load_dotenv
import os
load_dotenv()
# Connect to Neon
conn = psycopg2.connect(os.getenv('DATABASE_URL'))
cursor = conn.cursor()
# Create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
stock INTEGER DEFAULT 0
)
""")
# Insert data
cursor.execute(
"INSERT INTO products (name, price, stock) VALUES (%s, %s, %s)",
("Kenyan Coffee 500g", 850.00, 100)
)
conn.commit()
# Query data
cursor.execute("SELECT * FROM products")
products = cursor.fetchall()
for product in products:
print(f"ID: {product[0]}, Name: {product[1]}, Price: KSh {product[2]}")
cursor.close()
conn.close()
One of Neon's best features for learners is the built-in SQL Editor in the dashboard. You can practice SQL directly without installing anything locally. Here are the fundamental SQL operations you will use in almost every project.
-- ———— CREATE TABLE ————————————————————————————————————————————————————————————
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
price DECIMAL(10,2) NOT NULL,
category VARCHAR(100),
in_stock BOOLEAN DEFAULT true,
created TIMESTAMP DEFAULT NOW()
);
-- ———— INSERT DATA ————————————————————————————————————————————————————————————————
INSERT INTO products (name, price, category) VALUES
('Laptop Stand', 2500.00, 'Accessories'),
('Mechanical Keyboard', 8900.00, 'Input Devices'),
('USB-C Hub', 3200.00, 'Accessories');
-- ———— SELECT (basic query) ————————————————————————————————————————————————
SELECT * FROM products;
-- ———— SELECT with WHERE filter ——————————————————————————————————————
SELECT name, price FROM products
WHERE category = 'Accessories'
ORDER BY price ASC;
-- ———— UPDATE a row ————————————————————————————————————————————————————————————————
UPDATE products
SET price = 2800.00
WHERE name = 'Laptop Stand';
-- ———— DELETE a row ————————————————————————————————————————————————————————————————
DELETE FROM products WHERE id = 3;
-- ———— JOIN two tables ——————————————————————————————————————————————————————————
SELECT orders.id, users.name, products.name AS product, orders.quantity
FROM orders
JOIN users ON orders.user_id = users.id
JOIN products ON orders.product_id = products.id
WHERE orders.created > NOW() - INTERVAL '7 days';
-- ———— COUNT and GROUP BY ————————————————————————————————————————————————————
SELECT category, COUNT(*) AS total, AVG(price) AS avg_price
FROM products
GROUP BY category
ORDER BY total DESC;
-- ———— FULL TEXT SEARCH (PostgreSQL specific) ——————————————
SELECT * FROM products
WHERE to_tsvector('english', name) @@ to_tsquery('keyboard');
-- ———— JSON query (JSONB column example) ——————————————————————
SELECT data->>'email' AS email
FROM users
WHERE data->>'role' = 'admin';
Neon's pricing model is usage-based, which is fundamentally different from traditional database hosting that charges a fixed monthly fee regardless of how much you use the service. This makes Neon very cost-effective for development, side projects, and apps with variable or unpredictable traffic — you only pay for what you actually consume.
| Plan | Monthly Cost | Compute | Storage | Branches | History |
|---|---|---|---|---|---|
| Free | $0 | 0.5 CU/month (shared) | 512 MB | 10 branches | 7 days |
| Launch | $19/month | 300 CU/month included | 10 GB included | Unlimited | 14 days |
| Scale | $69/month | 750 CU/month included | 50 GB included | Unlimited | 30 days |
| Business | $700/month | 1,000 CU/month included | 500 GB included | Unlimited | 30 days + SLA |
Neon is not the only modern managed database platform. Here is an honest, detailed comparison of the most popular alternatives to help you choose the right one for your project.
| Feature | Neon | Supabase | PlanetScale | Railway |
|---|---|---|---|---|
| Database type | PostgreSQL | PostgreSQL | MySQL (Vitess) | PostgreSQL, MySQL, Redis |
| Serverless | Yes — scales to zero | Partial — compute pauses on free tier | Yes — fully serverless | No — always-on containers |
| Branching | Yes — instant copy-on-write | No | Yes — schema-level branching | No |
| Free tier storage | 512 MB | 500 MB | 5 GB (recently reduced) | $5/month credit |
| Full PostgreSQL | Yes — 100% compatible | Yes — includes extras (Auth, Storage) | No — MySQL compatible only | Yes |
| Built-in Auth/Storage | No (database only) | Yes — full backend platform | No | No |
| Vercel integration | Official — automatic branch per preview | Good — manual setup | Good | Good |
| Cold start latency | ~200—500ms after idle | ~2—5 seconds after idle (free tier) | Very fast | None — always on |
| Best for | PostgreSQL apps, Next.js, multi-environment workflows | Full-stack apps needing Auth + DB + Storage | MySQL apps needing serverless scale | Consistent-traffic apps, multi-service deployments |
-pooler connection string variant in Next.js API routes and Vercel functions. Direct connections
in serverless environments can exhaust PostgreSQL's max_connections limit.
CREATE INDEX idx_users_email ON users(email); Unindexed queries on large tables will be slow.
Index columns used in WHERE clauses, JOIN conditions, and ORDER BY expressions.
.env.local and .env to your .gitignore. Rotate the
password immediately if you accidentally expose it.?sslmode=require in your connection string and set
ssl: { rejectUnauthorized: false } in pg Pool options.
log: ['query', 'slow'] to your
Prisma client configuration during development to spot slow queries before they become production problems.
Neon's free tier is genuinely free with no credit card required. The free plan includes 512 MB of storage and a monthly compute allocation. If you stay within these limits — which is easy for learning, side projects, and small apps — you will never be charged. Unlike some services that say "free" but bill you after a trial period, Neon's free tier is ongoing. If you want to upgrade for more resources, you choose to do so explicitly. There are no surprise bills on the free tier.
Your data is completely safe. Scaling to zero only affects the compute layer (the PostgreSQL process that executes queries). Your data lives in the storage layer, which is persistent and never goes away. When the next query arrives, Neon wakes up the compute layer, reconnects it to the storage, and executes the query normally. Think of it like a computer going to sleep — the files on the hard drive are fine, you just need to wake the machine up before you can open them.
Absolutely — Neon works with any language or framework that can connect to PostgreSQL. This includes Express, Fastify, NestJS, Django, Flask, FastAPI, Laravel, Ruby on Rails, Spring Boot, and many more. If your framework or ORM supports PostgreSQL, it supports Neon. You just need the connection string from your Neon project dashboard.
Neon uses continuous write-ahead log (WAL) archiving, which means your database is backed up continuously — not just once per day. This is the technology behind Neon's point-in-time restore feature. On the free tier, you can restore to any point within the last 7 days. On paid tiers, the history window extends to 14 or 30 days. You do not need to configure or schedule backups — it happens automatically.
Yes — Neon is used in production by thousands of apps, including ventures backed by Y Combinator and companies processing millions of queries per day. The autoscaling architecture handles traffic spikes gracefully. The main consideration for production use is cold start latency: if your app is accessed infrequently and cold starts of ~300ms are unacceptable, configure a minimum compute size to keep the database warm. On the Launch plan and above, you can set a minimum of 0.25 CUs to virtually eliminate cold starts.
Neon Database represents a genuine evolution in how developers interact with PostgreSQL. By separating compute from storage and embracing a serverless model, Neon removes the traditional barriers to database adoption — no server provisioning, no capacity planning, no maintenance windows — while delivering the full power of PostgreSQL that modern applications depend on.
For beginners, Neon's free tier, built-in SQL editor, and instant setup make it one of the best ways to learn relational databases and SQL without touching a command line or a server configuration file. For experienced developers building production applications, Neon's branching workflow, autoscaling, and Vercel integration represent a meaningful improvement in the development and deployment experience over any managed database service that came before it.
Whether you are building your first CRUD app, launching an AI-powered SaaS, or maintaining a growing startup's data infrastructure — Neon is worth a serious look. Sign up at neon.tech, create a project in 30 seconds, and write your first SQL query. The rest will become clear quickly.