---
title: "Part 6: test and deploy"
description: "Test the paid path with backend tests, a page test over the mock backend and one browser run, then deploy Panels as a sandbox demo and check it with doctor."
canonical_url: "https://nuxt-backend.dev/docs/start/tutorial/deploy"
---
# Part 6: test and deploy

> Test the paid path with backend tests, a page test over the mock backend and one browser run, then deploy Panels as a sandbox demo and check it with doctor.

Version: nuxt-backend 0.6.x · Tab: Start · Kind: tutorial · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Prove the paid path works at three levels, then deploy Panels as a public demo that charges and mails nobody for real.

<table>
<thead>
  <tr>
    <th>
      Part
    </th>
    
    <th>
      You add
    </th>
    
    <th>
      Accounts
    </th>
    
    <th>
      Time
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      6. Test and deploy
    </td>
    
    <td>
      Backend tests, a page test, one Playwright run, and a deployed demo on the providers' test modes
    </td>
    
    <td>
      A Convex account and a Vercel account
    </td>
    
    <td>
      30 min
    </td>
  </tr>
</tbody>
</table>

## Before you start

You need the app from [Part 5](https://nuxt-backend.dev/docs/start/tutorial/notify-and-share). For the deploy, you need:

- **A Convex account**, signed in with `npx convex login`. The demo gets a Convex project of its own, so its data never mixes with your development data ([Convex](https://nuxt-backend.dev/docs/services/convex)).
- **A Vercel account**, signed in with `npx vercel login` ([Vercel](https://nuxt-backend.dev/docs/services/vercel)). Another host works too: `deploy` prints what to set there.
- **The sandbox keys you already use:** the Polar sandbox token and the Resend key. A demo keeps every provider in its test mode.

Install the test tools once. `@edge-runtime/vm` runs the backend tests in the edge runtime, as the deployment runs them:

```bash
npm install -D vitest convex-test @edge-runtime/vm @nuxt/test-utils @vue/test-utils happy-dom @playwright/test
```

<steps level="3">

### Set up the test projects

One Vitest config with two projects: the backend functions on `convex-test` in the edge runtime, and the pages over the mock backend in Nuxt. The browser run is Playwright's.

```ts [vitest.config.ts]
import { defineConfig } from 'vitest/config'
import { defineVitestProject } from '@nuxt/test-utils/config'
import { backendTestAliases } from 'nuxt-backend/test-utils'

export default defineConfig({
  test: {
    projects: [
      {
        test: {
          name: 'backend',
          include: ['backend/**/*.test.ts'],
          environment: 'edge-runtime',
        },
      },
      await defineVitestProject({
        resolve: { alias: backendTestAliases() },
        test: {
          name: 'app',
          include: ['test/app/**/*.test.ts'],
          environment: 'nuxt',
          environmentOptions: { nuxt: { domEnvironment: 'happy-dom' } },
        },
      }),
    ],
  },
})
```

### Test the backend functions

`nuxt-backend/test` runs your functions on `convex-test`, with every component the scaffold mounts and a real session for each caller. No provider is called:

```ts [backend/strips.test.ts]
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('a strip belongs to the workspace it was made in', async () => {
  const t = testApp()
  const ada = await asUser(t)
  const grace = await asUser(t)
  const id = await ada.mutation(api.strips.create, { idea: 'A cat learns to surf' })
  expect(await ada.query(api.strips.get, { id })).toMatchObject({ idea: 'A cat learns to surf' })
  expect(await grace.query(api.strips.get, { id })).toBeNull()
})

test('a strip waits for credits', async () => {
  const ada = await asUser(testApp())
  const id = await ada.mutation(api.strips.create, { idea: 'A cat learns to surf' })
  await expect(ada.mutation(api.strips.generate, { id })).rejects.toMatchObject({ data: { code: 'not_ready' } })
  expect(await ada.query(api.strips.get, { id })).toMatchObject({ status: 'draft' })
})
```

No credits have reached a fresh workspace in the test, so `generate` is refused with `not_ready`, and the refusal rolls the whole mutation back.

```bash
npx vitest run --project backend
```

**You should see** both tests pass: Grace cannot read Ada's strip, and the refused generation left the strip a draft.

### Test a page over the mock backend

`createBackendMock` puts a fake backend and session under a page, so a test renders it with no deployment. Mount the strips list with one strip in it:

```ts [test/app/strips.test.ts]
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { createBackendMock, resetBackendMock } from 'nuxt-backend/test-utils'
import { afterEach, expect, test } from 'vitest'
import StripsPage from '~/pages/strips/index.vue'

afterEach(() => resetBackendMock())

test('the list shows the workspace\'s strips', async () => {
  createBackendMock({
    user: { name: 'Ada' },
    queries: {
      'strips:list': [{ _id: 'strip_1', idea: 'A cat learns to surf', status: 'ready', panels: [] }],
    },
  })
  const page = await mountSuspended(StripsPage)
  expect(page.text()).toContain('A cat learns to surf')
})
```

[Test pages over a mock backend](https://nuxt-backend.dev/docs/develop/testing/pages) covers what else the mock answers.

### Run the paid path in a browser

One Playwright run covers what the mocks cannot: a real sign-in, a real checkout on Polar's sandbox, and a real strip. Point Playwright at the app, which it starts with `npm run dev` unless one is running already:

```ts [playwright.config.ts]
import { defineConfig, devices } from '@playwright/test'

export default defineConfig({
  testDir: 'e2e',
  timeout: 240_000,
  use: {
    baseURL: 'http://localhost:3000',
    trace: 'on-first-retry',
    ...devices['Desktop Chrome'],
  },
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:3000/login',
    reuseExistingServer: true,
    timeout: 180_000,
  },
})
```

A strip draws in about a minute on real models, so a test has four. Polar owns its checkout page, and its fields can change between its releases, so one helper follows them. It pays with the test card, `4242 4242 4242 4242`, any future expiry and any CVC:

```ts [e2e/checkout.ts]
import { expect, type Page } from '@playwright/test'

export async function payWithTestCard(page: Page) {
  await page.waitForURL(/sandbox\.polar\.sh/)
  const card = page.frameLocator('iframe[title*="payment"]').first()
  await card.getByLabel('Card number').fill('4242 4242 4242 4242')
  await card.getByLabel(/Expiration/).fill('12 / 34')
  await card.getByLabel('Security code').fill('123')
  await page.getByRole('button', { name: /^(Pay|Subscribe)/ }).click()
  await page.waitForURL(/localhost:3000/, { timeout: 60_000 })
  await expect(page).not.toHaveURL(/polar\.sh/)
}
```

The run signs in by code. `npx nuxt-backend inbox <address> --json` prints `{ address, deployment, messages, code }`, so the run reads the newest sign-in code from `.code`, and the payment uses the test card:

```ts [e2e/paid-path.spec.ts]
import { execFileSync } from 'node:child_process'
import { expect, test } from '@playwright/test'
import { payWithTestCard } from './checkout'

const address = `delivered+e2e-${Date.now()}@resend.dev`

function latestCode(to: string): string | null {
  return JSON.parse(execFileSync('npx', ['nuxt-backend', 'inbox', to, '--json'], { encoding: 'utf8' })).code
}

test('sign in, buy credits and draw a strip', async ({ page }) => {
  await page.goto('/login')
  await page.getByRole('button', { name: 'Continue with email code' }).click()
  await page.getByLabel('Email').fill(address)
  await page.getByRole('button', { name: 'Email me a code' }).click()
  await expect.poll(() => latestCode(address), { timeout: 30_000 }).toBeTruthy()
  await page.getByLabel('Verification code').fill(latestCode(address)!)
  await page.getByRole('button', { name: 'Verify' }).click()
  await page.getByRole('button', { name: 'Skip for now' }).click({ timeout: 10_000 }).catch(() => {})
  await expect(page).not.toHaveURL(/\/login/)

  await page.goto('/pricing')
  await page.getByRole('article').filter({ hasText: '100 credits' }).getByRole('button', { name: 'Top up' }).click()
  await payWithTestCard(page)
  await expect(page.getByRole('link', { name: /credits$/ })).toContainText('130', { timeout: 30_000 })

  await page.goto('/strips')
  await page.getByLabel('Idea for a new strip').fill('A cat learns to surf')
  await page.getByRole('button', { name: 'Start a strip' }).click()
  await page.getByRole('button', { name: 'Draw this strip for 30 credits' }).click()
  await expect(page.getByText('AI-generated')).toBeVisible({ timeout: 180_000 })
})
```

The form offers a passkey where the browser supports them, so the run skips it when it is offered. [Run end-to-end tests](https://nuxt-backend.dev/docs/develop/testing/e2e) covers the CI job.

**You should see** the run end on a finished strip, about two minutes after it starts.

### Make panels a public demo

A demo runs the same build as production while every provider stays in its test mode: `BACKEND_ENVIRONMENT=sandbox`. Anyone can sign up there, and the model calls are real, so Panels holds itself to a public demo when `isDemo()` is true. Parts 1 to 5 already wrote most of it: an idea of one's own needs a passkey sign-in (`create`), a canned idea is a free copy once drawn and refused before (`generate`), share links are off (`storage.ts`), and `spendLimit` pauses AI for the rest of a costly day (`ai.ts`). The rest is in the template, and this step names it.

Accounts on the demo hold no real address. `canSignIn` in `backend/auth.ts` admits only a generated sandbox identity, `delivered+<label>@resend.dev` with a random label of 16 or more characters, whose codes the sign-in page reads from the dev inbox. The same check guards invitations and changes of address:

```ts [backend/auth.ts]
const SANDBOX_IDENTITY = /^delivered\+[a-z0-9]{16,}@resend\.dev$/
// …
export function admitsAddress(email: string): boolean {
  return backendEnvironment() !== 'sandbox' || SANDBOX_IDENTITY.test(email.trim().toLowerCase())
}
// …
  canSignIn: async (_ctx, { email }) => admitsAddress(email) || { allowed: false, message: SANDBOX_IDENTITY_HELP },
```

A page reads those codes with `useSandboxInbox`, which calls `getSandboxInbox` ([Read test mail in the dev inbox](https://nuxt-backend.dev/docs/develop/dev-inbox) puts it beside `<AuthForm>`). The starter's `backend/email.ts` already exports it; keep it:

```ts [backend/email.ts]
export const { getSandboxInbox } = email.api
```

It answers only on a deployment that is not `production` and has `EMAIL_DEV_INBOX=1`, and never shows an administrator's or a passkey-only account's mail. `nuxt-backend dev` sets the variable on your dev deployment, and `deploy --sandbox` on the demo's (next step).

The canned ideas are drawn once: the admin console's **Demo** tab calls `demo.seed`, and your own tooling can run `npx convex run demo:seedInternal` with a deploy key. Both queue one free job per canned idea not drawn yet, and leave an idea whose seed job still waits or draws to it. The app runs those jobs for itself, so the panels are the app's own files, not the administrator's. This listing names the parts that matter; copy the rest of [`backend/demo.ts`](https://github.com/qruto/nuxt-backend/blob/main/templates/panels/backend/demo.ts) from the template: `fillCache`, the seed job's steps `writeCannedCaptions` and `drawCannedPanel`, which ask the models through Part 4's `captionsFor` and `panelFor`, and `cachePanel`, which keeps each panel in the cache. Copy the Demo tab too, [`app/pages/admin/demo.vue`](https://github.com/qruto/nuxt-backend/blob/main/templates/panels/app/pages/admin/demo.vue): a page with `adminTab` in its `definePageMeta` joins the console as a tab.

```ts [backend/demo.ts]
const { jobId } = await jobs.enqueue(ctx, internal.demo.drawCanned, { ideaId: id }, { billTo: 'app' })
// …
export const seed = admin.mutation({
  recentSignIn: false,
  args: {},
  handler: ctx => fillCache(ctx),
})
// …
export const seedInternal = internalMutation({
  args: {},
  handler: ctx => fillCache(ctx),
})
// …
export const drawCanned = jobs.define({
  meter: false,
  cost: 0,
```

Once a canned idea is drawn, a strip started from it copies the panels at 0 credits, with no model call (`generate`, Part 4). Until then its button waits, and `generate` refuses it.

The demo starts each day clean. At 03:00 UTC a cron deletes every strip older than a day, and anywhere but a `sandbox` deployment the run does nothing:

```ts [backend/crons.ts]
crons.cron('reset the demo', '0 3 * * *', internal.demo.reset, {})
```

`reset` and the pass it starts end `backend/demo.ts`. `defineRetention` deletes the old strips in batches, by their creation time:

```ts [backend/demo.ts]
export const pruneStrips = defineRetention(internalMutation, {
  fn: 'demo:pruneStrips',
  table: 'strips',
  index: 'by_creation_time',
  ttl: DAY,
  onDelete: deleteStrip,
})

export const reset = internalMutation({
  args: { now: v.optional(v.number()) },
  handler: async (ctx, { now }) => {
    if (!isDemo()) return false
    await ctx.scheduler.runAfter(0, internal.demo.pruneStrips, now === undefined ? {} : { now })
    return true
  },
})
```

Each deletion goes through `deleteStrip`, which takes what hangs off the strip with it: its photo, its panels unless they are the cache's, its share link, and the notifications that link to it. `notifications.forget` deletes an app kind's notifications by their target, up to 200 per call:

```ts [backend/strips.ts]
export async function deleteStrip(ctx: MutationCtx, strip: Doc<'strips'>) {
  await storage.release(ctx, strip.photoId)
  if (!strip.cached) {
    for (const panel of strip.panels) await storage.release(ctx, panel.imageId)
  }
  await storage.revokeShareLink(ctx, 'strips', strip._id)
  await notifications.forget(ctx, { kind: 'app.strip_ready', target: strip._id })
}
```

The same deletion serves an account's erasure, on the demo and everywhere else. `setupAccount` in `backend/account.ts` takes your own tables as `sources`: an export lists the strips the account started, and an erasure deletes them. They are deleted rather than anonymised: the idea is the author's own words and the panels were drawn from their photo, so a strip without its author's name would still be theirs.

```ts [backend/account.ts]
export const account = setupAccount(components, {
  audit,
  billing,
  email,
  paths,
  sources: {
    strips: {
      description: 'The strips the account started: each idea, its photo and its drawn panels.',
      export: internal.strips.exportFor,
      forget: internal.strips.forgetFor,
    },
  },
})
```

```ts [backend/strips.ts]
export const exportFor = internalQuery({
  args: { userId: v.string() },
  handler: async (ctx, { userId }) => {
    const strips = await ctx.db.query('strips').withIndex('by_author', q => q.eq('authorId', userId)).take(1000)
    return strips.map(strip => ({
      id: strip._id,
      createdAt: new Date(strip._creationTime).toISOString(),
      workspaceId: strip.workspaceId,
      idea: strip.idea,
      status: strip.status,
      photoId: strip.photoId ?? null,
      panels: strip.panels,
    }))
  },
})

export const forgetFor = internalMutation({
  args: { userId: v.optional(v.string()), email: v.optional(v.string()) },
  handler: async (ctx, { userId }) => {
    if (userId === undefined) return { done: true }
    const strips = await ctx.db.query('strips').withIndex('by_author', q => q.eq('authorId', userId)).take(50)
    for (const strip of strips) {
      await deleteStrip(ctx, strip)
      await ctx.db.delete('strips', strip._id)
    }
    return { done: strips.length < 50 }
  },
})
```

`forgetFor` deletes a batch and answers `{ done: false }` while strips are left, and the erasure runs it again. An address with no account started no strip.

Panels' own refusals each get a sentence, read as `errors.<code>_<reason>`: the passkey the demo asks for, a hidden strip, a canned idea the demo has not drawn yet, and a strip with nothing to try again:

```ts [app/app.config.ts]
errors: {
        forbidden_passkey_required: 'On the public demo, an idea of your own needs a passkey sign-in. Add a passkey on your security page, sign in with it, or start from one of the ideas above.',
        forbidden_hidden: 'An administrator hid this strip after a report. It can no longer be drawn or changed.',
        not_ready_idea_not_drawn: 'The demo has not drawn this idea yet. Start from another one.',
        invalid_input_not_stopped: 'This strip is still drawing, or done. Nothing to try again.',
      },
```

The package adds the rest on any `sandbox` deployment: an administrator acts as one only from an account that signs in with passkeys only (`forbidden`, reason `passkey_only_admin`), the dev inbox never shows an administrator's or a passkey-only account's mail, and AI is refused while `setupAi` sets no `spendLimit` (`not_ready`, reason `no_budget`). [Deploy a demo or staging app](https://nuxt-backend.dev/docs/ship/deploy/staging) lists every limit.

### Deploy panels as a demo

Create a Convex project for the demo in the dashboard, and put its production deploy key in your shell. Deploy with `--sandbox`, so the production deployment runs as a demo and `deploy` asks for your sandbox keys rather than live ones:

```bash
npx nuxt-backend deploy --sandbox
```

`--sandbox` sets `BACKEND_ENVIRONMENT=sandbox`, and `EMAIL_DEV_INBOX=1`, so `getSandboxInbox` answers with each code the demo sends. A later `npx nuxt-backend deploy` without it keeps `sandbox`, since it only sets `production` on a deployment that does not already hold `sandbox`.

`deploy` links the deployment and generates its own secrets. It deploys the backend, syncs the catalog to Polar's sandbox, registers both webhooks and writes the Vercel project's env. It does not carry the AI gateway key, nor the key that signs Panels' content credentials. Push both, from `.env.local`; the push generates the signing key and its certificate when `.env.local` has none, and leaves `sandbox` as it is:

```bash
npx nuxt-backend env push --prod
```

`deploy` ends with `doctor --prod`, which fails until those keys are set: run it again now, and whenever you change the demo's env. Push to the production branch, or run `npx vercel deploy --prod`, for the app to build with that env.

```bash
npx nuxt-backend doctor --prod
```

Then make yourself the administrator with `npx nuxt-backend doctor --fix`, turn on passkey-only sign-in for that account, sign in with your passkey, and press **Draw the canned strips** on the console's Demo tab.

**You should see** `doctor --prod` end with no failure. Its warnings include that `BACKEND_ENVIRONMENT` is `sandbox`, which a demo means, and any optional service you left unset, such as monitoring: read each, and decide. Open the Vercel URL and sign in as a `delivered+…@resend.dev` address; `useSandboxInbox` reads its code.

</steps>

## Check your work

- `npx vitest run` passes the backend and page tests, and `npx playwright test` passes the paid path.
- `npx nuxt-backend status --prod` shows billing, email and AI as `test`, and the rest as `live`.
- On the demo, a canned idea's button waits until the Demo tab has drawn it. Then a strip from it says **Copy this strip for free**, and is ready at once, for 0 credits.
- Type an idea of your own after signing in with a code. The form asks for a passkey sign-in.
- Open a finished strip. Its share section says sharing is off on the public demo.

When you are ready to charge real customers, deploy a second project with live keys and `BACKEND_ENVIRONMENT=production`. Walk the [Production checklist](https://nuxt-backend.dev/docs/ship/checklist) first, and [Compliance](https://nuxt-backend.dev/docs/ship/compliance) for what a client app owes its users.

## What you used

- `defineBackendTestApp` and `asUser` ([Test backend functions](https://nuxt-backend.dev/docs/develop/testing/functions)).
- `createBackendMock` ([Test pages over a mock backend](https://nuxt-backend.dev/docs/develop/testing/pages)).
- Playwright with `inbox --json` and the test card ([Run end-to-end tests](https://nuxt-backend.dev/docs/develop/testing/e2e)).
- `BACKEND_ENVIRONMENT=sandbox`, `canSignIn`, `EMAIL_DEV_INBOX` with `getSandboxInbox`, and `notifications.forget` ([Deploy a demo or staging app](https://nuxt-backend.dev/docs/ship/deploy/staging), [Read test mail in the dev inbox](https://nuxt-backend.dev/docs/develop/dev-inbox)).
- `setupAccount({ sources })` for the strips in an export and an erasure ([Join your own tables](https://nuxt-backend.dev/docs/build/auth/accounts/data#join-your-own-tables)).
- `jobs.enqueue(…, { billTo: 'app' })` for the demo's own jobs ([Run generation jobs](https://nuxt-backend.dev/docs/build/ai/jobs)).
- `npx nuxt-backend deploy` and `doctor --prod` ([Deploy in one command](https://nuxt-backend.dev/docs/ship/deploy/one-command)).

## Next

Panels is live. From here:

- [Grow your app](https://nuxt-backend.dev/docs/build/growth): a waitlist, referrals, promotions and lifecycle emails.
- [Customization ladder](https://nuxt-backend.dev/docs/build/ui/customize): give the packaged pages Panels' own look, or take them headless.
- [Build your app](https://nuxt-backend.dev/docs/build): every feature, grouped by what you build.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
