neon

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Neon

Neon

Important: Neon is no longer just a Serverless Postgres provider. Neon is the backend for apps and agents with Serverless Postgres, Auth, Functions, Storage, and an AI Gateway: instant, branchable, serverless.
Use this skill as the starting point for anything Neon: get an overview of its capabilities, find your way around the Neon agent skills and documentation, and follow best practices for getting started and for branch-first development workflows.
重要提示:Neon不再仅仅是Serverless Postgres提供商。Neon是面向应用与Agent的后端平台,提供Serverless Postgres、Auth、Functions、Storage以及AI Gateway服务:具备即时可用、可分支、无服务器特性。
将本技能作为所有Neon相关操作的起点:了解其功能概览、查找Neon Agent技能与文档、遵循入门最佳实践及分支优先开发工作流。

Platform Services

平台服务

Neon bundles several backend primitives for building apps and agents that all branch together with your project:
  • Postgres — Serverless Postgres that scales and branches with your app. Generally available.
  • Auth — Managed authentication with users and sessions stored in Postgres. Generally available.
  • Object Storage — S3-compatible object storage that branches with your projects. Preview / early access.
  • Compute Functions — Long-running serverless functions running close to your database — for WebSocket servers, long agent HTTP streams, APIs, and server-sent event servers. Preview / early access.
  • AI Gateway — One API for all frontier and open-source models, with routing, logging, and cost controls, powered by Databricks. Preview / early access.
Neon整合了多种后端基础组件,用于构建应用与Agent,且所有组件均可随项目分支同步:
  • Postgres — 可随应用扩展与分支的Serverless Postgres。已正式可用。
  • Auth — 托管式认证服务,用户与会话存储于Postgres中。已正式可用。
  • Object Storage — 与S3兼容的对象存储服务,可随项目分支同步。预览/早期访问阶段。
  • Compute Functions — 运行在数据库附近的长时运行无服务器函数,适用于WebSocket服务器、长时Agent HTTP流、API及服务器发送事件(SSE)服务器。预览/早期访问阶段。
  • AI Gateway — 统一API接口,支持所有前沿及开源模型,具备路由、日志与成本控制功能,由Databricks提供技术支持。预览/早期访问阶段。

Preview Service Availability

预览服务可用性

Object Storage, Compute Functions, and AI Gateway are preview (early access) features.
Early access features are only available on net-new projects created in the
us-east-2
region; they cannot be enabled on existing projects for now. Before guiding a user through any of these services, confirm they are working with a new project in
us-east-2
. If not, they will need to create a new project in that region. Then confirm the user already has early access; otherwise, point them to the private beta sign-up: https://neon.com/blog/were-building-backends#access.
Object Storage、Compute Functions与AI Gateway为预览(早期访问)功能。
早期访问功能仅在
us-east-2
区域创建的全新项目中可用;目前无法在现有项目中启用。在引导用户使用这些服务前,需确认他们正在使用
us-east-2
区域的新项目。若用户未使用该区域项目,需指导其在该区域创建新项目。同时需确认用户已获得早期访问权限;否则,引导其前往私有Beta注册页面:https://neon.com/blog/were-building-backends#access。

Architecture: how Neon fits

架构:Neon的定位

Neon is not a place to host your full-stack app — it's backend primitives (Postgres, Auth, Object Storage, Functions, AI Gateway) that compose with the application platform you already use. Host the app on Vercel (or Netlify, or another frontend/app host); Neon is the backend it talks to.
A typical setup:
  • Full-stack app on Vercel (or Netlify) — e.g. Next.js or TanStack Start. It owns your UI and auth (e.g. Neon Auth) and talks directly to your Neon Postgres database and Neon Object Storage.
  • Reach for Neon Functions when you outgrow the host's limits — a WebSocket or SSE server, or long-running agents that risk timing out on short, lambda-style serverless. Run that one piece on a Neon Function, next to your data.
You can also move your whole backend control plane onto Neon Functions. This is especially useful when the frontend is client-only rather than full-stack — TanStack Router, React Router in client mode, and similar SPAs hosted on Vercel or Netlify. The client talks directly to Neon Functions, where you build REST APIs and request/response agents, host MCP servers, and run anything stateful or that should live close to Postgres and Object Storage. Secure these functions like any standalone REST API — verify a JWT or API key at the top of each handler (see the
neon-functions
skill).
Because Functions are just your backend, they compose with a full-stack app too: if you already have a backend (Next.js route handlers, etc.), Neon Functions sit alongside it, and you can move pieces between the two — e.g. relocate a long-running agent or a stateful WebSocket server off your host onto a Function when it needs more runtime.
Neon 并非全栈应用托管平台——它是后端基础组件(Postgres、Auth、Object Storage、Functions、AI Gateway),可与你已使用的应用平台组合使用。将应用托管在Vercel(或Netlify等前端/应用托管平台);Neon作为其对接的后端。
典型配置:
  • 全栈应用托管于Vercel(或Netlify)——例如Next.js或TanStack Start。负责UI与认证(如Neon Auth),并直接对接Neon Postgres数据库与Neon Object Storage
  • 当现有平台达到限制时,使用Neon Functions——例如WebSocket或SSE服务器,或可能在短时长Lambda式无服务器环境中超时的长时运行Agent。将此类组件部署在Neon Functions上,靠近你的数据。
你也可将整个后端控制平面迁移至Neon Functions。当前端为纯客户端而非全栈应用时(如TanStack Router、客户端模式下的React Router等托管于Vercel或Netlify的SPA),这一方案尤为实用。客户端直接与Neon Functions通信,你可在此构建REST API、请求/响应Agent、托管MCP服务器,并运行任何有状态或需靠近Postgres与Object Storage的服务。像保护独立REST API一样保护这些函数——在每个处理器顶部验证JWT或API密钥(详见
neon-functions
技能)。
由于Functions本质是你的后端,它也可与全栈应用组合使用:若你已有后端(如Next.js路由处理器等),Neon Functions可与其并存,你可在两者间迁移组件——例如当某长时运行Agent或有状态WebSocket服务器需要更长运行时间时,将其从现有平台迁移至Function。

Neon Documentation

Neon文档

The Neon documentation is the source of truth for all Neon-related information. Always verify claims against the official docs before responding. Neon features and APIs evolve, so prefer fetching current docs over relying on training data.
Neon官方文档是所有Neon相关信息的权威来源。在回复前,务必对照官方文档验证相关内容。Neon的功能与API不断演进,因此优先获取最新文档而非依赖训练数据。

Fetching Docs as Markdown

获取Markdown格式文档

Any Neon doc page can be fetched as markdown in two ways:
  1. Append
    .md
    to the URL
    (simplest): https://neon.com/docs/introduction/branching.md
  2. Request
    text/markdown
    on the standard URL:
    curl -H "Accept: text/markdown" https://neon.com/docs/introduction/branching
Both return the same markdown content. Use whichever method your tools support.
任何Neon文档页面均可通过两种方式获取Markdown格式内容:
  1. 在URL后追加
    .md
    (最简单方式):https://neon.com/docs/introduction/branching.md
  2. 在标准URL中请求
    text/markdown
    格式
    curl -H "Accept: text/markdown" https://neon.com/docs/introduction/branching
两种方式返回相同的Markdown内容,可根据工具支持情况选择使用。

Finding the Right Page

查找正确的文档页面

The docs index lists every available page with its URL and a short description:
https://neon.com/docs/llms.txt
Common doc URLs are organized in the topic links below. If you need a page not listed here, search the docs index: https://neon.com/docs/llms.txt. Don't guess URLs.
文档索引列出了所有可用页面的URL及简短描述:
https://neon.com/docs/llms.txt
常见文档URL按主题链接整理如下。若需查找未列出的页面,请搜索文档索引:https://neon.com/docs/llms.txt。请勿猜测URL。

Choosing the Right Skill

选择合适的技能

  • Working with the database, connections, schema, queries, autoscaling, or the CLI/MCP/API →
    neon-postgres
    .
  • Choosing or creating the right branch type for dev, preview, test, or CI workflows →
    neon-postgres-branches
    .
  • Storing and serving files (uploads, images, blobs) that branch with the database →
    neon-object-storage
    .
  • Deploying long-running or streaming serverless functions — APIs, agents, SSE/WebSocket servers — next to the database →
    neon-functions
    .
  • Calling an LLM or routing across model providers with one credential →
    neon-ai-gateway
    .
  • Provisioning instant, claimable temporary Postgres databases (for example, one per end user or demo) →
    claimable-postgres
    .
  • Diagnosing or fixing excessive Postgres egress (network data-transfer) costs in a codebase →
    neon-postgres-egress-optimizer
    .
  • 涉及数据库、连接、 schema、查询、自动扩缩容或CLI/MCP/API → 使用
    neon-postgres
  • 为开发、预览、测试或CI工作流选择或创建合适的分支类型 → 使用
    neon-postgres-branches
  • 存储与提供可随数据库分支同步的文件(上传文件、图片、二进制大对象) → 使用
    neon-object-storage
  • 在数据库附近部署长时运行或流式无服务器函数——API、Agent、SSE/WebSocket服务器 → 使用
    neon-functions
  • 调用LLM或通过单一凭据跨模型提供商路由请求 → 使用
    neon-ai-gateway
  • 预配即时可用、可申领的临时Postgres数据库(例如为每个终端用户或演示创建一个) → 使用
    claimable-postgres
  • 诊断或修复代码库中过高的Postgres出口(网络数据传输)成本 → 使用
    neon-postgres-egress-optimizer

Installing the Right Skill

安装合适的技能

First check whether the target skill is already installed and accessible (for example, it appears in the available skills list or its
SKILL.md
is present). If it is, use it directly. If it is not installed, install it via the
skills
CLI with
npx
/
bunx
:
bash
npx skills add neondatabase/agent-skills -s <skill-name>
Replace
<skill-name>
with the skill you need (for example,
neon-object-storage
,
neon-functions
, or
neon-ai-gateway
). Useful flags:
  • -g
    — install globally instead of into the current project.
  • -y
    — non-interactive mode (skip prompts).
  • -a <agent-name>
    — pick the target agent(s) for non-interactive mode.
For example, to install the object storage skill globally for a specific agent without prompts:
bash
npx skills add neondatabase/agent-skills -s neon-object-storage -g -y -a <agent-name>
首先检查目标技能是否已安装并可用(例如出现在可用技能列表中,或其
SKILL.md
已存在)。若已安装,直接使用;若未安装,通过
skills
CLI结合
npx
/
bunx
安装:
bash
npx skills add neondatabase/agent-skills -s <skill-name>
<skill-name>
替换为所需技能(例如
neon-object-storage
neon-functions
neon-ai-gateway
)。实用参数:
  • -g
    — 全局安装,而非安装到当前项目。
  • -y
    — 非交互模式(跳过提示)。
  • -a <agent-name>
    — 为非交互模式指定目标Agent。
例如,为特定Agent全局安装对象存储技能且跳过提示:
bash
npx skills add neondatabase/agent-skills -s neon-object-storage -g -y -a <agent-name>

Getting Started with Neon

Neon入门指南

Use this section when guiding a user through first-time Neon setup, or when adding a new Neon service (Auth, object storage, functions, and so on) to a project that is already onboarded (for example, one already using Neon Postgres).
当引导用户完成Neon首次设置,或向已使用Neon Postgres的项目添加新Neon服务(Auth、对象存储、函数等)时,使用本节内容。

Check Status Quo

检查现状

Before starting setup, inspect the user's codebase and environment:
  • Existing database connection code
  • Existing
    .neon
    or
    neon.ts
    files in the workspace
  • Existing Neon MCP server or Neon CLI configuration
  • Existence of a
    .env
    file and
    DATABASE_URL
    environment variable
  • Existing ORM (Prisma, Drizzle, TypeORM) configuration
开始设置前,检查用户的代码库与环境:
  • 现有数据库连接代码
  • 工作区中是否存在
    .neon
    neon.ts
    文件
  • 现有Neon MCP服务器或Neon CLI配置
  • 是否存在
    .env
    文件与
    DATABASE_URL
    环境变量
  • 现有ORM(Prisma、Drizzle、TypeORM)配置

Self-Driving Setup With Neon's CLI or MCP Server

使用Neon CLI或MCP Server实现自动化设置

Offer to inspect existing connected Neon projects or create new ones using the Neon CLI or MCP server. If neither is set up yet, run
npx -y neonctl init
. Use
npx -y
to skip the package install prompt. Auth is handled automatically. If the user is not logged in, it opens their browser for OAuth and waits for completion before proceeding.
bash
npx -y neonctl@latest init
This installs the Neon CLI and MCP server globally, installs the VSCode extension (for Cursor/VS Code), and adds the
neon
and
neon-postgres
agent skills to the project.
If
init
is not suitable, the individual steps can be run non-interactively, using the user's preferred package manager (npm, bun, pnpm):
  • CLI:
    npm i -g neonctl
  • Extension:
    cursor --install-extension databricks.neon-local-connect
  • MCP server:
    npx -y add-mcp https://mcp.neon.tech/mcp -g -n Neon -y -a <agent-name>
  • Agent skill:
    npx skills add neondatabase/agent-skills --skill neon-postgres --skill neon --agent <agent-name> -y
Prefer the CLI over the MCP server unless the user instructs otherwise, since it provides more capabilities, including deploying Neon Functions. For full CLI installation options, see https://neon.com/docs/reference/cli-install.md
主动提出使用Neon CLI或MCP Server检查现有已连接的Neon项目或创建新项目。若两者均未设置,运行
npx -y neonctl init
。使用
npx -y
跳过包安装提示。认证过程自动处理:若用户未登录,将打开浏览器进行OAuth认证,并等待完成后继续。
bash
npx -y neonctl@latest init
此命令将全局安装Neon CLI与MCP服务器,安装VSCode扩展(适用于Cursor/VS Code),并向项目添加
neon
neon-postgres
Agent技能。
init
不适用,可使用用户偏好的包管理器(npm、bun、pnpm)非交互地运行各个步骤:
  • CLI:
    npm i -g neonctl
  • 扩展:
    cursor --install-extension databricks.neon-local-connect
  • MCP服务器:
    npx -y add-mcp https://mcp.neon.tech/mcp -g -n Neon -y -a <agent-name>
  • Agent技能:
    npx skills add neondatabase/agent-skills --skill neon-postgres --skill neon --agent <agent-name> -y
除非用户另有指示,否则优先使用CLI而非MCP服务器,因为CLI提供更多功能,包括部署Neon Functions。有关CLI安装的完整选项,请查看https://neon.com/docs/reference/cli-install.md

Setup Flow

设置流程

Once the CLI, MCP server, and agent skills are installed, ensure the local workspace is linked to a Neon project through the
neonctl init
flow. If it isn't, run
npx -y neonctl link
to let the user interactively link a project. This produces a
.neon
file pointing to the organization, project, and branch the user wants to work with.
For each Neon service, consult that component's agent skill for service-specific setup instructions (Functions, Postgres, Object Storage, Gateway, and so on).
安装CLI、MCP服务器与Agent技能后,确保本地工作区通过
neonctl init
流程链接到Neon项目。若未链接,运行
npx -y neonctl link
让用户交互式链接项目。此操作会生成一个
.neon
文件,指向用户想要使用的组织、项目与分支。
对于每个Neon服务,请参考该组件的Agent技能获取服务特定的设置说明(Functions、Postgres、Object Storage、Gateway等)。

Resume Support

恢复设置

If resuming setup, check what's already configured (MCP connection,
.env
with
DATABASE_URL
, dependencies, schema) and continue from the next incomplete step.
若恢复设置,检查已配置的内容(MCP连接、包含
DATABASE_URL
.env
、依赖项、schema),并从下一个未完成的步骤继续。

Security Reminders

安全提示

Remind users to use environment variables for credentials, never commit connection strings, and use least-privilege database roles.
提醒用户使用环境变量存储凭据,切勿提交连接字符串,并使用最小权限数据库角色。

Branch-First Dev Flow

分支优先开发流程

Default to a branch-first loop that mirrors
git
: one isolated Neon branch per feature, so nothing leaks between features and there are no shared connection strings to copy around. Two commands drive it —
link
once per project, then
checkout
per feature — and a third,
env pull
, runs automatically under the hood so the branch you pin is immediately usable:
  • neonctl link
    — Interactively links the workspace to a Neon org, project, and branch, writing the IDs to a git-ignored
    .neon
    file. Run once per project. Once linked, project- and branch-scoped commands no longer need
    --project-id
    or
    --branch
    (for example,
    neonctl branch list
    ).
  • neonctl checkout <branch-name>
    — Creates the branch if it doesn't exist, or checks out the existing one, by updating only the branch pointer in
    .neon
    . Run without a name for an interactive picker. It does not touch code or local Postgres.
  • neonctl env pull
    — Fetches the current branch's Neon environment variables (
    DATABASE_URL
    , …) into your existing
    .env
    , or
    .env.local
    if you don't have one (override the target with
    --file
    ). No branch ID needed; it reads
    .neon
    .
    link
    and
    checkout
    run this for you by default
    , so you rarely call it directly.
Run
link
once when starting on a project, then
checkout
per feature:
bash
neonctl link                     # once; also pulls the linked branch's env
neonctl checkout dev-add-search  # per feature; also pulls the branch's env
Because
link
and
checkout
pull env by default, the branch's
DATABASE_URL
lands in your local
.env
automatically — build against it, then
checkout
the next branch and repeat. As the agent, drive this loop yourself: run
checkout
between tasks to get a fresh, isolated database per feature with no shared state to corrupt.
默认采用镜像
git
的分支优先循环:每个功能对应一个独立的Neon分支,确保功能间无数据泄露,无需共享连接字符串。三个命令驱动该流程——每个项目运行一次
link
,每个功能运行一次
checkout
,第三个命令
env pull
在后台自动运行,确保你选定的分支可立即使用:
  • neonctl link
    — 交互式将工作区链接到Neon组织、项目与分支,将ID写入被git忽略的
    .neon
    文件。每个项目运行一次。链接完成后,项目与分支范围的命令无需再使用
    --project-id
    --branch
    (例如
    neonctl branch list
    )。
  • neonctl checkout <branch-name>
    — 若分支不存在则创建,否则切换到现有分支,仅更新
    .neon
    中的分支指针。不带分支名称运行将弹出交互式选择器。此操作不会修改代码或本地Postgres。
  • neonctl env pull
    — 将当前分支的Neon环境变量(
    DATABASE_URL
    等)提取到现有
    .env
    文件中;若不存在
    .env
    则提取到
    .env.local
    (可使用
    --file
    指定目标文件)。无需分支ID,将从
    .neon
    读取信息。
    link
    checkout
    默认会自动运行此命令
    ,因此你很少需要直接调用它。
项目启动时运行一次
link
,每个功能运行一次
checkout
bash
neonctl link                     # 仅运行一次;同时拉取链接分支的环境变量
neonctl checkout dev-add-search  # 每个功能运行一次;同时拉取分支的环境变量
由于
link
checkout
默认会拉取环境变量,分支的
DATABASE_URL
会自动写入本地
.env
文件——基于此构建代码,然后切换到下一个分支重复操作。作为Agent,可自主驱动此循环:任务间运行
checkout
,为每个功能获取全新的隔离数据库,避免共享状态损坏。

Updating
.neon
without interactive prompts

无需交互式提示更新
.neon

Plain
neonctl link
/
neonctl checkout
prompt interactively, which an agent can't answer. Use one of these non-interactive paths instead:
  • neonctl link --agent
    — a JSON state machine for agents. Each call returns a single JSON object with a
    status
    (
    needs_org
    needs_project
    needs_project_details
    linked
    , or
    error
    ), the available
    options
    , and the exact
    next_command_template
    to run next. Drive it step by step until
    status: "linked"
    . (Errors also come back as JSON with exit code 1, so you can always parse the result.)
  • neonctl set-context --project-id <id> --org-id <id> --branch-id <id>
    — when you already know the IDs, write all three into
    .neon
    in one shot. This is a destructive write: it replaces the file's contents entirely with exactly these fields, so it's the most direct way to point
    .neon
    at a specific org / project / branch.
Both avoid prompts entirely; reach for
set-context
when you have the IDs and
link --agent
when you need to discover them.
普通的
neonctl link
/
neonctl checkout
会弹出交互式提示,Agent无法回答。可使用以下非交互方式替代:
  • neonctl link --agent
    — 面向Agent的JSON状态机。每次调用返回一个JSON对象,包含
    status
    needs_org
    needs_project
    needs_project_details
    linked
    error
    )、可用
    options
    及确切的
    next_command_template
    ,用于下一步操作。逐步执行直到
    status: "linked"
    。(错误也会以JSON格式返回,退出码为1,因此你始终可以解析结果。)
  • neonctl set-context --project-id <id> --org-id <id> --branch-id <id>
    — 当你已知道ID时,可一次性将三个ID写入
    .neon
    。这是破坏性写入:会完全替换文件内容,因此是将
    .neon
    指向特定组织/项目/分支最直接的方式。
两种方式均无提示;若已拥有ID,使用
set-context
;若需发现ID,使用
link --agent

Opting out of local env vars

选择不使用本地环境变量

If env vars are injected at runtime instead of written to disk — or you simply don't want secrets in the working tree — pass
--no-env-pull
to
link
/
checkout
and supply the env another way:
  • neon-env run -- <your dev command>
    (from
    @neondatabase/env
    ) fetches the branch's vars from your
    neon.ts
    and injects them into the child process at runtime — no
    .env
    file needed. This is the runtime counterpart to the on-disk
    env pull
    .
  • neon-env export
    (from
    @neondatabase/env
    ) prints the branch's env to stdout as dotenv lines or, with
    --format json
    , JSON — for piping into another env manager rather than running a command. For example, varlock can bulk-load it from a
    .env.schema
    with
    @setValuesBulk(exec("neon-env export --format json"), format=json)
    .
  • fetchEnv
    from
    @neondatabase/env
    is the programmatic version of the same thing: resolve the branch's env in code at runtime instead of shelling out to
    neon-env run
    .
  • neonctl dev
    injects the same vars into your local dev server — it's part of Neon Functions local development (a private preview feature).
When an agent should not write a local
.env
, instruct it (for example in your
AGENTS.md
) to run
neonctl checkout <branch> --no-env-pull
and rely on runtime injection.
For reading env you already have on disk (typed and validated against your
neon.ts
), use
parseEnv
— see Neon Infrastructure as Code below.
若环境变量在运行时注入而非写入磁盘——或你只是不希望工作区中存在机密信息——可在
link
/
checkout
时添加
--no-env-pull
参数,并通过其他方式提供环境变量:
  • neon-env run -- <your dev command>
    (来自
    @neondatabase/env
    )从
    neon.ts
    拉取分支的变量,并在运行时注入到子进程中——无需
    .env
    文件。这是磁盘操作
    env pull
    的运行时对应方案。
  • neon-env export
    (来自
    @neondatabase/env
    )将分支的环境变量以dotenv行格式或JSON格式(使用
    --format json
    )打印到标准输出——可导入到其他环境管理器而非直接运行命令。例如,varlock可通过
    @setValuesBulk(exec("neon-env export --format json"), format=json)
    .env.schema
    批量加载变量。
  • @neondatabase/env
    中的
    fetchEnv
    是上述功能的程序化版本:在代码运行时解析分支的环境变量,而非通过
    neon-env run
    调用外壳命令。
  • neonctl dev
    将相同变量注入本地开发服务器——这是Neon Functions本地开发的私有预览功能。
当Agent不应写入本地
.env
文件时,需指示其(例如在
AGENTS.md
中)运行
neonctl checkout <branch> --no-env-pull
并依赖运行时注入。
若要读取磁盘上已有的环境变量(根据
neon.ts
进行类型化与验证),使用
parseEnv
——详见下文Neon基础设施即代码

Neon Infrastructure as Code

Neon基础设施即代码

neon.ts
is Neon's branch config and infrastructure-as-code file: declare which Neon services your project's branches should have, get type-safe env vars, and program branch settings — all in TypeScript. It's the config layer for Neon as a platform, and it composes with the branch-first loop above. Add it with
@neondatabase/config
:
bash
npm i @neondatabase/config
typescript
// neon.ts
import { defineConfig } from "@neondatabase/config/v1";

export default defineConfig({
  auth: true,
  dataApi: true,
});
neon.ts
是Neon的分支配置与基础设施即代码文件:在TypeScript中声明项目分支应具备的Neon服务、获取类型安全的环境变量、配置分支设置——所有操作均可在一个文件中完成。它是Neon平台的配置层,可与上述分支优先循环组合使用。通过
@neondatabase/config
添加该文件:
bash
npm i @neondatabase/config
typescript
// neon.ts
import { defineConfig } from "@neondatabase/config/v1";

export default defineConfig({
  auth: true,
  dataApi: true,
});

Provision services with neonctl config

使用neonctl config预配服务

Every project ships with serverless Postgres;
neon.ts
lets you also declare Neon Auth and the Data API today, with Functions, buckets, and the AI Gateway under a
preview
block — every service for the branch composes in one file:
typescript
// neon.ts
export default defineConfig({
  auth: true,
  dataApi: true,
  preview: {
    functions: { /* ... */ }, // see the neon-functions skill
    buckets: { /* ... */ },    // see the neon-object-storage skill
    aiGateway: true,           // see the neon-ai-gateway skill
  },
});
Reconcile the declaration from the CLI — the Neon equivalent of
terraform status
/
plan
/
apply
:
bash
neonctl config status   # print the branch's live config (read-only)
neonctl config plan     # dry-run diff of what apply would change (read-only)
neonctl config apply    # provision the declared services
neonctl deploy          # alias for `neonctl config apply`
config status
and
config plan
only read state.
apply
/
deploy
— like
link
and
checkout
— provision the declared services and then pull the branch's env into your local
.env.local
(e.g.
Pulled 5 Neon variables into .env.local: DATABASE_URL, …
), so your local env always matches what's deployed.
每个项目默认包含Serverless Postgres;
neon.ts
允许你同时声明Neon Auth与Data API,Functions、存储桶与AI Gateway则放在
preview
块中——分支的所有服务均可在一个文件中组合:
typescript
// neon.ts
export default defineConfig({
  auth: true,
  dataApi: true,
  preview: {
    functions: { /* ... */ }, // 详见neon-functions技能
    buckets: { /* ... */ },    // 详见neon-object-storage技能
    aiGateway: true,           // 详见neon-ai-gateway技能
  },
});
通过CLI协调声明内容——相当于Neon版本的
terraform status
/
plan
/
apply
bash
neonctl config status   # 打印分支的实时配置(只读)
neonctl config plan     # 试运行apply操作的差异(只读)
neonctl config apply    # 预配声明的服务
neonctl deploy          # `neonctl config apply`的别名
config status
config plan
仅读取状态。
apply
/
deploy
——与
link
checkout
类似——会预配声明的服务并将分支的环境变量拉取到本地
.env.local
(例如
Pulled 5 Neon variables into .env.local: DATABASE_URL, …
),确保本地环境始终与部署内容一致。

Type-safe env vars with parseEnv

使用parseEnv获取类型安全的环境变量

@neondatabase/env
's
parseEnv
takes your
neon.ts
config object and returns a parsed, typed env object, validated against the services you declared. The shape of
env
follows your config — enable
auth
and you get
env.auth
, enable
dataApi
and you get
env.dataApi
— and missing variables are flagged with clear errors (for you and your agents). Use it to read env you already have (typically pulled into
.env
by
checkout
/
env pull
); for fetching env at runtime without a file, reach for
fetchEnv
/
neon-env run
instead.
bash
npm i @neondatabase/env
typescript
import { parseEnv } from "@neondatabase/env/v1";
import config from "./neon";

const env = parseEnv(config);

console.log(env.postgres.databaseUrl);
console.log(env.auth.baseUrl);
By default
parseEnv
requires every variable your config implies. When a process only uses a subset — a common case in frameworks like Next.js, where you might read
DATABASE_URL
but never the unpooled URL — pass an array of env-var keys to require and return only those. The keys are typesafe: autocomplete only offers variables your config enables, and the returned shape is narrowed to exactly what you selected (so unselected variables are neither enforced nor present).
typescript
import { parseEnv } from "@neondatabase/env/v1";
import config from "./neon";

// Only DATABASE_URL is required and returned; DATABASE_URL_UNPOOLED is not enforced.
const { postgres } = parseEnv(config, ["DATABASE_URL"]);
console.log(postgres.databaseUrl);

// Selecting across services — only these keys are validated/returned.
const env = parseEnv(config, ["DATABASE_URL", "NEON_AUTH_BASE_URL"]);
console.log(env.postgres.databaseUrl, env.auth.baseUrl);
@neondatabase/env
parseEnv
接收你的
neon.ts
配置对象,返回经过解析、类型化的环境对象,并根据你声明的服务进行验证。
env
的结构与你的配置一致——启用
auth
则得到
env.auth
,启用
dataApi
则得到
env.dataApi
——缺失的变量会触发清晰的错误提示(面向你与Agent)。使用它读取已有的环境变量(通常由
checkout
/
env pull
拉取到
.env
中);若需在运行时无需文件即可获取环境变量,使用
fetchEnv
/
neon-env run
bash
npm i @neondatabase/env
typescript
import { parseEnv } from "@neondatabase/env/v1";
import config from "./neon";

const env = parseEnv(config);

console.log(env.postgres.databaseUrl);
console.log(env.auth.baseUrl);
默认情况下,
parseEnv
要求配置中隐含的所有变量。当进程仅使用子集时——在Next.js等框架中常见,例如你可能读取
DATABASE_URL
但从不使用非池化URL——可传入环境变量键数组,仅要求并返回这些变量。键是类型安全的:自动补全仅提供配置启用的变量,返回的结构会缩小到你选择的变量(因此未选择的变量既不强制要求也不会出现)。
typescript
import { parseEnv } from "@neondatabase/env/v1";
import config from "./neon";

// 仅要求并返回DATABASE_URL;不强制要求DATABASE_URL_UNPOOLED。
const { postgres } = parseEnv(config, ["DATABASE_URL"]);
console.log(postgres.databaseUrl);

// 跨服务选择变量——仅验证/返回这些键。
const env = parseEnv(config, ["DATABASE_URL", "NEON_AUTH_BASE_URL"]);
console.log(env.postgres.databaseUrl, env.auth.baseUrl);

How checkout composes with neon.ts

checkout与neon.ts的组合方式

When a
neon.ts
is present,
neonctl checkout
applies your policy as it creates a branch, so a fresh branch comes up with its declared settings and services already in place. Checking out an existing branch never reconciles it — apply config changes to it explicitly with
neonctl config apply
(or
neonctl deploy
). The bundled
env pull
also checks
neon.ts
against the linked branch and fails fast if the branch is missing a declared service, pointing you at
neonctl deploy
to provision it, so your local env and the remote branch never drift apart silently.
当存在
neon.ts
时,
neonctl checkout
创建分支时应用你的策略,因此新分支创建后会立即具备声明的设置与服务。切换到现有分支时不会自动协调配置——需显式使用
neonctl config apply
(或
neonctl deploy
)将配置变更应用到现有分支。自动运行的
env pull
也会检查
neon.ts
与链接分支是否匹配,若分支缺失声明的服务则快速失败,并引导你运行
neonctl deploy
预配服务,确保本地环境与远程分支不会悄然偏离。

Branch configuration

分支配置

Beyond services,
neon.ts
can program what configuration new branches receive via the
branch
property — a function of the branch being evaluated that returns its settings:
typescript
// neon.ts
import { defineConfig } from "@neondatabase/config/v1";

export default defineConfig({
  auth: true,
  dataApi: true,
  branch: (branch) => {
    if (branch.exists) {
      // leave existing branches untouched
      return {};
    }
    if (branch.name.startsWith("dev")) {
      return {
        ttl: "7d", // clean up the branch after 7 days
        postgres: {
          computeSettings: {
            autoscalingLimitMinCu: 0.25, // scale to zero
            autoscalingLimitMaxCu: 1, // keep it cheap
            suspendTimeout: "5m",
          },
        },
      };
    }
    return {};
  },
});
The
branch
function receives the target branch (its
name
, whether it
exists
yet, whether it's the default, and more) and returns the tuning you want. Here new
dev-*
branches get a 7-day TTL so they clean themselves up, plus a cheap scale-to-zero compute profile, while existing branches and everything else fall through to the defaults. Because
neonctl checkout
applies this policy on create, a fresh
dev-*
branch comes up with these settings already in place.
除服务外,
neon.ts
可通过
branch
属性配置分支的设置——该属性是一个函数,接收待评估的分支并返回其设置:
typescript
// neon.ts
import { defineConfig } from "@neondatabase/config/v1";

export default defineConfig({
  auth: true,
  dataApi: true,
  branch: (branch) => {
    if (branch.exists) {
      // 不修改现有分支
      return {};
    }
    if (branch.name.startsWith("dev")) {
      return {
        ttl: "7d", // 7天后自动清理分支
        postgres: {
          computeSettings: {
            autoscalingLimitMinCu: 0.25, // 缩容至零
            autoscalingLimitMaxCu: 1, // 控制成本
            suspendTimeout: "5m",
          },
        },
      };
    }
    return {};
  },
});
branch
函数接收目标分支(包含
name
、是否
exists
、是否为默认分支等信息)并返回你想要的配置。在此示例中,新的
dev-*
分支会设置7天TTL以自动清理,同时配置低成本的缩容至零计算配置,而现有分支及其他分支则使用默认设置。由于
neonctl checkout
在创建分支时应用此策略,新的
dev-*
分支创建后会立即具备这些设置。

Type-safe config: invalid setups don't compile

类型安全配置:无效设置无法编译

Because
neon.ts
is TypeScript, the compiler catches invalid infrastructure before you ever deploy — and Neon encodes the actual rules (and their fixes) into the types, so the error tells you what to do rather than failing with a useless
Type 'true' is not assignable to type 'never'
. The canonical case: the Data API verifies requests with Neon Auth by default, so enabling it on its own is a type error on
dataApi
:
typescript
export default defineConfig({
  dataApi: true, // type error: `dataApi` (default authProvider 'neon') requires Neon Auth
});
The message names both fixes, so pick one:
typescript
// 1. Enable Neon Auth (the default Data API auth provider):
export default defineConfig({ auth: true, dataApi: true });

// 2. Or verify a third-party IdP instead of Neon Auth:
export default defineConfig({
  dataApi: { authProvider: "external", jwksUrl: "https://your-idp/.well-known/jwks.json" },
});
Treat a
neon.ts
type error as the config telling you which services must go together — read the message, it spells out the valid combinations.
由于
neon.ts
是TypeScript文件,编译器会在部署前捕获无效的基础设施配置——Neon将实际规则(及修复方案)编码到类型中,因此错误提示会告诉你具体操作,而非返回无用的
Type 'true' is not assignable to type 'never'
错误。典型案例:Data API默认使用Neon Auth验证请求,因此单独启用Data API会在
dataApi
上触发类型错误:
typescript
export default defineConfig({
  dataApi: true, // 类型错误:`dataApi`(默认authProvider为'neon')需要启用Neon Auth
});
错误提示会列出两种修复方案,你可任选其一:
typescript
// 1. 启用Neon Auth(Data API默认的认证提供商):
export default defineConfig({ auth: true, dataApi: true });

// 2. 使用第三方IdP而非Neon Auth进行验证:
export default defineConfig({
  dataApi: { authProvider: "external", jwksUrl: "https://your-idp/.well-known/jwks.json" },
});
neon.ts
的类型错误视为配置告诉你哪些服务必须组合使用——阅读错误提示,它会列出有效的组合方式。

Gotchas

常见问题

Neon Auth: "invalid domain"

Neon Auth:“invalid domain”(无效域名)

Neon Auth only redirects back to domains on its trusted-domains list. Anytime the domain your app runs on changes — a new production custom domain, a new deploy/preview URL, moving from
localhost
to a hosted environment, and so on — you must register the new domain with Neon Auth. Otherwise sign-in and OAuth callbacks fail with an
invalid domain
error because the redirect target isn't trusted.
The easiest way to fix this is the CLI. With the workspace linked to the project (see the branch-first flow above), add the new domain to the trusted list:
bash
neonctl neon-auth domain add <domain>   # e.g. neonctl neon-auth domain add https://app.example.com
neonctl neon-auth domain list           # verify what's currently trusted
neonctl neon-auth domain delete <domain> # remove one you no longer use
If the workspace isn't linked, pass
--project-id <id>
(and
--branch <id|name>
) explicitly. For local development,
neonctl neon-auth domain allow-localhost
manages whether
localhost
is permitted. Register the domain before pointing users at the new URL, so they never hit the
invalid domain
error.
Neon Auth仅重定向到其可信域名列表中的域名。每当应用运行的域名变更时——例如新的生产自定义域名、新的部署/预览URL、从
localhost
迁移到托管环境等——你必须向Neon Auth注册新域名。否则,登录与OAuth回调会失败并返回**
invalid domain
**错误,因为重定向目标不在可信列表中。
最简单的修复方式是使用CLI。当工作区已链接到项目(详见分支优先流程),将新域名添加到可信列表:
bash
neonctl neon-auth domain add <domain>   # 例如:neonctl neon-auth domain add https://app.example.com
neonctl neon-auth domain list           # 验证当前可信域名
neonctl neon-auth domain delete <domain> # 删除不再使用的域名
若工作区未链接,需显式传入
--project-id <id>
(及
--branch <id|name>
)。对于本地开发,
neonctl neon-auth domain allow-localhost
用于管理是否允许
localhost
。在引导用户访问新URL前注册域名,避免用户遇到
invalid domain
错误。