# Deploy a FastAPI backend for a Next.js frontend on Vercel

Gregale · Updated 2026-11-30

Keep Next.js on Vercel, deploy the FastAPI API separately, configure exact CORS origins, and verify the live browser request.

Keep the Next.js project and domain you already have on Vercel. Deploy only FastAPI to Gregale, allow the frontend's exact origin, then verify that a browser on the Vercel site can read a real API response. You need the [Gregale CLI](https://gregale.dev/docs/quickstart), access to the Vercel project, and two separate project roots. This minimal API is deliberately public, returns a fixed non-sensitive message, and has no database or managed-services requirement. Check [plan limits](https://gregale.dev/pricing) against your actual app.

[Get the runnable example on GitHub](https://github.com/gregale-dev/nextjs-vercel-fastapi-gregale).

## 1. Give FastAPI a real route to verify

Use your existing API if it already answers a safe, read-only route. For a new example, make a `backend/` directory containing these files. Do not upload the frontend, a virtual environment, or local secrets with the backend.

**`main.py`**

```python
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
origins = [origin.strip() for origin in os.getenv("FRONTEND_ORIGINS", "").split(",") if origin.strip()]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=False,
    allow_methods=["GET"],
    allow_headers=[],
)

@app.get("/healthz")
def health():
    return {"ok": True}

@app.get("/api/message")
def message():
    return {"message": "Hello from FastAPI on Gregale"}
```

**`requirements.txt`**

```text
fastapi==0.141.1
uvicorn==0.52.1
```

**`Procfile`**

```text
web: uvicorn main:app --host 0.0.0.0 --port ${PORT:-8080}
```

**`gregale.yaml`**

```yaml
hosting:
  port: 8080
  health: /healthz
```

`FRONTEND_ORIGINS` is a comma-separated list of origins: scheme, domain, and optional port, with no path or trailing slash. If the list is empty, the API still responds to non-browser clients, but cross-origin browser code cannot read the response. CORS is not authentication: enforce authentication and authorization separately before adding private data, user actions, or writes.

## 2. Deploy the backend to Gregale

Use the **exact** production hostname shown by Vercel for your site. You can add a second origin for a custom domain explicitly. In this example the origin setting uses Gregale's runtime configuration file import; it is not a browser secret. Do not commit the config file. Pick a new app name unless you explicitly intend to replace an existing Gregale backend.

```bash
cd backend
APP=your-unique-api-name
FRONTEND_ORIGIN=https://your-frontend.vercel.app
CONFIG="$(mktemp)"
printf 'FRONTEND_ORIGINS=%s\n' "$FRONTEND_ORIGIN" > "$CONFIG"
gregale --non-interactive --json deploy --path . --source=worktree \
  --name "$APP" --secrets-file "$CONFIG" --yes
rm -f -- "$CONFIG"
gregale app update "$APP" --visibility public --public-auth open --no-require-authn
```

Use open ingress only on the disposable public demo or an API that enforces its own authentication. The deployment can be healthy while the edge still requires a Gregale token.

Copy the HTTPS URL and accepted deployment UUID from the deploy result; do not guess the hostname. Verify the exact release and then the public URL without a Gregale token:

```bash
DEPLOYMENT_ID=your-deployment-uuid
API_URL=https://your-deployed-api.example
gregale --non-interactive --json release verify "$DEPLOYMENT_ID" \
  --app "$APP" --path /api/message
curl -fsS "$API_URL/api/message"
```

Expected JSON: `{"message":"Hello from FastAPI on Gregale"}`. An unknown path should give an application HTTP 404. Check the CLI's `public_access_verified` field separately from `verified`; a control-plane check by itself does not show that a browser can reach the API. A health probe does not prove this route works either. See [Guided first deploy](https://gregale.dev/docs/quickstart) for what each verification proves.

## 3. Point Vercel at the API

In your Vercel project's **Settings → Environment Variables**, add `NEXT_PUBLIC_API_BASE_URL` with the API HTTPS URL (no route), scoped to **Production**, and redeploy the frontend. This is a public URL, not a credential. Next.js inlines `NEXT_PUBLIC_` values into browser builds, so changing the value does not update existing deployments. Never add Gregale API keys, shared service secrets, or private database URLs to `NEXT_PUBLIC_` variables.

In an App Router project, the following `app/page.tsx` provides a visible check. For an existing app, put the test component on a disposable route rather than replacing the home page.

```tsx
'use client';

import { useState } from 'react';

export default function Page() {
  const [status, setStatus] = useState('No request sent.');

  async function checkBackend() {
    const base = process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, '');
    if (!base) {
      setStatus('Set NEXT_PUBLIC_API_BASE_URL and redeploy.');
      return;
    }
    setStatus('Checking backend…');
    try {
      const response = await fetch(`${base}/api/message`, { cache: 'no-store' });
      if (!response.ok) throw new Error(`Backend returned HTTP ${response.status}`);
      const body = await response.json();
      if (body.message !== 'Hello from FastAPI on Gregale') {
        throw new Error('Unexpected API response');
      }
      setStatus(body.message);
    } catch (error) {
      setStatus(error instanceof Error ? error.message : 'Request failed');
    }
  }

  return (
    <main>
      <h1>FastAPI deployment check</h1>
      <button onClick={checkBackend}>Check backend</button>
      <p role="status">{status}</p>
    </main>
  );
}
```

Open the actual Vercel page, click **Check backend**, and expect **Hello from FastAPI on Gregale**. In the browser's Network panel confirm that `GET /api/message` went to the Gregale host, returned 200, and included `Access-Control-Allow-Origin` with your exact frontend origin. This last step tests the deployed browser path; a terminal check does not enforce CORS.

## Use the right backend in previews

Give **Preview** its own `NEXT_PUBLIC_API_BASE_URL` on Vercel and redeploy the branch. Use a separate staging API and data, not the production backend. For this direct-browser pattern, allow the actual preview origin in the staging API and verify it from that particular preview. Vercel can assign different preview URLs to a branch and to its individual deployments; the allowed origin must match the URL the browser actually uses. Prefer an intentionally stable staging hostname where available. Do not allow all `*.vercel.app` origins. For a backend per pull request, see [Connect a Vercel preview to the right backend PR](https://gregale.dev/articles/connect-vercel-preview-to-backend-pr).

If you need per-PR URLs without maintaining a browser CORS allowlist, use a server-side Next.js route handler with a same-origin browser request. Scope its upstream to a fixed, server-only `API_BASE_URL`; never forward a URL supplied by the caller. Authenticate requests to the route and to any protected upstream. A server proxy changes where the request is made, not who is authorized.

## Troubleshoot the path

- **API responds in curl, browser fails:** Inspect the request's `Origin` and the response headers. Add the exact frontend origin to `FRONTEND_ORIGINS` and redeploy the API. If you add JSON POST or an Authorization header, expand only the methods and headers your app needs; this example permits only GET.
- **Frontend still uses the old URL:** Check the variable's Production/Preview scope and redeploy after changing it.
- **Healthy app, wrong response:** Verify `/api/message` against the accepted deployment UUID and curl the public URL without credentials. If this updates an existing app, verify when rollout is complete.
- **Should both services live on Vercel instead?** [Vercel also hosts FastAPI](https://vercel.com/docs/frameworks/backend/fastapi). This split is for a team that wants an independent Python backend without moving its frontend.

References: [Gregale CLI quickstart](https://gregale.dev/docs/quickstart) · [Vercel environment variables](https://vercel.com/docs/environment-variables) · [Next.js browser environment variables](https://nextjs.org/docs/app/guides/environment-variables) · [FastAPI CORS middleware](https://fastapi.tiangolo.com/tutorial/cors/)

## Questions

### Do I need to move my Next.js frontend?

No. Keep the Vercel project and point it at the deployed FastAPI HTTPS URL.

### Does CORS protect private data?

No. Use authentication and authorization separately. The demo only returns a public, fixed message.

Canonical URL: https://gregale.dev/articles/deploy-fastapi-backend-nextjs-vercel

