TanStack

Deploy a TanStack Start app

Run a TanStack Start app with server rendering, server functions that query a managed database and secrets that never reach the browser. This guide takes a new app from the TanStack CLI to a production deploy on Modelence.

Last updated /Tested with TanStack Start 1.169, Nitro 3.0 beta, Vite 8.4 and Node.js 22

To deploy a TanStack Start app on Modelence, build it with the Nitro Vite plugin, which writes a Node.js server to .output, and add a modelence.config.json file that starts it with node .output/server/index.mjs, then run npx modelence@latest deploy. Modelence is a managed cloud on AWS that runs the app as a long-running server in one of 17 regions, next to managed MongoDB, Postgres and Redis databases, and handles rollouts and backups for you.

This guide uses TanStack Start with React, the way the official CLI sets it up. It builds a small app whose server function reads from Postgres, deploys it, and then covers what to change before real traffic arrives, including how to keep the server answering while a deploy replaces it. Lovable projects created since May 2026 are TanStack Start apps too, and Move from Lovable covers that case. If you already have an app, skip to Run the app locally. For an app built on React Router see the React Router guide, for Next.js see Next.js, and for a plain server see Node.js.

TanStack Start on Modelence at a glance

How it runs
node .output/server/index.mjs, the Node.js server Nitro builds, runs in a long-lived container on the PORT Modelence sets
Server functions
createServerFn handlers and .server files run only in the container, and a build fails if browser code imports a .server file
Build output
Nitro bundles the server's dependencies into .output, so the server starts without node_modules
Regions
17 regions on AWS, with the app's containers and its databases in the same region
Databases
Managed MongoDB, Postgres and Redis next to the app, with production backups at least every six hours
Deploys
The new version starts next to the old one and takes traffic after its health check passes; a crashing version rolls back
Price
A free plan, and paid plans from $20 a month that count the whole $20 toward usage

Before you start

  • Node.js 22.12 or newer, which TanStack Start 1.169 asks for, and npm
  • A Modelence account, which you can create for free
  • Optionally, Claude Code, Cursor or Codex, if you want your coding agent to write the config and run the deploy

Create a TanStack Start app

The TanStack CLI creates the app, installs its dependencies and, with --deployment nitro, adds the Nitro Vite plugin. Nitro is what turns vite build into a server you can run with Node.js: the build writes the server to .output/server/index.mjs and the browser files to .output/public. The new package.json has a dev script that runs vite dev --port 3000 and a build script that runs vite build, and it has no start script, so production runs the Nitro server with node directly.

Without --deployment nitro, the CLI leaves Nitro out and vite build writes dist/client and dist/server instead, which has no server to start. To add it to an existing app, run npm install nitro and put nitro() in the plugins in vite.config.ts, as in this file from a new app:

// vite.config.ts
import { defineConfig } from 'vite'
import { devtools } from '@tanstack/devtools-vite'

import { tanstackStart } from '@tanstack/react-start/plugin/vite'

import viteReact from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { nitro } from 'nitro/vite'

const config = defineConfig({
  resolve: { tsconfigPaths: true },
  plugins: [devtools(), nitro(), tailwindcss(), tanstackStart(), viteReact()],
})

export default config
bash
npx @tanstack/cli@latest create my-app --framework React --deployment nitro --package-manager npm --non-interactive
cd my-app

Read Postgres in a server function

Install a Postgres client with npm install pg and npm install -D @types/pg, then create one connection pool in src/lib/db.server.ts:

// src/lib/db.server.ts
import pg from 'pg'

// One pool per server process, shared by every request. The .server suffix
// keeps this module and the connection string out of the browser bundle.
export const db = new pg.Pool({ connectionString: process.env.DATABASE_URL })

TanStack Start checks every import during the build. A file whose name contains .server. can only be imported by server code, and if browser code imports it, vite build stops with "Import denied in client environment". A server function made with createServerFn runs its handler on the server. The route's loader calls it during server rendering, and when the visitor navigates in the browser, the call becomes a request to the server, so the query and DATABASE_URL stay out of the browser bundle. The #/ prefix is the import alias the CLI sets up in package.json for src/. Add the route file:

src/routes/items.tsx
import { createFileRoute } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { db } from '#/lib/db.server'

// The handler runs only on the server. In the browser bundle, getItems
// becomes a fetch call to it, so db and DATABASE_URL never ship there.
const getItems = createServerFn({ method: 'GET' }).handler(async () => {
  const { rows } = await db.query<{ id: number; name: string }>(
    'SELECT id, name FROM items ORDER BY id',
  )
  return rows
})

export const Route = createFileRoute('/items')({
  loader: () => getItems(),
  component: Items,
})

function Items() {
  const items = Route.useLoaderData()
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  )
}

Add a health route

A server route answers HTTP requests itself instead of rendering a page. Modelence can call this one to decide whether a new container is ready for traffic, which the config in the deploy step turns on. TanStack Router picks up the file and adds it to src/routeTree.gen.ts the next time the dev server or the build runs:

src/routes/health.ts
import { createFileRoute } from '@tanstack/react-router'

// A server route: it answers GET /health with JSON and renders no page.
export const Route = createFileRoute('/health')({
  server: {
    handlers: {
      GET: () => Response.json({ status: 'ok' }),
    },
  },
})

Run the app locally

Start the development server and open http://localhost:3000/items:

npm run dev

TanStack Start loads a .env file from the project root, so server functions can read DATABASE_URL from there while you work. To work without a .env file, connect the project to a Modelence local environment instead. npx modelence@latest setup opens the browser so you can sign in and pick or create an app and environment, and npx modelence@latest dev then runs the dev script with that environment's connection strings and variables.

bash
npx modelence@latest setup
npx modelence@latest dev

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

Modelence hands the app the connection strings for its managed MongoDB, Postgres and Redis as environment variables. Production databases are backed up at least every six hours, and connections are encrypted in transit. MongoDB comes in as MONGODB_URI, and Postgres and Redis use the names you give them in modelence.config.json, usually DATABASE_URL and REDIS_URL.

In a TanStack Start app, read these variables only in server code: server function handlers, server route handlers and .server files. Vite puts only variables that start with VITE_ into the browser bundle, through import.meta.env, so a connection string without that prefix stays on the server. Create one client per process in a .server file, as src/lib/db.server.ts does above, and pass it to the library you already use, such as pg, Drizzle, Prisma, the MongoDB driver or a Redis client.

A database you already run at Supabase or Neon keeps working. Declare its URL in env with "type": "secret" and enter the value when the deploy asks for it.

Run migrations against the environment's database before you deploy, and keep them out of the start command. Every container runs the start command, and a rollout starts more than one container, so the same migration would run several times at once.

Declare Postgres and Redis as resources next to the app's service, and the deploy creates them before the new version starts:

modelence.config.json
{
  "resources": {
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "cache": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
  }
}

Describe the app in modelence.config.json

Modelence runs a TanStack Start app as a Node.js service on an official Node.js image. The build commands install the dependencies and run vite build, and the start command runs the server Nitro wrote to .output. Nitro reads the PORT variable Modelence sets and listens on all interfaces, so the command needs no flags. The health check calls the /health server route from the setup steps. Add the file to the root of the repository and commit it:

modelence.config.json
{
  "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
  "resources": {
    "web": {
      "type": "service",
      "image": "node-22-slim",
      "build": { "commands": ["npm ci", "npm run build"] },
      "start": { "commands": ["node .output/server/index.mjs"] },
      "healthCheck": { "type": "http", "path": "/health" }
    },
    "main-db": { "type": "postgres", "plan": "postgres-1gb" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" }
  }
}

Adjust the config for your project

  • npm ci installs exactly what package-lock.json lists. With pnpm or Yarn, run corepack enable first and then that package manager's frozen-lockfile install.
  • Never start the app with vite dev or vite preview. The Nitro server in .output is the production server.
  • Keep node-22-slim unless engines.node in package.json asks for another version. TanStack Start 1.169 needs Node.js 22.12 or newer.
  • Vite writes VITE_ variables into the browser bundle during the build, so give them "scopes": ["build", "runtime"], and never use the prefix for a secret.
  • Declare API keys and tokens with "type": "secret" and no value. The deploy asks you for each one, and afterwards you can view or change it in the dashboard under Environment variables, where every view is logged.
  • Set root on the service when the app lives in a folder of a monorepo rather than at the repository root.
  • The start command doesn't need node_modules, because Nitro bundles what the server imports, pg included, into .output/server.

Check the build locally

Run the commands a deploy runs, in the same order, then open http://localhost:3000/health in another terminal. A build that fails here fails in the cloud too. npx modelence@latest verify goes a step further: it copies the project, runs the build commands from modelence.config.json, starts the app the way a container does and checks that it answers. It needs no sign-in and lists the variables the cloud will provide, such as DATABASE_URL.

bash
npm ci && npm run build && PORT=3000 node .output/server/index.mjs

Deploy

In the project directory, run:

npx modelence@latest deploy

The command opens the browser, where you sign in, choose or create the organization, app and environment, and fill in any secrets the environment doesn't have yet. It then uploads the project and streams the build until the new version is live. The first deploy to an environment asks for an AWS region, and that environment's containers and databases are created there. Later deploys can skip the prompts with --app <app> --env <env>.

On the first deploy, Modelence creates the Postgres database, starts the app once the database is ready and serves the web service at <app>-<environment>.cloud.modelence.app. To use your own domain, add it in the dashboard under Domains. Every app comes with a sandbox and a production environment, and the same file deploys to both.

Let your coding agent do it

In Claude Code, Cursor or Codex, paste Deploy using https://modelence.com/skill.md in the project. The agent reads the docs, writes modelence.config.json for the app, checks the build and runs the deploy, and it asks you whenever a step needs your account.

Production readiness

Keep serving for 10 seconds after SIGTERM

When a deploy replaces a container, Modelence sends it SIGTERM, and requests can still reach it for about 10 seconds after that. The Nitro server stops accepting connections as soon as it gets SIGTERM, gives open requests 5 seconds to finish and then closes the rest. In our test, a request sent a quarter of a second after SIGTERM was refused, a 3-second request finished and an 8-second request was cut off at 5 seconds. To keep answering through those 10 seconds, start the server through a small wrapper that holds Nitro's SIGTERM handler back. Add start.mjs at the project root and set the start command to node start.mjs:

// start.mjs
// Starts the server from `vite build` and keeps it serving for 10 seconds
// after SIGTERM, while the load balancer may still send it requests.
// Nitro's own SIGTERM handler stops accepting connections right away, so
// hold it back and call it once the delay is over.
await import('./.output/server/index.mjs')

const nitroHandlers = process.listeners('SIGTERM')
process.removeAllListeners('SIGTERM')

process.once('SIGTERM', () => {
  setTimeout(async () => {
    // Stop accepting connections, let open requests finish, then exit.
    await Promise.all(nitroHandlers.map((handler) => handler('SIGTERM')))
    process.exit(0)
  }, 10_000)
})

With the wrapper, a request sent 9.5 seconds after SIGTERM still got a 200, one sent at 10.5 seconds was refused, and a 13-second request that was already running finished before the process exited. Don't name the file server.mjs, because Nitro picks up a server file at the project root as its own server entry and the build then fails. The process.exit(0) matters too: an idle pg pool kept the default server's process alive for 10 more seconds after it had closed. Modelence waits 30 seconds by default before it stops a container for good, which leaves room for the delay and the 5-second drain. If a request can run longer, raise stopTimeout on the service and set SERVER_SHUTDOWN_TIMEOUT to the number of seconds Nitro should wait for open requests.

Keep state out of the container

Containers have no persistent disk, and every deploy replaces all of them, so files written to disk and sessions kept in memory are gone after the next deploy. Keep sessions in a signed cookie or in Redis from the same region, store uploads in object storage, and keep everything else in the database. Under Configure in the dashboard, run the service on two or more containers so the app stays up when one crashes or an availability zone goes down. Availability explains how deploys and rollbacks keep it serving.

Expect open tabs to reload after a deploy

Each build gives the browser files new hashed names, and the new containers serve only the new ones. When a tab opened before the deploy moves to a route whose file is gone, TanStack Router catches the failed import and reloads the page once, so the visitor lands on the new version. If a reload in the middle of a long form would lose work, save drafts on the server.

Run background jobs as their own service

Keep queue consumers and scheduled jobs out of the TanStack Start server. With more than one container, each one would pick up the same job, and a reminder email would go out once per container. Add a second service to modelence.config.json with its own start command, "healthCheck": { "type": "none" } and "rollout": "recreate", as Multiple services describes.

Watch logs and metrics

The Nitro server prints a line when it starts and doesn't log each request, so log what you need from server functions with console.log or a logger. The environment's Logs page shows everything the app writes to its output, with nothing to set up. For traces and metrics, add a telemetry resource and point the standard OpenTelemetry variables at it, as the modelence.config.json reference describes.

Modelence vs Vercel, Netlify and Cloudflare for TanStack Start

TanStack Start teams most often weigh Vercel and Netlify, which run it as serverless functions, against Cloudflare, which runs it on Workers. Netlify and Cloudflare are official TanStack hosting partners. The table is based on each platform's own docs and pricing pages in November 2026.

PlatformHow a TanStack Start app runsDatabasesPricing
ModelenceNitro's Node.js server as long-running containers on AWS, in 17 regions, across two availability zonesManaged MongoDB, Postgres and Redis in the app's regionFree plan; paid plans from $20 a month with $20 of usage included
VercelThe Nitro build as Vercel Functions with Fluid compute; functions run in iad1 by default, with 1 region on Hobby and up to 5 on ProPostgres and Redis through Marketplace providers such as Neon, Supabase and UpstashHobby is $0 with usage caps; Pro is $20 per developer seat a month with $20 of credit
NetlifyNetlify's Vite plugin deploys server rendering, server routes and server functions as serverless functions, in Ohio by default, with a 60-second limit per requestNetlify Database, a managed Postgres, on credit-based plansFree with 300 credits a month; Personal $9 and Pro $20 a month
CloudflareThe Workers runtime, through the Cloudflare Vite plugin and WranglerD1 with SQLite semantics, and Hyperdrive for an existing Postgres or MySQLFree with 100,000 requests a day; Paid from $5 a month with 10 million requests included

Cloudflare suits an app that should render close to visitors everywhere and can keep its data in D1 or reach its database through Hyperdrive. Vercel and Netlify each need only a Vite plugin to deploy the app as functions, and Vercel scales those functions up and down with traffic. Netlify adds its own Postgres, where every deploy preview gets a branch of the database, while on Vercel the database comes from a Marketplace provider. Modelence fits an app whose server functions do real work against a database and that should run as an ordinary long-lived Node.js server, with the database and its backups in one region you choose. Modelence vs Vercel and Vercel alternatives go into more depth, and Railway alternatives covers Railway, the third official TanStack partner, which also runs the app as a Node.js service.

Next steps

Frequently asked questions

How do I deploy a TanStack Start app?

Build it with the Nitro Vite plugin, which writes a Node.js server to .output, and run node .output/server/index.mjs on a host that runs Node.js. On Modelence you put those build and start commands in modelence.config.json and run npx modelence@latest deploy, which builds the app, creates the databases it declares and starts it in containers on AWS.

What does vite build output for TanStack Start?

With the Nitro plugin, vite build writes a .output folder with the server in .output/server/index.mjs and the browser files in .output/public. The server bundles the dependencies it imports, so you can start it with node .output/server/index.mjs without node_modules, and it serves the files in .output/public itself.

Why does my TanStack Start build create dist instead of .output?

Because the project doesn't use the Nitro plugin, which is what writes .output. The TanStack CLI adds Nitro only when you pick it as the deployment target, so install it with npm install nitro and add nitro() from nitro/vite to the plugins in vite.config.ts, then build again.

Does a TanStack Start app need a server in production?

Yes, when it uses server rendering, server functions or server routes, which a new app does. Those run on every request, so the app needs a running process such as the Nitro Node.js server, a serverless function or a Worker, and on Modelence it runs as a long-lived container.

Can I host a TanStack Start app on AWS without setting up AWS myself?

Yes, Modelence runs on AWS and creates the app's containers, databases and backups for you, with no AWS account to configure. You choose one of 17 regions on the first deploy, and the app runs there in containers spread across two availability zones, with its databases in the same region.

How do I connect TanStack Start to Postgres?

Create a pg Pool from process.env.DATABASE_URL in a file such as src/lib/db.server.ts and query it inside createServerFn handlers. On Modelence, declare a postgres resource in modelence.config.json and connect DATABASE_URL to its url output, and the connection string reaches the server at runtime without ever reaching the browser.

How do I keep secrets out of the client bundle in TanStack Start?

Read them from process.env only in server function handlers, server routes and files whose name contains .server, and never give them a VITE_ prefix. TanStack Start fails the build when browser code imports a .server file, and Vite only puts VITE_ variables into the browser bundle.

Why does my TanStack Start server function return 403 Forbidden?

TanStack Start rejects server function requests that don't come from the same origin, judged by the Sec-Fetch-Site header or, when that is missing, by the Origin header. Calls from your own pages in a browser pass, while a call from another site, or from a script that sends neither header, gets 403, so add a server route for anything outside the app that needs the data.

How do I deploy a Lovable app built with TanStack Start?

Clone the repository Lovable syncs to GitHub and deploy it like any TanStack Start app, with the Nitro build and node .output/server/index.mjs as the start command. Move from Lovable at modelence.com/migrate/lovable covers the steps, including the Supabase variables a Lovable app expects.

How much does it cost to host a TanStack Start app on Modelence?

It can cost nothing on the free plan, which runs one instance that sleeps when idle. Paid plans start at $20 a month, all of which counts toward usage, and each container is billed by the hour for its size, from about $9 a month for the smallest one with 0.25 vCPU and 0.5 GB of memory.

Deploy other stacks

Deploy your TanStack Start app

Start on the free plan and move up when your app needs more.

Or paste this into your coding agent