Skip to content

Deployment · By Rivtor · Updated

Deploy Next.js, FastAPI and Postgres together

Keep the Next.js frontend and FastAPI backend in separate service directories. Rivtor detects supported services and provisions the database your code needs. Verify a complete browser-to-API-to-database request after release.

See the Rivtor deployment workflow →

Separate the service roots

Put the Next.js package manifest in the web directory and Python dependencies alongside the API entrypoint. Confirm each service works from its own directory. An import that succeeds only from the repository root can fail when the backend is built independently. Commit lockfiles and migration history before deployment.

Check prerequisites before deploying

Use a disposable project with Node.js, Python, a working Next.js production build and an independently startable FastAPI service. Install each service from its committed dependency files. You also need reviewed database migrations and a Rivtor account with allowances appropriate to the services in the plan. Create an account and read the quickstart before connecting valuable data.

From web, run your project's documented build and production start scripts. From api, run the production ASGI entrypoint, for example:

python -m uvicorn main:app --host 0.0.0.0 --port 8000

This assumes main.py exposes app. The illustrative database health endpoint below additionally requires a reachable disposable Postgres database in DATABASE_URL. Do not use a live customer database to rehearse migrations.

Distinguish browser and database addresses

Browser requests need a publicly reachable API URL. Database traffic belongs on the server and should use the injected database connection. Never expose a database password through a NEXTPUBLIC variable. A hardcoded localhost URL in the frontend points at the visitor’s computer after release, not your hosted API.

Review migrations and missing secrets

Use the deployment plan to check detected services, data dependencies and variable names. Set required secret values through the documented environment workflow. Apply reviewed Alembic migrations before code that needs the new schema starts serving requests. A successful server startup does not prove that tables exist.

Verify the complete journey

Visit the frontend, create a synthetic record through the API, reload the page and confirm persistence. Read the verification verdict separately from deployment status, including skipped checks. If a release fails, inspect the first meaningful error and preserve the previously working application while investigating.

Command reference

npx rivtor login
npx rivtor deploy --dry-run
npx rivtor deploy
npx rivtor verify

These commands illustrate the documented workflow. Replace example addresses and identifiers with your own. Deployment and migration commands affect the selected project; confirm the target before running them.

Work through a concrete repository

A useful first project has two independently installable services:

my-app/
  web/
    package.json
    app/
  api/
    requirements.txt
    main.py

Run the frontend from web and the API from api before testing deployment. Keep Python dependencies out of the frontend package. In the API, load DATABASE_URL on the server; in the browser, use NEXT_PUBLIC_API_URL for the public API address. Those values serve different trust boundaries.

A small database health endpoint can exercise the same driver used by application requests:

import os
import psycopg
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
def health():
    with psycopg.connect(
        os.environ["DATABASE_URL"],
        connect_timeout=5,
        prepare_threshold=None,
    ) as connection:
        connection.execute("SELECT 1")
    return {"ok": True}

This illustrative synchronous endpoint requires fastapi, uvicorn and psycopg with a suitable installation extra in requirements.txt. It checks database reachability, not record ownership, migrations or the entire application. Disabling automatic prepared statements here accommodates transaction-pooling configurations; choose settings appropriate to your driver and pool.

Connect the browser to the deployed API

For a browser request, construct the address from NEXT_PUBLIC_API_URL and an application endpoint. Inspect that variable before building: a NEXT_PUBLIC value can be compiled into the JavaScript bundle. Rebuilding the API alone will not update an old frontend address. If the services use different origins, configure FastAPI CORS for the actual frontend origin. Server-side fetches do not demonstrate that browser CORS works.

Use the production CORS troubleshooting guide if a direct API request succeeds while the page fails. Never solve this by exposing the database address in a public variable.

Confirm the result with application data

After reviewing the dry-run plan, deploy the intended project through the quickstart. A useful acceptance sequence is: load the page, create a synthetic record through the API, refresh, read it again and remove it. Check both the public API URL and the frontend URL from the deployment result. A JSON health response only covers the checks implemented by that endpoint.

If startup reports an absent table, investigate migration history instead of repeatedly rebuilding the frontend. If the API works but the page cannot reach it, inspect its built address, browser console and allowed origins. Verification documentation explains report verdicts and skipped checks.

Configuration checklist

ValueRead byAppropriate visibility
DATABASE_URLBackend database driverServer only
NEXT_PUBLIC_API_URLBrowser applicationPublic API origin
Allowed frontend originAPI CORS middlewareExact deployed frontend origin

Check expected results and common failures

CheckExpected observationIf it fails
Dry-run detectionSeparate web and API services with intended roots and data dependenciesReview package boundaries and deploy.toml overrides
API healthSuccessful response from the returned API URLInspect startup logs, port binding and server-only environment values
Browser requestRequest reaches the intended API and receives an allowed CORS responseInspect the frontend build-time API URL and the exact allowed origin
Synthetic create and readRecord can be read again after a page refreshCheck route authorization, migration history and transaction handling
Verification reportRequired checks ran with understood verdictsInvestigate failed checks; record skipped checks as unverified

The commands and snippets in this guide are documented examples, not evidence of a runtime-tested deployment. Choose a hosting comparison when evaluating platform fit; use FastAPI hosting checks when region, workers or resource limits determine the choice.

Review FastAPI deployment concepts and Next.js environment variables alongside the framework versions installed in your project.

Next steps

Read the Rivtor reference for supported configuration and limitations, and use the deployment quickstart when trying Rivtor for the first time. Validate workflows with synthetic data before connecting valuable production records.