Serve the built frontend from Express
Yes. Put the React build and the Express server in one Node.js web deployment. Express listens on the assigned port and serves both the static files and routes under /api/. A React component can call fetch('/api/health') on the same origin. That URL continues to work when you move from the Bothosting hostname to a custom domain.
This example assumes a single npm package with Vite, React and a build script that runs vite build. Install Express with npm install express. Vite’s default build directory is dist/. Place server.mjs beside package.json. Vite build output.
Keep API responses separate from browser routes
Define the API routes first, then a JSON 404 for unknown API paths. Serve the built files next. For a client-side route like /dashboard, explicitly serve the same HTML entry point on direct visits. Add other client routes your app owns in the same way. Missing assets will then return an ordinary 404.
import express from 'express';
import { fileURLToPath } from 'node:url';
const app = express();
const dist = fileURLToPath(new URL('./dist/', import.meta.url));
app.get('/api/health', (_req, res) => res.json({ status: 'ok' }));
app.use('/api', (_req, res) => res.status(404).json({ error: 'Unknown API route' }));
app.use(express.static(dist));
app.get('/dashboard', (_req, res) => res.sendFile('index.html', { root: dist }));
app.listen(Number(process.env.SERVER_PORT), '0.0.0.0');Point the static middleware at dist/. Keep server code, private files and API credentials outside that directory. Serving static files with Express.
Build once locally or build during startup
Choose HTTP app or API under Node.js hosting. If you already built locally, upload dist/, server.mjs, the manifest and lockfile. Set RUN_COMMAND to npm ci --omit=dev && node server.mjs. If you upload the frontend source instead, include its HTML entry and Vite configuration and use the following startup command.
npm ci --include=dev && npm run build && node server.mjsKeep backend secrets in the deployment’s environment. Any value embedded in the frontend build is readable by visitors. Where to put a private API key.
Make three requests to the same hostname
- Load
/and check that the page renders with its JavaScript and CSS. - Open
/api/healthand look for JSON withstatusequal took. If your frontend reports an unexpected<while parsing JSON, inspect the response. An HTML document here points to a route or fallback serving the frontend. - Open
/dashboarddirectly and refresh it. The browser should load the React app, and its router should show the dashboard. Try/api/missingas well to verify the API still returns a JSON 404.
For a backend-only project, the Express API deployment guide has a smaller example.