# Move an existing app to Scava - Next.js, API routes, Supabase, own login

An app that already runs somewhere else, for example on Vercel with Supabase and a login of its own, can move to Scava as a whole. It does not have to shrink to a demo. Almost every part has a counterpart: the pages become a static build, the API routes become server code, the login and the codes from an authenticator app come from Scava, cron jobs become schedules. This page is the checklist for the agent that does the move. It says what changes, what stays, and what Scava cannot do.

## Before you start

The app fits Scava when the people who use it are known and sign in: colleagues, partners, clients. It cannot move as it is when one of these is essential to it:

- **Public pages or visitors without a sign-in**, such as a website, a shop or a public sign-up. Every page of every app needs a signed-in person with access.
- **A connection the app keeps open to another service**, such as Slack's Socket Mode or Discord's gateway. Web sockets of the app's own pages and agents that run around the clock work: see [Agents](/docs/app-agents). Bots use the webhooks of their service.
- **A database reachable only over its own network connection**, such as a direct PostgreSQL, MySQL or MongoDB connection or an ORM that opens one. Server code reaches other services only over http and https.

If one of these is essential, tell the person before you start, instead of moving a reduced version. [When Scava fits](/docs/compare) lists more cases.

These parts are removed or replaced during the move, because the browser does not load them (see [What the browser allows](/docs/hosting#what-the-browser-allows)):

- Analytics, ads, chat widgets, embedded videos and map tiles from other sites.
- Images from other sites, such as a public storage bucket. Store them with `scava.files`, or let server code fetch and serve them at `/api/...`.
- Direct calls from the page to other sites. The page calls its own `/api/...`, and the server code calls the other site.
- The address of the old site in the code. Use paths like `/api/items`, never a full address, because the app can also run on an [own address](/docs/custom-domains) of the company.

## What becomes what

| In the app today | On Scava |
|---|---|
| Pages rendered by a framework | A static build, published as a folder |
| API routes, server actions, middleware | One `fetch()` in `server/index.js`, called by the pages at `/api/...` |
| Login, passwords, sessions, password reset | Removed. Scava signs people in, and `scava.me()` says who it is |
| Codes from an authenticator app | Removed from the app. The agent turns on the code of Scava (or the owner ticks one box on the app page) |
| User table and roles | Shares, groups and the rules in `scava.json` |
| A database with an http API, such as Supabase or Firebase | Kept and called from server code, or moved into `scava.db` |
| File storage, such as S3 or Supabase Storage | `scava.files`, or kept and served through server code |
| Environment variables with keys | Secrets that the owner sets on the app page |
| Cron jobs | `schedules` in `scava.json` |
| Incoming webhooks, calendar feeds | `webhooks` in `scava.json`, each with its own key |
| Push notifications | `"notifications": true` and `env.SCAVA.push()` |
| Camera, microphone, location | `"devices"` in `scava.json`; the browser asks each person |
| Payment forms, maps, videos, chat widgets from other sites | `"embeds"` in `scava.json` with their host names |
| Email | `env.SCAVA.mail()` to people with access |
| Sign-in with another service (OAuth) | Its return address points to the app's `/api/...` |
| Long jobs: PDFs, Python, ffmpeg | `env.SCAVA.run()` |

## The pages

Build the pages the way the framework builds static files, and publish the output folder. Every app has a whole address to itself, so the defaults of the build work, without a base path or prefix.

- **Vite, React, Vue, Svelte, Angular:** publish `dist`, or the folder the build names. Client-side routing works: a path without a file ending that has no page of its own gets `index.html`.
- **Next.js with a server**, with server components, server actions, route handlers or middleware: it moves as it is, see [Next.js](/docs/nextjs). The rest of this section is for apps that become static files.
- **Next.js as static files:** set `output: 'export'` in `next.config.js`, and `images: { unoptimized: true }` when the app uses `next/image`. `next build` then writes the folder `out`. Scava serves `/about` from `about.html`, as the export writes it, so `trailingSlash` is not needed.
- **SvelteKit** with `adapter-static`, **Nuxt** with `nuxt generate`, **Astro** with its default static output: publish the folder they write.

In Next.js, these parts do not exist after an export, and this replaces them (or keep the server, see [Next.js](/docs/nextjs)):

- `getServerSideProps`, server components that read cookies or headers, server actions and middleware: the page loads its data in the browser from the app's own `/api/...`, and the work moves into server code.
- Route handlers in `app/api`: an export refuses them, so move them out of `app/` before `next build`, for example to `api/`, and call them from server code (see below).
- A page per id, such as `/items/[id]`, exists only for the ids known at build time (`generateStaticParams`). For data that changes, use one page with a parameter, `/item?id=42`, and read it with `useSearchParams` inside `<Suspense>`. A path without a page of its own shows `index.html`, the start page.

The upload check warns when code names other websites. Names inside the framework's own code, such as links to its documentation in error messages, are harmless. A Next.js build made on Windows names some of its prefetch files wrongly, so the test run may list missing files whose names start with `__next`. The pages work without them.

## API routes become server code

Server code is one object with `fetch(request, env)` in `server/index.js`, in the shape of a Cloudflare Worker. Scava sends every request for `/api` or `/api/...` there, after it checked the sign-in and the access. See [Server code](/docs/server-code).

```js
// src/server.js
import { GET as listItems, POST as addItem } from '../api/items/route.js';

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (url.pathname === '/api/items' && request.method === 'GET') return listItems(request, env);
    if (url.pathname === '/api/items' && request.method === 'POST') return addItem(request, env);
    return new Response('Not found', { status: 404 });
  },
};
```

- Route handlers of Next.js take a standard `Request` and return a `Response`, so they can be called like this. Replace `NextResponse` with `Response`, and `cookies()` and `headers()` from `next/headers` with `request.headers`. A handler with a dynamic segment gets it as its second argument: pass `{ params: Promise.resolve({ id }) }`.
- The person who asks is `await env.SCAVA.me()`: `{ email, name, role, groups }`. It replaces the session lookup of the old app.
- Express, Fastify and similar servers do not run, because there is no port to listen on. Move their routes into `fetch()`, or use a router made for Workers, such as Hono, whose app is such an object.
- Read keys from `env`, the second argument of `fetch()`, not from `process.env`.
- Nothing is sure to stay in memory from one request to the next. Counters, caches and rate limits belong in `env.SCAVA.db()`. Scava already limits floods of requests before they reach the app.
- There is no file system, no child process and no raw network connection. The built-in modules that work are listed in [What the code can import](/docs/server-code#what-the-code-can-import).

Bundle the server code into one file, with its packages, after the page build: a new build empties the output folder. esbuild also compiles TypeScript: name the entry `src/server.ts`.

```bash
npx esbuild src/server.js --bundle --format=esm --platform=neutral --main-fields=browser,module,main --conditions=workerd,worker,browser --outfile=out/server/index.js
```

As one script in `package.json`, with `esbuild` in the `devDependencies`:

```json
{
  "scripts": {
    "build": "next build && esbuild src/server.js --bundle --format=esm --platform=neutral --main-fields=browser,module,main --conditions=workerd,worker,browser --outfile=out/server/index.js"
  }
}
```

Then publish with `npx -y scava-ai setup out`.

## Login, users and roles

Remove the app's own login completely: sign-in and sign-up pages, password fields, password reset, session cookies, token checks and auth middleware. Scava signs people in with Google or a code by email before they see any page or reach `/api`. The upload check refuses password fields.

- **Who it is:** `await scava.me()` in the page, `await env.SCAVA.me()` in server code. The email address is the stable key of a person: where the old app stored a user id, store the email address.
- **Who gets in:** share the app with addresses, a company domain such as `@company.com`, or a group. Nobody signs up on their own; people get in through a share, or ask for access and the owner approves. See [Sharing](/docs/sharing).
- **Roles:** groups, which the owner makes on the Overview page, and the rules in `scava.json`. Use `role` and `groups` from `me()` only to show or hide buttons. See [Permission rules](/docs/rules).
- **Codes from an authenticator app:** the agent turns on "Ask for a code from an authenticator app" (`change_app` with `two_step`, or the owner ticks it on the app page), and Scava asks everyone who opens the app, the owner included. The secrets of the old app cannot be moved: each person scans a QR code once. See [A code from an authenticator app](/docs/login#a-code-from-an-authenticator-app).

## Data: keep the database or move it

### Keep it

Server code calls the database over its http API. The browser cannot call another site, so each page that read the database directly now calls the app's own `/api/...`, and server code calls the database. For Supabase:

1. The owner sets the key as a secret on the app page, bound to the host of the project, for example `SUPABASE_KEY` for `abcdefgh.supabase.co`. Agents never handle key values; they tell the owner the name and the host.
2. Server code uses `env.SUPABASE_KEY` exactly like the key. Scava puts the real key in when the request leaves for that host:

```js
const res = await fetch('https://abcdefgh.supabase.co/rest/v1/items?select=*', {
  headers: { apikey: env.SUPABASE_KEY, authorization: 'Bearer ' + env.SUPABASE_KEY },
});
```

The client library `@supabase/supabase-js` works too, bundled with the command above.

Supabase sees only the server code, not the person behind a request. Row level security that relies on Supabase's own sign-in (`auth.uid()`) therefore no longer tells people apart. Use a key that may reach what the app needs, and decide in server code with `env.SCAVA.me()`.

A value the code computes with, such as a secret for signing tokens, is a readable secret: the owner sets it without a service. See [Secrets and API keys](/docs/server-code#secrets-and-api-keys).

### Move it into `scava.db`

`scava.db` stores JSON entries in collections. Pages read and write it directly, under the rules in `scava.json`, with no server code. There is no SQL and no query language: list the entries and filter them. See [Database](/docs/database).

- A table becomes a collection, a row becomes an entry. Keep relations as ids inside the entries.
- Import through server code. A page that only the owner opens reads the export of the old database, for example a JSON file the owner picks, and sends its rows in parts to an `/api/import` route, which checks that `me.role` is `"owner"` and adds them with `env.SCAVA.db('items').add(row)`.
- Send up to 200 rows per request: one request of server code can make at most 500 calls to `env.SCAVA`. Server code changes at most 5,000 entries in 10 minutes, so a larger import waits between parts.
- Imported rows count as created by the person who runs the import, normally the owner. Rules with `"own"` therefore do not give people their old rows. Keep each person's email address in the entry and let server code decide who may change it, or use rules with groups for these collections.
- Remove the import route after the move.

Files move the same way, with `env.SCAVA.files('name').put(fileName, bytes)`, up to 25 MB per file. See [Files](/docs/files).

## Cron jobs, webhooks and feeds

- **Cron jobs** become schedules in `scava.json`. They run `scheduled(event, env)` of the server code, in the time zone you name. A run that fails is tried once more. See [Schedules and webhooks](/docs/schedules-webhooks).
- **Incoming webhooks** get the address `https://<app address>/_scava/hook/<name>?key=...`. Each webhook has its own key, which the owner sees on the app page; the other service gets the full address. Check the other service's signature in the code, with its signing secret as a readable secret.
- **Calendar feeds and other feeds** work as webhooks. The answer keeps its content type, for example `text/calendar`, and other parameters of the address stay. Calendar apps subscribe to the address with its key.

## Notifications and email

- **Push notifications:** remove the app's own push code: its service worker for push, its VAPID keys and the sending to push services. Put `"notifications": true` into `scava.json` and send with `env.SCAVA.push({ to, title, text, url })`. People turn notifications on in the panel of every page, or with a button of the app. On iPhone and iPad this works once the app is on the Home Screen. See [Notifications](/docs/server-code#notifications).
- **Email:** `env.SCAVA.mail()` sends plain text to people who have access to the app. Mail to anyone else, for example customers who never sign in, needs a mail provider of your own, called from server code with a bound key.

## Sign-in with another service

When the app connects to another service with OAuth, such as a bank, a calendar or a social network:

- Register the return address `https://<app address>/api/<route>` with the service. It changes with the move, and again if the app gets an own address.
- The return is a normal page load of the signed-in person, so server code receives it together with the person. Use the usual return by address (a GET request), not a form that the other site posts: Scava refuses changing requests from other sites.
- The client secret of the service is a secret bound to the service's host. Scava puts a bound key only into the address and the headers, so send it with HTTP Basic authentication (`authorization: 'Basic ' + btoa(clientId + ':' + env.CLIENT_SECRET)`), which most services accept. A service that wants it in the body of the request needs a readable secret.
- Store the tokens the service hands out in a collection that only the owner reads and writes, and use them from server code.

## Size

A version can hold 50 MB and 2,000 files when published with `npx -y scava-ai setup`, and 10 MB when an AI passes the files in a chat. Large files such as models are sent to browsers as a stream. Files that change without a new version, such as uploads, belong in `scava.files`, up to 25 MB each. See [Limits](/docs/limits).

## After the move

1. Publish with `npx -y scava-ai setup <output folder>`. The test run lists errors, blocked calls and missing files, each with a hint.
2. Ask the owner to set the secrets on the app page, and turn on the code from an authenticator app if the old app had one.
3. Change the addresses at the other services: webhooks, OAuth return addresses, calendar subscriptions.
4. Share the app with the people who used it.
5. Run each schedule once with "Run now" on the app page, and check the server part with `npx -y scava-ai server`.
