neon
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNeon
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 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 . 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.
us-east-2us-east-2Object Storage、Compute Functions与AI Gateway为预览(早期访问)功能。
早期访问功能仅在区域创建的全新项目中可用;目前无法在现有项目中启用。在引导用户使用这些服务前,需确认他们正在使用区域的新项目。若用户未使用该区域项目,需指导其在该区域创建新项目。同时需确认用户已获得早期访问权限;否则,引导其前往私有Beta注册页面:https://neon.com/blog/were-building-backends#access。
us-east-2us-east-2Architecture: 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 skill).
neon-functionsBecause 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:
- Append to the URL (simplest): https://neon.com/docs/introduction/branching.md
.md - Request on the standard URL:
text/markdowncurl -H "Accept: text/markdown" https://neon.com/docs/introduction/branching
Both return the same markdown content. Use whichever method your tools support.
任何Neon文档页面均可通过两种方式获取Markdown格式内容:
- 在URL后追加(最简单方式):https://neon.com/docs/introduction/branching.md
.md - 在标准URL中请求格式:
text/markdowncurl -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.txtCommon 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 is present). If it is, use it directly. If it is not installed, install it via the CLI with /:
SKILL.mdskillsnpxbunxbash
npx skills add neondatabase/agent-skills -s <skill-name>Replace with the skill you need (for example, , , or ). Useful flags:
<skill-name>neon-object-storageneon-functionsneon-ai-gateway- — install globally instead of into the current project.
-g - — non-interactive mode (skip prompts).
-y - — pick the target agent(s) for non-interactive mode.
-a <agent-name>
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>首先检查目标技能是否已安装并可用(例如出现在可用技能列表中,或其已存在)。若已安装,直接使用;若未安装,通过 CLI结合/安装:
SKILL.mdskillsnpxbunxbash
npx skills add neondatabase/agent-skills -s <skill-name>将替换为所需技能(例如、或)。实用参数:
<skill-name>neon-object-storageneon-functionsneon-ai-gateway- — 全局安装,而非安装到当前项目。
-g - — 非交互模式(跳过提示)。
-y - — 为非交互模式指定目标Agent。
-a <agent-name>
例如,为特定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 or
.neonfiles in the workspaceneon.ts - Existing Neon MCP server or Neon CLI configuration
- Existence of a file and
.envenvironment variableDATABASE_URL - 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 . Use 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.
npx -y neonctl initnpx -ybash
npx -y neonctl@latest initThis installs the Neon CLI and MCP server globally, installs the VSCode extension (for Cursor/VS Code), and adds the and agent skills to the project.
neonneon-postgresIf is not suitable, the individual steps can be run non-interactively, using the user's preferred package manager (npm, bun, pnpm):
init- 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项目或创建新项目。若两者均未设置,运行。使用跳过包安装提示。认证过程自动处理:若用户未登录,将打开浏览器进行OAuth认证,并等待完成后继续。
npx -y neonctl initnpx -ybash
npx -y neonctl@latest init此命令将全局安装Neon CLI与MCP服务器,安装VSCode扩展(适用于Cursor/VS Code),并向项目添加与 Agent技能。
neonneon-postgres若不适用,可使用用户偏好的包管理器(npm、bun、pnpm)非交互地运行各个步骤:
init- 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 flow. If it isn't, run to let the user interactively link a project. This produces a file pointing to the organization, project, and branch the user wants to work with.
neonctl initnpx -y neonctl link.neonFor 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技能后,确保本地工作区通过流程链接到Neon项目。若未链接,运行让用户交互式链接项目。此操作会生成一个文件,指向用户想要使用的组织、项目与分支。
neonctl initnpx -y neonctl link.neon对于每个Neon服务,请参考该组件的Agent技能获取服务特定的设置说明(Functions、Postgres、Object Storage、Gateway等)。
Resume Support
恢复设置
If resuming setup, check what's already configured (MCP connection, with , dependencies, schema) and continue from the next incomplete step.
.envDATABASE_URL若恢复设置,检查已配置的内容(MCP连接、包含的、依赖项、schema),并从下一个未完成的步骤继续。
DATABASE_URL.envSecurity 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 : 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 — once per project, then per feature — and a third, , runs automatically under the hood so the branch you pin is immediately usable:
gitlinkcheckoutenv pull- — Interactively links the workspace to a Neon org, project, and branch, writing the IDs to a git-ignored
neonctl linkfile. Run once per project. Once linked, project- and branch-scoped commands no longer need.neonor--project-id(for example,--branch).neonctl branch list - — Creates the branch if it doesn't exist, or checks out the existing one, by updating only the branch pointer in
neonctl checkout <branch-name>. Run without a name for an interactive picker. It does not touch code or local Postgres..neon - — Fetches the current branch's Neon environment variables (
neonctl env pull, …) into your existingDATABASE_URL, or.envif you don't have one (override the target with.env.local). No branch ID needed; it reads--file..neonandlinkrun this for you by default, so you rarely call it directly.checkout
Run once when starting on a project, then per feature:
linkcheckoutbash
neonctl link # once; also pulls the linked branch's env
neonctl checkout dev-add-search # per feature; also pulls the branch's envBecause and pull env by default, the branch's lands in your local automatically — build against it, then the next branch and repeat. As the agent, drive this loop yourself: run between tasks to get a fresh, isolated database per feature with no shared state to corrupt.
linkcheckoutDATABASE_URL.envcheckoutcheckout默认采用镜像的分支优先循环:每个功能对应一个独立的Neon分支,确保功能间无数据泄露,无需共享连接字符串。三个命令驱动该流程——每个项目运行一次,每个功能运行一次,第三个命令在后台自动运行,确保你选定的分支可立即使用:
gitlinkcheckoutenv pull- — 交互式将工作区链接到Neon组织、项目与分支,将ID写入被git忽略的
neonctl link文件。每个项目运行一次。链接完成后,项目与分支范围的命令无需再使用.neon或--project-id(例如--branch)。neonctl branch list - — 若分支不存在则创建,否则切换到现有分支,仅更新
neonctl checkout <branch-name>中的分支指针。不带分支名称运行将弹出交互式选择器。此操作不会修改代码或本地Postgres。.neon - — 将当前分支的Neon环境变量(
neonctl env pull等)提取到现有DATABASE_URL文件中;若不存在.env则提取到.env(可使用.env.local指定目标文件)。无需分支ID,将从--file读取信息。.neon与link默认会自动运行此命令,因此你很少需要直接调用它。checkout
项目启动时运行一次,每个功能运行一次:
linkcheckoutbash
neonctl link # 仅运行一次;同时拉取链接分支的环境变量
neonctl checkout dev-add-search # 每个功能运行一次;同时拉取分支的环境变量由于与默认会拉取环境变量,分支的会自动写入本地文件——基于此构建代码,然后切换到下一个分支重复操作。作为Agent,可自主驱动此循环:任务间运行,为每个功能获取全新的隔离数据库,避免共享状态损坏。
linkcheckoutDATABASE_URL.envcheckoutUpdating .neon
without interactive prompts
.neon无需交互式提示更新.neon
.neonPlain / prompt interactively, which an agent can't answer. Use one of these non-interactive paths instead:
neonctl linkneonctl checkout- — a JSON state machine for agents. Each call returns a single JSON object with a
neonctl link --agent(status→needs_org→needs_project→needs_project_details, orlinked), the availableerror, and the exactoptionsto run next. Drive it step by step untilnext_command_template. (Errors also come back as JSON with exit code 1, so you can always parse the result.)status: "linked" - — when you already know the IDs, write all three into
neonctl set-context --project-id <id> --org-id <id> --branch-id <id>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.neonat a specific org / project / branch..neon
Both avoid prompts entirely; reach for when you have the IDs and when you need to discover them.
set-contextlink --agent普通的 / 会弹出交互式提示,Agent无法回答。可使用以下非交互方式替代:
neonctl linkneonctl checkout- — 面向Agent的JSON状态机。每次调用返回一个JSON对象,包含
neonctl link --agent(status→needs_org→needs_project→needs_project_details或linked)、可用error及确切的options,用于下一步操作。逐步执行直到next_command_template。(错误也会以JSON格式返回,退出码为1,因此你始终可以解析结果。)status: "linked" - — 当你已知道ID时,可一次性将三个ID写入
neonctl set-context --project-id <id> --org-id <id> --branch-id <id>。这是破坏性写入:会完全替换文件内容,因此是将.neon指向特定组织/项目/分支最直接的方式。.neon
两种方式均无提示;若已拥有ID,使用;若需发现ID,使用。
set-contextlink --agentOpting 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 to / and supply the env another way:
--no-env-pulllinkcheckout- (from
neon-env run -- <your dev command>) fetches the branch's vars from your@neondatabase/envand injects them into the child process at runtime — noneon.tsfile needed. This is the runtime counterpart to the on-disk.env.env pull - (from
neon-env export) prints the branch's env to stdout as dotenv lines or, with@neondatabase/env, JSON — for piping into another env manager rather than running a command. For example, varlock can bulk-load it from a--format jsonwith.env.schema.@setValuesBulk(exec("neon-env export --format json"), format=json) - from
fetchEnvis the programmatic version of the same thing: resolve the branch's env in code at runtime instead of shelling out to@neondatabase/env.neon-env run - injects the same vars into your local dev server — it's part of Neon Functions local development (a private preview feature).
neonctl dev
When an agent should not write a local , instruct it (for example in your ) to run and rely on runtime injection.
.envAGENTS.mdneonctl checkout <branch> --no-env-pullFor reading env you already have on disk (typed and validated against your ), use — see Neon Infrastructure as Code below.
neon.tsparseEnv若环境变量在运行时注入而非写入磁盘——或你只是不希望工作区中存在机密信息——可在 / 时添加参数,并通过其他方式提供环境变量:
linkcheckout--no-env-pull- (来自
neon-env run -- <your dev command>)从@neondatabase/env拉取分支的变量,并在运行时注入到子进程中——无需neon.ts文件。这是磁盘操作.env的运行时对应方案。env pull - (来自
neon-env export)将分支的环境变量以dotenv行格式或JSON格式(使用@neondatabase/env)打印到标准输出——可导入到其他环境管理器而非直接运行命令。例如,varlock可通过--format json从@setValuesBulk(exec("neon-env export --format json"), format=json)批量加载变量。.env.schema - 中的
@neondatabase/env是上述功能的程序化版本:在代码运行时解析分支的环境变量,而非通过fetchEnv调用外壳命令。neon-env run - 将相同变量注入本地开发服务器——这是Neon Functions本地开发的私有预览功能。
neonctl dev
当Agent不应写入本地文件时,需指示其(例如在中)运行并依赖运行时注入。
.envAGENTS.mdneonctl checkout <branch> --no-env-pullNeon Infrastructure as Code
Neon基础设施即代码
neon.ts@neondatabase/configbash
npm i @neondatabase/configtypescript
// neon.ts
import { defineConfig } from "@neondatabase/config/v1";
export default defineConfig({
auth: true,
dataApi: true,
});neon.ts@neondatabase/configbash
npm i @neondatabase/configtypescript
// 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; lets you also declare Neon Auth and the Data API today, with Functions, buckets, and the AI Gateway under a block — every service for the branch composes in one file:
neon.tspreviewtypescript
// 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 statusplanapplybash
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 statusconfig planapplydeploylinkcheckout.env.localPulled 5 Neon variables into .env.local: DATABASE_URL, …每个项目默认包含Serverless Postgres;允许你同时声明Neon Auth与Data API,Functions、存储桶与AI Gateway则放在块中——分支的所有服务均可在一个文件中组合:
neon.tspreviewtypescript
// 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 statusplanapplybash
neonctl config status # 打印分支的实时配置(只读)
neonctl config plan # 试运行apply操作的差异(只读)
neonctl config apply # 预配声明的服务
neonctl deploy # `neonctl config apply`的别名config statusconfig planapplydeploylinkcheckout.env.localPulled 5 Neon variables into .env.local: DATABASE_URL, …Type-safe env vars with parseEnv
使用parseEnv获取类型安全的环境变量
@neondatabase/envparseEnvneon.tsenvauthenv.authdataApienv.dataApi.envcheckoutenv pullfetchEnvneon-env runbash
npm i @neondatabase/envtypescript
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 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 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).
parseEnvDATABASE_URLtypescript
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/envparseEnvneon.tsenvauthenv.authdataApienv.dataApicheckoutenv pull.envfetchEnvneon-env runbash
npm i @neondatabase/envtypescript
import { parseEnv } from "@neondatabase/env/v1";
import config from "./neon";
const env = parseEnv(config);
console.log(env.postgres.databaseUrl);
console.log(env.auth.baseUrl);默认情况下,要求配置中隐含的所有变量。当进程仅使用子集时——在Next.js等框架中常见,例如你可能读取但从不使用非池化URL——可传入环境变量键数组,仅要求并返回这些变量。键是类型安全的:自动补全仅提供配置启用的变量,返回的结构会缩小到你选择的变量(因此未选择的变量既不强制要求也不会出现)。
parseEnvDATABASE_URLtypescript
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 is present, 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 (or ). The bundled also checks against the linked branch and fails fast if the branch is missing a declared service, pointing you at to provision it, so your local env and the remote branch never drift apart silently.
neon.tsneonctl checkoutneonctl config applyneonctl deployenv pullneon.tsneonctl deploy当存在时,在创建分支时应用你的策略,因此新分支创建后会立即具备声明的设置与服务。切换到现有分支时不会自动协调配置——需显式使用(或)将配置变更应用到现有分支。自动运行的也会检查与链接分支是否匹配,若分支缺失声明的服务则快速失败,并引导你运行预配服务,确保本地环境与远程分支不会悄然偏离。
neon.tsneonctl checkoutneonctl config applyneonctl deployenv pullneon.tsneonctl deployBranch configuration
分支配置
Beyond services, can program what configuration new branches receive via the property — a function of the branch being evaluated that returns its settings:
neon.tsbranchtypescript
// 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 function receives the target branch (its , whether it yet, whether it's the default, and more) and returns the tuning you want. Here new 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 applies this policy on create, a fresh branch comes up with these settings already in place.
branchnameexistsdev-*neonctl checkoutdev-*除服务外,可通过属性配置新分支的设置——该属性是一个函数,接收待评估的分支并返回其设置:
neon.tsbranchtypescript
// 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 {};
},
});branchnameexistsdev-*neonctl checkoutdev-*Type-safe config: invalid setups don't compile
类型安全配置:无效设置无法编译
Because 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 . The canonical case: the Data API verifies requests with Neon Auth by default, so enabling it on its own is a type error on :
neon.tsType 'true' is not assignable to type 'never'dataApitypescript
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 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将实际规则(及修复方案)编码到类型中,因此错误提示会告诉你具体操作,而非返回无用的错误。典型案例:Data API默认使用Neon Auth验证请求,因此单独启用Data API会在上触发类型错误:
neon.tsType 'true' is not assignable to type 'never'dataApitypescript
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.tsGotchas
常见问题
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 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 error because the redirect target isn't trusted.
localhostinvalid domainThe 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 useIf the workspace isn't linked, pass (and ) explicitly. For local development, manages whether is permitted. Register the domain before pointing users at the new URL, so they never hit the error.
--project-id <id>--branch <id|name>neonctl neon-auth domain allow-localhostlocalhostinvalid domainNeon Auth仅重定向到其可信域名列表中的域名。每当应用运行的域名变更时——例如新的生产自定义域名、新的部署/预览URL、从迁移到托管环境等——你必须向Neon Auth注册新域名。否则,登录与OAuth回调会失败并返回****错误,因为重定向目标不在可信列表中。
localhostinvalid 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> # 删除不再使用的域名若工作区未链接,需显式传入(及)。对于本地开发,用于管理是否允许。在引导用户访问新URL前注册域名,避免用户遇到错误。
--project-id <id>--branch <id|name>neonctl neon-auth domain allow-localhostlocalhostinvalid domain