ViteReact

Deploy a Vite single-page app

Serve a Vite single-page app from its dist build, with deep links that load on refresh, VITE_ variables set per environment and an API next to it. This guide takes the React template from npm create vite to a production deploy on Modelence.

Last updated /Tested with Vite 8.4, React 19.3, React Router 8.5 and Node.js 22

To deploy a Vite app on Modelence, add a modelence.config.json file whose build runs npm run build and whose static entry serves the dist folder, then run npx modelence@latest deploy. Modelence is a managed cloud on AWS that builds the app, serves its files with a fallback to index.html for client-side routes, and can run your API and managed MongoDB, Postgres and Redis databases next to it in one of 17 regions.

This guide starts from the React and TypeScript template of Vite, adds a client-side route and deploys the build with no server process at all. The Vue, Svelte and plain TypeScript templates write their build to the same dist folder, so the config and commands work for them unchanged. The guide then covers VITE_ variables, which are fixed when the app is built, and two ways to give the app an API. If your app already builds, skip to Describe the app in modelence.config.json. For a React app that renders on the server, see the React Router or Next.js guide instead.

Vite on Modelence at a glance

How it runs
npm run build writes dist, and the platform serves those files itself, so there is no server process of your own to run
Client-side routes
Paths with no file extension, such as /settings/profile, get index.html, so deep links load on refresh
Caching
Hashed files in dist/assets are cached for a year as immutable, and index.html is revalidated, so a deploy shows at once
VITE_ variables
Read when the build runs and written into the bundle, so each environment builds with its own values
API
An Express or other Node.js server behind the same files on one origin, or a separate service in any language
Regions
17 regions on AWS, with the app, its API and its MongoDB, Postgres and Redis databases in the one you pick
Price
A free plan, and paid plans from $20 a month with that $20 included as usage

Before you start

  • Node.js 20.19 or newer (or 22.12 or newer on Node.js 22), which Vite 8 needs, 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 Vite app

npm create vite@latest scaffolds a project from one of Vite's templates, and --no-interactive skips the questions it would otherwise ask. The react-ts template has a dev script that runs vite, a build script that type-checks with tsc -b and then runs vite build, and a preview script. For Vue, Svelte or plain TypeScript, pass vue-ts, svelte-ts or vanilla-ts instead, and the rest of this guide stays the same.

bash
npm create vite@latest my-app -- --template react-ts --no-interactive
cd my-app
npm install

Add client-side routes

A single-page app decides what to show from the URL after it loads, so /settings/profile exists only in the browser and there is no settings/profile.html in the build. When a visitor opens that link directly or refreshes the page, the server has to answer with index.html and let the router take over, which the config in the deploy steps sets up. Install React Router with npm install react-router and create the page in src/Profile.tsx:

// src/Profile.tsx
import { useEffect, useState } from 'react'

// Vite replaces import.meta.env.VITE_API_URL with its value at build time.
const API_URL = import.meta.env.VITE_API_URL ?? ''

export default function Profile() {
  const [message, setMessage] = useState('Loading...')

  useEffect(() => {
    fetch(`${API_URL}/api/hello`)
      .then((response) => response.json())
      .then((data: { message: string }) => setMessage(data.message))
      .catch(() => setMessage('The API did not answer'))
  }, [])

  return (
    <main>
      <h1>Profile settings</h1>
      <p>{message}</p>
    </main>
  )
}

The page calls /api/hello, which the API step further down adds. Until then it shows "The API did not answer". Then put the routes in src/main.tsx, replacing the template's version:

src/main.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, Route, Routes } from 'react-router'
import './index.css'
import App from './App.tsx'
import Profile from './Profile.tsx'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />} />
        <Route path="/settings/profile" element={<Profile />} />
      </Routes>
    </BrowserRouter>
  </StrictMode>,
)

Run the app locally

Start the development server and open http://localhost:5173/settings/profile:

npm run dev

vite reads a .env file in the project root, so VITE_API_URL can live there while you work. To skip the file, connect the project to a Modelence local environment: npx modelence@latest setup signs you in and picks an app and environment, and npx modelence@latest dev runs your dev script with that environment's variables.

To look at the production build, run npm run build and then npm run preview, which serves dist on http://localhost:4173. Vite's own docs say not to use vite preview as a production server, and the deploy below doesn't need it.

bash
npx modelence@latest setup
npx modelence@latest dev

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

A Vite app runs in the visitor's browser, so it never holds a database connection string: anything the bundle contains can be read by everyone who loads the page. The database belongs to the API the app calls, which is either a Node.js server in the same service, as in the API step below, or a separate backend.

Modelence passes the connection strings for its managed MongoDB, Postgres and Redis to that server as environment variables. Postgres and Redis are declared as resources in modelence.config.json and tied to variables such as DATABASE_URL and REDIS_URL, and a mongodb resource gives every service MONGODB_URI. These variables reach the running server only and never the build, so they can't end up in the bundle by mistake. Production databases are backed up at least every six hours, and connections are encrypted in transit. The Express and Node.js guides show the server code that reads them.

An app that talks to Supabase or Firebase straight from the browser keeps working as it is. Its project URL and public key are VITE_ variables with the build scope, as the variables step below describes, and the key is public by design, so keep row-level security or security rules switched on.

This config serves the build in front of the API server and creates a Postgres database and a Redis cache for it. Postgres and Redis need a paid plan:

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 server.js"] },
      "static": [{ "path": "/", "dir": "dist" }],
      "healthCheck": { "type": "http", "path": "/health" }
    },
    "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

The web service builds on the official Node.js image with npm ci and npm run build, and the static entry serves the dist folder at /. List the build commands yourself, because a service without build runs only npm install and would never create dist. There is no start command, so no process of yours runs, and the platform answers every request from the files in dist:

  • A file that exists is sent as it is, such as /assets/index-C6TD1M2X.js.
  • A path with no file extension, such as /settings/profile, gets index.html with status 200, so the router can show the page.
  • A missing file with an extension, such as an old /assets/index-Ab12Cd34.js, gets a 404 instead of index.html, so a broken script tag fails loudly rather than loading HTML as JavaScript.
  • Files under assets/ with a content hash in their name get Cache-Control: public, max-age=31536000, immutable, and everything else, index.html included, gets no-cache, so browsers pick up a new deploy on the next page load.

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"] },
      "static": [{ "path": "/", "dir": "dist" }]
    }
  }
}

Adjust the config for your project

  • npm ci installs exactly what package-lock.json lists. With pnpm or Yarn, start with corepack enable and use that package manager's frozen-lockfile install instead.
  • If build.outDir in vite.config.ts points somewhere other than dist, set dir to the same folder.
  • For an app served under a sub-path, build it with base: '/app/' in vite.config.ts and set the static path to "/app". Give React Router the same basename.
  • Set root on the service when the app sits in a folder of a monorepo, such as apps/web. The dir is then relative to that folder.
  • Never add vite or vite preview as a start command. Both are meant for your machine, and the static entry already serves the build.
  • Keep node-22-slim unless engines.node in package.json asks for another version. Vite 8 needs Node.js 20.19 or newer, and 22 meets that.

Set VITE_ variables for each environment

Vite replaces every import.meta.env.VITE_* expression with its value while vite build runs, so the value is written into the JavaScript files in dist and changing it later in a running container does nothing. Declare each one in env with the build scope. Leave out value for anything that differs between environments, and the deploy asks for it, after which you can change it in the dashboard under Environment variables:

// 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"] },
      "static": [{ "path": "/", "dir": "dist" }]
    }
  },
  "env": {
    "VITE_API_URL": { "scopes": ["build", "runtime"] }
  }
}

Every deploy to an environment runs the build with that environment's values, so the sandbox bundle can call a staging API while production calls the real one, from the same commit. A changed value takes effect on the next deploy, since a restart doesn't rebuild the files. You can see the effect locally: VITE_API_URL=https://api.example.com npx vite build puts the literal https://api.example.com into dist/assets/index-*.js.

Because the value ends up in a file every visitor downloads, never use the VITE_ prefix for a secret such as a Stripe secret key or an OpenAI key. Keep those on the API, declared with "type": "secret", where the browser never sees them.

Call an API

There are two ways to give a Vite app a backend on Modelence.

Serve the build in front of a Node.js server

Add a start command next to static, and one service runs both. The platform answers from dist whenever a file matches, sends every other request to your server, and still returns index.html when a browser navigation reaches a path the server answers with 404. The app and the API share one origin, so the browser needs no CORS headers and fetch('/api/hello') works with VITE_API_URL left unset. Install Express with npm install express and add server.js at the project root, shown below, then change the service to:

// 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 server.js"] },
      "static": [{ "path": "/", "dir": "dist" }],
      "healthCheck": { "type": "http", "path": "/health" }
    }
  }
}

The server listens on the PORT it is given, and the health check calls /health through the same router. The Express and Node.js guides cover the server side in more depth.

Call a separate backend with CORS

A backend in Python or any other language runs from its own Dockerfile, and a Dockerfile service can't take a static entry, so it runs as a service of its own, in the same environment or in a separate app. Attach a custom domain to it under Domains, such as api.example.com, set VITE_API_URL to that address, and allow the Vite app's origin in the backend's CORS settings, for example with CORSMiddleware in FastAPI. Calls between services on the private network are for servers only, so the browser always uses the public address.

server.js
import express from 'express'

const app = express()

app.get('/health', (req, res) => {
  res.json({ status: 'ok' })
})

app.get('/api/hello', (req, res) => {
  res.json({ message: 'Hello from the API' })
})

// The platform serves dist in front of this server, so it only sees the
// requests that match no built file.
const port = Number(process.env.PORT) || 3000
const server = app.listen(port, () => console.log(`API listening on port ${port}`))

// Requests can still arrive for about 10 seconds after SIGTERM, so keep
// serving for that long, then finish open requests and exit.
process.once('SIGTERM', () => {
  setTimeout(() => server.close(() => process.exit(0)), 10_000)
})

Check the build locally

npx modelence@latest verify rehearses the deploy on your machine without signing in. It copies the files a deploy would upload, runs the build commands from modelence.config.json and serves the result through the same entrypoint the cloud container uses, on a random PORT. It then checks that / answers, and lists which declared variables the build and the server got. For the static config above it ends with GET / -> 200 and modelence.config.json verified. A build that fails here fails in the cloud too.

bash
npx modelence@latest verify

Deploy

In the project directory, run:

npx modelence@latest deploy

The command opens the browser so you can sign in, choose or create the organization, app and environment, and fill in variables the environment doesn't have yet, such as VITE_API_URL. 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 everything in that environment is created there. Later deploys can skip the prompts with --app <app> --env <env>.

The app is served at <app>-<environment>.cloud.modelence.app, and you can add your own domain in the dashboard under Domains. Each app comes with a sandbox and a production environment, and both deploy from the same file, each with its own build.

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, runs the build and the deploy, and asks you whenever a step needs your account.

Production readiness

Reload tabs that ask for an old chunk

Each build gives the JavaScript files new hashed names, and the new containers serve only the new ones. A tab opened before the deploy that lazy-loads a route afterwards asks for a file that is gone, gets a 404 and logs "Failed to fetch dynamically imported module". Vite fires a vite:preloadError event when that happens, so add a listener at the end of src/main.tsx that reloads the page:

// A tab opened before a deploy can ask for a chunk the new build no longer
// has. Reload the page so the visitor gets the new version.
window.addEventListener('vite:preloadError', (event) => {
  event.preventDefault()
  window.location.reload()
})

After one full page load the visitor is on the new version. If a reload in the middle of a form would lose work, save drafts on the server.

Keep secrets on the server

Everything the bundle imports, every VITE_ variable included, can be read in the browser's developer tools. Put API keys, payment secrets and database credentials on the API instead, declared as "type": "secret" in modelence.config.json. Members of the environment can view or change a secret in the dashboard, and every view is logged.

Give client routes paths without a file extension

With no server behind it, the static entry tells a page from a file by the extension, so /settings/profile gets index.html and /users/jane.doe gets a 404, because it looks like a file named jane.doe. Use IDs or slugs without dots in client routes, or serve the build in front of a Node.js server as in the API step, where a browser navigation that the server answers with 404 still gets index.html.

Let Vite hash your assets

Images, fonts and styles you import from src get hashed names under assets/ and are cached for a year. Files in public/ keep their names and are revalidated on every load, so keep that folder for files that need a fixed URL, such as favicon.svg or robots.txt, and import everything else.

Run more than one container

A static app still runs in containers, and the free plan runs one instance that sleeps when idle. On a paid plan, run the service on two or more containers under Configure in the dashboard, so the app keeps serving if one is replaced or an availability zone goes down. A deploy starts the new containers and moves traffic to them once they are healthy, and a version that fails to start rolls back.

Track errors in the browser

The environment's Logs page shows the build and anything your server writes, but a single-page app fails in the visitor's browser, where those logs can't see it. Add an error tracker that runs in the browser, and call it from the vite:preloadError listener and your router's error boundary.

Modelence vs Vercel, Netlify and Cloudflare for Vite apps

Vite apps are most often deployed on Vercel, Netlify and Cloudflare, which all serve a static build from their own global networks. The table is based on each platform's own docs and pricing pages in November 2026.

PlatformHow the build is servedBackend for the appPricing
ModelenceBuilt from modelence.config.json and served by the app's containers in one of 17 regions; paths without a file extension get index.html with no extra ruleA Node.js server behind the same files, or services in any language, with managed MongoDB, Postgres and RedisFree plan; paid plans from $20 a month with $20 of usage included
VercelThe vercel CLI deploys the build and serves it from Vercel's CDN; deep links need a rewrite to /index.html in vercel.jsonVercel Functions through a framework that supports them, or Nitro added to the Vite projectHobby is $0 with 100 GB of transfer a month; Pro is $20 per developer seat a month with $20 of credit and 1 TB
NetlifySuggests npm run build and dist and serves from its CDN; deep links need a /* /index.html 200 rewriteA proxy rewrite from /api/* to an API hosted elsewhere, which times out after 26 secondsFree with 300 credits a month; Personal $9 with 1,000; Pro $20 with 3,000; each GB of bandwidth costs 20 credits
CloudflareWorkers static assets, which Cloudflare now suggests over Pages for new sites, with not_found_handling set to single-page-applicationA Worker in the same project answers /api/* through the Cloudflare Vite pluginStatic asset requests are free and unlimited; Workers Free has 100,000 requests a day, and Paid starts at $5 a month

For a front end with no backend of its own, such as a marketing site or an app that calls a hosted service directly, Cloudflare is hard to beat on cost because it doesn't charge for static asset requests, and all three serve the files from locations close to visitors around the world. Vercel suits a team that wants a preview URL for every pull request, and Netlify's proxy rule is a quick way to reach an API that doesn't send CORS headers. Modelence fits when the Vite app is the front of an API and a database you also run, because one file describes all of them, the app and API can share one origin with no CORS, and everything stays in the region you pick. Modelence vs Vercel and Vercel alternatives compare the platforms in more depth, and Railway alternatives covers moving an app with its backend.

Next steps

Frequently asked questions

How do I deploy a Vite React app?

Run vite build, which writes static files to dist, and serve that folder with a fallback to index.html for client-side routes. On Modelence, a modelence.config.json with the build commands npm ci and npm run build and a static entry for dist does both, and npx modelence@latest deploy builds and serves it. The same file works for the Vue, Svelte and plain TypeScript templates.

Why do I get a 404 when I refresh a page in my Vite app?

The server looked for a file at that path, such as /settings/profile, and found none, because the route exists only in the browser. The fix is a fallback that answers such paths with index.html. A static entry on Modelence does this for every path without a file extension, while Vercel and Netlify need a rewrite rule and Cloudflare Workers needs not_found_handling set to single-page-application.

Can I use vite preview in production?

No, Vite's own docs say vite preview is for checking the build locally and is not designed as a production server. Serve dist with a static host or file server instead. On Modelence the static entry serves it, so the service needs no start command at all.

Why are my VITE_ environment variables undefined in production?

Vite reads them when the build runs, so they have to be present in the build environment, not only in the running container. Check that the name starts with VITE_, that it is read as import.meta.env.VITE_NAME written out in full, and on Modelence that it is declared with the build scope in modelence.config.json. Then deploy again, because only a new build picks up a changed value.

Can I change a VITE_ variable without rebuilding the app?

No, because Vite writes the value into the JavaScript files during the build. Each deploy on Modelence builds with the target environment's values, so sandbox and production can differ from the same commit. For settings that must change without a deploy, have the app fetch them from your API when it starts.

Is it safe to put an API key in a VITE_ variable?

Only if the key is meant to be public, such as a Supabase anon key or a Stripe publishable key, because every visitor can read the bundle. Secret keys belong on a server: call your own API from the app, and keep the key there as a secret variable that the browser never receives.

How do I connect a Vite frontend to a FastAPI or Express backend?

Point fetch calls at the backend's URL from a VITE_API_URL variable and allow the frontend's origin in the backend's CORS settings, or serve both from one origin so CORS doesn't apply. On Modelence, an Express or other Node.js server can run in the same service as the static files, and a FastAPI backend runs from its own Dockerfile as a separate service with its own domain.

Do I need Nginx to serve a Vite app?

No, Nginx is one way to serve the dist folder with an index.html fallback, but any static host does the same job. On Modelence the platform serves the files, sets long-lived caching for hashed assets and falls back to index.html, so there is no Nginx config or Dockerfile to maintain.

Why do I see "Failed to fetch dynamically imported module" after a deploy?

A tab opened before the deploy tried to load a lazy chunk from the previous build, whose hashed file no longer exists. Listen for Vite's vite:preloadError event and reload the page, so the visitor loads the new index.html and its new chunks.

How much does it cost to host a Vite 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 by size, from about $9 a month for the smallest one with 0.25 vCPU and 0.5 GB of memory, which is enough to serve a static build.

Deploy other stacks

Deploy your Vite app

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

Or paste this into your coding agent