Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/2.deploy/0.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ When deploying to production using CI/CD, Nitro tries to detect the provider env
For Turborepo users, its Strict Environment Mode can interfere with zero-config detection. You may need to allow the detection variables explicitly or use Loose Environment Mode (the `--env-mode=loose` flag).
::

Other built-in providers are available with an explicit preset, including [Zephyr](/deploy/providers/zephyr).
Other built-in providers are available with an explicit preset, including [Neon Functions](/deploy/providers/neon) and [Zephyr](/deploy/providers/zephyr).

## Changing the deployment preset

Expand Down
184 changes: 184 additions & 0 deletions docs/2.deploy/20.providers/neon.md
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.
2 changes: 2 additions & 0 deletions src/presets/_all.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import _genezio from "./genezio/preset.ts";
import _heroku from "./heroku/preset.ts";
import _iis from "./iis/preset.ts";
import _koyeb from "./koyeb/preset.ts";
import _neon from "./neon/preset.ts";
import _netlify from "./netlify/preset.ts";
import _node from "./node/preset.ts";
import _renderCom from "./render.com/preset.ts";
Expand Down Expand Up @@ -48,6 +49,7 @@ export default [
..._heroku,
..._iis,
..._koyeb,
..._neon,
..._netlify,
..._node,
..._renderCom,
Expand Down
4 changes: 2 additions & 2 deletions src/presets/_types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ export interface PresetOptions {

export const presetsWithConfig = ["awsAmplify","awsLambda","azure","cloudflare","firebase","iis","netlify","vercel","zephyr"] as const;

export type PresetName = "alwaysdata" | "aws-amplify" | "aws-lambda" | "azure-swa" | "base-worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflare-durable" | "cloudflare-module" | "cloudflare-pages" | "cloudflare-pages-static" | "deno" | "deno-server" | "digital-ocean" | "edgeone" | "edgeone-pages" | "firebase-app-hosting" | "flight-control" | "genezio" | "github-pages" | "gitlab-pages" | "heroku" | "iis-handler" | "iis-node" | "koyeb" | "netlify" | "netlify-edge" | "netlify-static" | "nitro-dev" | "nitro-prerender" | "nitro-serve" | "node" | "node-cluster" | "node-middleware" | "node-server" | "platform-sh" | "render-com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercel-static" | "zeabur" | "zeabur-static" | "zephyr" | "zerops" | "zerops-static";
export type PresetName = "alwaysdata" | "aws-amplify" | "aws-lambda" | "azure-swa" | "base-worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflare-durable" | "cloudflare-module" | "cloudflare-pages" | "cloudflare-pages-static" | "deno" | "deno-server" | "digital-ocean" | "edgeone" | "edgeone-pages" | "firebase-app-hosting" | "flight-control" | "genezio" | "github-pages" | "gitlab-pages" | "heroku" | "iis-handler" | "iis-node" | "koyeb" | "neon" | "neon-functions" | "netlify" | "netlify-edge" | "netlify-static" | "nitro-dev" | "nitro-prerender" | "nitro-serve" | "node" | "node-cluster" | "node-middleware" | "node-server" | "platform-sh" | "render-com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercel-static" | "zeabur" | "zeabur-static" | "zephyr" | "zerops" | "zerops-static";

export type PresetNameInput = "alwaysdata" | "aws-amplify" | "awsAmplify" | "aws_amplify" | "aws-lambda" | "awsLambda" | "aws_lambda" | "azure-swa" | "azureSwa" | "azure_swa" | "base-worker" | "baseWorker" | "base_worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflareDev" | "cloudflare_dev" | "cloudflare-durable" | "cloudflareDurable" | "cloudflare_durable" | "cloudflare-module" | "cloudflareModule" | "cloudflare_module" | "cloudflare-pages" | "cloudflarePages" | "cloudflare_pages" | "cloudflare-pages-static" | "cloudflarePagesStatic" | "cloudflare_pages_static" | "deno" | "deno-server" | "denoServer" | "deno_server" | "digital-ocean" | "digitalOcean" | "digital_ocean" | "edgeone" | "edgeone-pages" | "edgeonePages" | "edgeone_pages" | "firebase-app-hosting" | "firebaseAppHosting" | "firebase_app_hosting" | "flight-control" | "flightControl" | "flight_control" | "genezio" | "github-pages" | "githubPages" | "github_pages" | "gitlab-pages" | "gitlabPages" | "gitlab_pages" | "heroku" | "iis-handler" | "iisHandler" | "iis_handler" | "iis-node" | "iisNode" | "iis_node" | "koyeb" | "netlify" | "netlify-edge" | "netlifyEdge" | "netlify_edge" | "netlify-static" | "netlifyStatic" | "netlify_static" | "nitro-dev" | "nitroDev" | "nitro_dev" | "nitro-prerender" | "nitroPrerender" | "nitro_prerender" | "nitro-serve" | "nitroServe" | "nitro_serve" | "node" | "node-cluster" | "nodeCluster" | "node_cluster" | "node-middleware" | "nodeMiddleware" | "node_middleware" | "node-server" | "nodeServer" | "node_server" | "platform-sh" | "platformSh" | "platform_sh" | "render-com" | "renderCom" | "render_com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercelDev" | "vercel_dev" | "vercel-static" | "vercelStatic" | "vercel_static" | "zeabur" | "zeabur-static" | "zeaburStatic" | "zeabur_static" | "zephyr" | "zerops" | "zerops-static" | "zeropsStatic" | "zerops_static" | (string & {});
export type PresetNameInput = "alwaysdata" | "aws-amplify" | "awsAmplify" | "aws_amplify" | "aws-lambda" | "awsLambda" | "aws_lambda" | "azure-swa" | "azureSwa" | "azure_swa" | "base-worker" | "baseWorker" | "base_worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflareDev" | "cloudflare_dev" | "cloudflare-durable" | "cloudflareDurable" | "cloudflare_durable" | "cloudflare-module" | "cloudflareModule" | "cloudflare_module" | "cloudflare-pages" | "cloudflarePages" | "cloudflare_pages" | "cloudflare-pages-static" | "cloudflarePagesStatic" | "cloudflare_pages_static" | "deno" | "deno-server" | "denoServer" | "deno_server" | "digital-ocean" | "digitalOcean" | "digital_ocean" | "edgeone" | "edgeone-pages" | "edgeonePages" | "edgeone_pages" | "firebase-app-hosting" | "firebaseAppHosting" | "firebase_app_hosting" | "flight-control" | "flightControl" | "flight_control" | "genezio" | "github-pages" | "githubPages" | "github_pages" | "gitlab-pages" | "gitlabPages" | "gitlab_pages" | "heroku" | "iis-handler" | "iisHandler" | "iis_handler" | "iis-node" | "iisNode" | "iis_node" | "koyeb" | "neon" | "neon-functions" | "neonFunctions" | "neon_functions" | "netlify" | "netlify-edge" | "netlifyEdge" | "netlify_edge" | "netlify-static" | "netlifyStatic" | "netlify_static" | "nitro-dev" | "nitroDev" | "nitro_dev" | "nitro-prerender" | "nitroPrerender" | "nitro_prerender" | "nitro-serve" | "nitroServe" | "nitro_serve" | "node" | "node-cluster" | "nodeCluster" | "node_cluster" | "node-middleware" | "nodeMiddleware" | "node_middleware" | "node-server" | "nodeServer" | "node_server" | "platform-sh" | "platformSh" | "platform_sh" | "render-com" | "renderCom" | "render_com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercelDev" | "vercel_dev" | "vercel-static" | "vercelStatic" | "vercel_static" | "zeabur" | "zeabur-static" | "zeaburStatic" | "zeabur_static" | "zephyr" | "zerops" | "zerops-static" | "zeropsStatic" | "zerops_static" | (string & {});
32 changes: 32 additions & 0 deletions src/presets/neon/preset.ts
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;
109 changes: 109 additions & 0 deletions src/presets/neon/runtime/_shutdown.ts
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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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();
Comment thread
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 })
)
);
});
}
Loading