Repository navigation
feat(presets): add neon preset #5181
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rishi-raj-jain
wants to merge
5
commits into
nitrojs:main
Choose a base branch
from
rishi-raj-jain:docs/neon-functions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d8733cf
presets: add neon
rishi-raj-jain f400723
fix(neon): await shutdown work and keep root server entry
rishi-raj-jain 1d522b4
fix(neon): drain in-flight requests before hooks on shutdown
rishi-raj-jain a3c6a51
fix(neon): keep streamed response bodies tracked until they finish
rishi-raj-jain 0ee9f55
fix(neon): track response body cancellation until it settles
rishi-raj-jain File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| # Neon Functions | ||
|
|
||
| > Deploy Nitro apps to Neon Functions. | ||
|
|
||
| **Preset:** `neon` | ||
|
|
||
| :read-more{title="Neon Functions" to="https://neon.com/docs/compute/functions/overview"} | ||
|
|
||
| [Neon Functions](https://neon.com/docs/compute/functions/overview) run Node.js 24 next to your Neon Postgres branch. | ||
|
|
||
| The `neon` preset builds your app into a single function. Nitro serves your routes, server-side rendering, and public assets from it, and maps Nitro features to the Neon runtime: | ||
|
|
||
| | Nitro feature | On Neon Functions | | ||
| | --- | --- | | ||
| | [Public assets](/docs/assets) | Served by the function from disk, with ETags and precompressed variants | | ||
| | [`event.waitUntil`](/docs/lifecycle) | Neon `waitUntil` (up to 15 minutes after the response) | | ||
| | [Database](/docs/database) | The branch's Postgres, with no connection string to configure | | ||
| | [Scheduled tasks](/docs/tasks) | [Neon Function Triggers](https://neon.com/docs/compute/functions/triggers/schedule) | | ||
| | [`shutdown` and `close` hooks](/docs/lifecycle#server-shutdown) | Called on `SIGINT`, before Neon stops an isolate | | ||
|
|
||
| ## Deploy with the Neon CLI | ||
|
|
||
| 1. Install the [Neon CLI](https://neon.com/docs/cli) and link your project to a Neon project and branch. Functions are available in [these regions](https://neon.com/docs/compute/functions/overview). | ||
|
|
||
| ```bash | ||
| npm install -g neon@latest | ||
| neon link | ||
| ``` | ||
|
|
||
| 2. Build your app with the `neon` preset: | ||
|
|
||
| ```bash | ||
| NITRO_PRESET=neon npx nitro build | ||
| ``` | ||
|
|
||
| You can also set `preset: "neon"` in your Nitro config. | ||
|
|
||
| 3. Deploy the `.output` directory as a prebuilt function: | ||
|
|
||
| ```bash | ||
| neon functions deploy myapp --src .output --no-bundle | ||
| ``` | ||
|
|
||
| `myapp` is the function slug. It becomes part of the URL and can't be changed after the first deploy. A slug has 1 to 20 lowercase letters and digits, with no hyphens. | ||
|
|
||
| 4. Get the public URL of your function: | ||
|
|
||
| ```bash | ||
| neon functions get myapp | ||
| ``` | ||
|
|
||
| ::note | ||
| Deploy the whole `.output` directory, not `.output/server`. Nitro writes an `index.mjs` entry at the root of `.output` for Neon Functions to load, and serves public assets from `.output/public`. | ||
| :: | ||
|
|
||
| ## Deploy with `neon.ts` | ||
|
|
||
| To deploy your app with the rest of your Neon config, declare it in [`neon.ts`](https://neon.com/docs/reference/neon-ts) with `bundler: "none"`, so Neon ships the prebuilt output as is: | ||
|
|
||
| ```ts [neon.ts] | ||
| import { defineConfig } from "@neon/config/v1"; | ||
|
|
||
| export default defineConfig({ | ||
| functions: { | ||
| myapp: { | ||
| name: "My Nitro app", | ||
| source: "./.output", | ||
| bundler: "none", | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| Then build and deploy: | ||
|
|
||
| ```bash | ||
| NITRO_PRESET=neon npx nitro build | ||
| neon deploy | ||
| ``` | ||
|
|
||
| ## Environment variables | ||
|
|
||
| Neon injects the branch's service variables into every function at runtime, such as `DATABASE_URL`, `PGHOST`, `PGUSER`, `PGPASSWORD`, and `PGDATABASE`. See [Neon Functions environment variables](https://neon.com/docs/compute/functions/environment-variables). | ||
|
|
||
| Set your own variables at deploy time. Variables with the `NITRO_` prefix override [runtime config](/docs/configuration#runtime-configuration): | ||
|
|
||
| ```bash | ||
| neon functions deploy myapp --src .output --no-bundle --env NITRO_API_TOKEN=secret | ||
| ``` | ||
|
|
||
| ## Database | ||
|
|
||
| When [database](/docs/database) support is enabled, the `neon` preset sets the default connection to the branch's Postgres. The `postgresql` connector reads the variables that Neon injects, so you don't configure a connection string: | ||
|
|
||
| ```ts [nitro.config.ts] | ||
| import { defineConfig } from "nitro"; | ||
|
|
||
| export default defineConfig({ | ||
| preset: "neon", | ||
| experimental: { | ||
| database: true, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| ```ts [routes/users.ts] | ||
| import { defineHandler } from "nitro"; | ||
| import { useDatabase } from "nitro/database"; | ||
|
|
||
| export default defineHandler(async () => { | ||
| const db = useDatabase(); | ||
| const { rows } = await db.sql`SELECT * FROM users LIMIT 10`; | ||
| return rows; | ||
| }); | ||
| ``` | ||
|
|
||
| ::warning | ||
| Don't use SQLite connectors on Neon Functions. The filesystem is read-only outside `/tmp`, and `/tmp` is local to each isolate and lost when the isolate stops. | ||
| :: | ||
|
|
||
| ## WebSockets | ||
|
|
||
| The `neon` preset doesn't support Nitro [WebSockets](/docs/websocket) yet. With `features.websocket` enabled, the build logs a warning, and WebSocket clients get a `426 Upgrade Required` response. | ||
|
|
||
| For one-way, server-to-client updates, stream a response with [server-sent events](https://neon.com/docs/compute/functions/websockets#server-sent-events-sse). | ||
|
|
||
| ## Scheduled tasks | ||
|
|
||
| Neon runs [scheduled tasks](/docs/tasks#scheduled-tasks) with [Function Triggers](https://neon.com/docs/compute/functions/triggers/schedule). For each cron expression in `scheduledTasks`, Nitro writes a function path to `.output/neon.json`: | ||
|
|
||
| ```json [.output/neon.json] | ||
| { | ||
| "triggers": [ | ||
| { | ||
| "cron": "0 3 * * *", | ||
| "functionPath": "/_neon/cron/MCAzICogKiAq", | ||
| "tasks": ["db:cleanup"] | ||
| } | ||
| ] | ||
| } | ||
| ``` | ||
|
|
||
| Create a schedule trigger for each entry, pointing at its `functionPath`: | ||
|
|
||
| ```bash | ||
| neon triggers create --function-slug myapp --name db-cleanup \ | ||
| --cron "0 3 * * *" --function-path /_neon/cron/MCAzICogKiAq | ||
| ``` | ||
|
|
||
| Or declare the triggers in `neon.ts`: | ||
|
|
||
| ```ts [neon.ts] | ||
| import { defineConfig } from "@neon/config/v1"; | ||
|
|
||
| export default defineConfig({ | ||
| functions: { | ||
| myapp: { name: "My Nitro app", source: "./.output", bundler: "none" }, | ||
| }, | ||
| triggers: { | ||
| "db-cleanup": { | ||
| type: "schedule", | ||
| function: "myapp", | ||
| cron: "0 3 * * *", | ||
| functionPath: "/_neon/cron/MCAzICogKiAq", | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| Neon evaluates schedules in UTC and accepts only five numeric fields, so names like `MON`, macros like `@daily`, and a seconds field are rejected. Each task receives the trigger's scheduled time as `payload.scheduledTime`. Nitro rejects requests to these paths that don't come from Neon. | ||
|
|
||
| ## Caching and storage | ||
|
|
||
| Every isolate has its own memory. The default in-memory [KV storage](/docs/storage) and [cache](/docs/cache) are not shared between isolates and are lost when an isolate stops. For data that must persist or be shared, use the branch's Postgres, or mount a KV driver backed by an external service. | ||
|
|
||
| ## Preview locally | ||
|
|
||
| To preview the build locally, run: | ||
|
|
||
| ```bash | ||
| npx srvx --prod .output | ||
| ``` | ||
|
|
||
| `event.waitUntil` and scheduled trigger deliveries need the Neon Functions runtime, so test them on a deployed function. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { defineNitroPreset } from "../_utils/preset.ts"; | ||
| import { warnUnsupportedFeatures, writeNeonOutput } from "./utils.ts"; | ||
|
|
||
| const neon = defineNitroPreset( | ||
| { | ||
| entry: "./neon/runtime/neon", | ||
| serveStatic: true, | ||
| commands: { | ||
| preview: "npx srvx --prod ./", | ||
| deploy: "neon functions deploy <slug> --src ./ --no-bundle", | ||
| }, | ||
| // Neon Functions inject `PGHOST`, `PGUSER`, `PGPASSWORD` and `PGDATABASE` for the | ||
| // branch Postgres, which `pg` reads at runtime. | ||
| database: { | ||
| default: { connector: "postgresql", options: { ssl: true } }, | ||
| }, | ||
| hooks: { | ||
| "build:before"(nitro) { | ||
| warnUnsupportedFeatures(nitro); | ||
| }, | ||
| async compiled(nitro) { | ||
| await writeNeonOutput(nitro); | ||
| }, | ||
| }, | ||
| }, | ||
| { | ||
| name: "neon" as const, | ||
| aliases: ["neon-functions"], | ||
| } | ||
| ); | ||
|
|
||
| export default [neon] as const; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import type { NitroShutdownContext } from "nitro/types"; | ||
| import { useNitroHooks } from "nitro/app"; | ||
|
|
||
| const inflight = new Set<Promise<void>>(); | ||
| let shutdownWaitUntil: NitroShutdownContext["waitUntil"] | undefined; | ||
|
|
||
| /** | ||
| * Keep a shutdown pending until `promise` settles: use it for requests and for the work they | ||
| * register with `waitUntil`. | ||
| */ | ||
| export function trackInflight<T>(promise: Promise<T>): Promise<T> { | ||
| const settled = promise.then( | ||
| () => {}, | ||
| () => {} | ||
| ); | ||
| inflight.add(settled); | ||
| settled.finally(() => inflight.delete(settled)); | ||
| shutdownWaitUntil?.(settled); | ||
| return promise; | ||
| } | ||
|
|
||
| /** | ||
| * Keep a shutdown pending until the response body is fully sent, cancelled or failed. The body | ||
| * is read one chunk at a time as the client pulls it, so it is never buffered. | ||
| */ | ||
| export function trackResponse(response: Response): Response { | ||
| const body = response.body; | ||
| if (!body) { | ||
| return response; | ||
| } | ||
| let settle!: () => void; | ||
| trackInflight(new Promise<void>((resolve) => (settle = resolve))); | ||
| const reader = body.getReader(); | ||
| const tracked = new ReadableStream<Uint8Array>({ | ||
| async pull(controller) { | ||
| try { | ||
| const { done, value } = await reader.read(); | ||
| if (done) { | ||
| settle(); | ||
| controller.close(); | ||
| } else { | ||
| controller.enqueue(value); | ||
| } | ||
| } catch (error) { | ||
| settle(); | ||
| controller.error(error); | ||
| } | ||
| }, | ||
| cancel(reason) { | ||
| // Resolves once the source stream finished its own cancellation cleanup. | ||
| const cancelled = trackInflight(reader.cancel(reason)); | ||
| settle(); | ||
| return cancelled; | ||
| }, | ||
| }); | ||
| return new Response(tracked, { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| headers: response.headers, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Call the Nitro `shutdown` hooks, then wait for in-flight requests and the work registered | ||
| * with `waitUntil` for up to `timeout` milliseconds, then call the `close` hooks. | ||
| * | ||
| * Neon sends `SIGINT` before stopping an isolate and stops it 5 seconds later, so the timeout | ||
| * leaves time for the `close` hooks within that window. | ||
| */ | ||
| export async function shutdownNitro({ timeout }: { timeout: number }): Promise<void> { | ||
| try { | ||
| await callShutdownHooks(timeout); | ||
| await useNitroHooks().callHook("close"); | ||
| } catch (error) { | ||
| console.error("[nitro] Error while shutting down:", error); | ||
| } | ||
| } | ||
|
|
||
| function callShutdownHooks(timeout: number): Promise<void> { | ||
| const controller = new AbortController(); | ||
| return new Promise<void>((resolve) => { | ||
| let pending = 0; | ||
| const timer = setTimeout(() => { | ||
| console.warn(`[nitro] Shutdown did not finish within ${timeout}ms.`); | ||
| controller.abort(); | ||
| resolve(); | ||
| }, timeout); | ||
| const waitUntil: NitroShutdownContext["waitUntil"] = (promise) => { | ||
| pending++; | ||
| Promise.resolve(promise) | ||
| .catch((error) => console.error("[nitro] Error while shutting down:", error)) | ||
| .finally(() => { | ||
| if (--pending === 0) { | ||
| clearTimeout(timer); | ||
| resolve(); | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
| }); | ||
| }; | ||
| shutdownWaitUntil = waitUntil; | ||
| for (const promise of inflight) { | ||
| waitUntil(promise); | ||
| } | ||
| waitUntil( | ||
| Promise.resolve( | ||
| useNitroHooks().callHook("shutdown", { waitUntil, signal: controller.signal }) | ||
| ) | ||
| ); | ||
| }); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.