---
title: "Part 1: sign in"
description: "Create Panels from the starter, run it on a local deployment, sign in with the code in the terminal, and model strips per workspace."
canonical_url: "https://nuxt-backend.dev/docs/start/tutorial/sign-in"
---
# Part 1: sign in

> Create Panels from the starter, run it on a local deployment, sign in with the code in the terminal, and model strips per workspace.

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.

Create the app from the starter, run it, sign in, and store strips per workspace.

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

<tbody>
  <tr>
    <td>
      1. Sign in
    </td>
    
    <td>
      The app, sign-in with a code or a passkey, and a list of strips that belongs to a workspace
    </td>
    
    <td>
      None
    </td>
    
    <td>
      15 min
    </td>
  </tr>
</tbody>
</table>

## Before you start

You need Node 24.11 or later and a terminal. No account is needed: this part runs on a local deployment, and sign-in codes print in your terminal.

Every listing in the tutorial is code from the finished app, the [Panels template](https://nuxt-backend.dev/docs/start/templates). A line that reads `// …` or `<!-- … -->` marks code the listing leaves out: code a later part adds, which the text says, or code that stays as it is. The template explains each file in comments; the listings leave those out, and the text explains instead.

<steps level="3">

### Create the app from the starter

The starter is a Nuxt app with the module installed and its backend files written. Create Panels from it, then start it on a local deployment:

```bash
npm create nuxt@latest panels -- -t gh:qruto/nuxt-backend/templates/starter
cd panels
npx nuxt-backend dev --anonymous
```

`nuxt-backend dev` runs Convex and Nuxt together, and `--anonymous` creates a deployment on your machine that needs no account. The first run gives it an `AUTH_SECRET`, a `SITE_URL` and a `BACKEND_ENVIRONMENT` of `development`.

To add Panels to a Nuxt app you already have, run `npx nuxt module add nuxt-backend` instead. It writes the same files ([Installation](https://nuxt-backend.dev/docs/start/installation)).

**You should see** `backend preflight: …` in the terminal, then Nuxt's local URL. The email and billing findings in the preflight are expected: you connect those services in later parts.

### Sign in with the code in the terminal

Open [localhost:3000/login](http://localhost:3000/login). The module mounts this page, and `<AuthForm>` on it drives the whole sign-in through `useLoginFlow`. Type your email and ask for a code. No email provider is connected yet, and a `development` deployment logs every code, so it prints in the terminal running `dev`.

Paste the code. The form then offers to add a passkey: accept, and your next sign-in takes a fingerprint or a PIN instead of a code. A code works only in the browser that asked for it, so paste it into the same window.

**You should see** the starter's `/app` page inside the app shell: the Personal workspace in the switcher and the part of your address before the `@` in the account menu. Your account already has a personal workspace: the unit that pays, holds members and owns data. The first sign-in also leads you once to `/welcome`, where you can give yourself a name; **Skip setup** is fine for now.

### Name panels' paths

The backend writes links to Panels' pages: the inbox notification, the ready email, a report in the admin console. Keep those paths in one file, so the backend and `nuxt.config.ts` read the same ones:

```ts [backend/routes.ts]
export const base = ''

export const routes = {
  strips: `${base}/strips`,
  strip: (id: string) => `${base}/strips/${id}`,
  share: `${base}/s`,
  welcome: `${base}/welcome`,
}
```

`base` is where the app's pages are mounted: nothing, at the root of your app. This site runs the same files under `/playground`, and sets `base` there on this one line. For the same reason, Panels' pages never write a path of their own: they link by route name, such as `{ name: 'strips-id', params: { id } }`, and to a packaged page through `useBackendPagePath('pricing')`.

Send people to their strips after sign-in. The `welcome` line is for the first-run page the template adds, which replaces the packaged one at the same path:

```ts [nuxt.config.ts]
import { routes } from './backend/routes'
// …
  backend: {
    redirects: { afterSignIn: routes.strips },
    pages: { welcome: routes.welcome },
  },
})
```

Panels has no `/app` page: delete `app/pages/app/`. The starter's landing page links there, so replace it with Panels' own, which links to the strips by name:

```vue [app/pages/index.vue]
<script setup lang="ts">
const { isSignedIn } = useAuth()
</script>

<template>
  <div class="page">
    <h1>Panels</h1>
    <p>
      Turn an idea and a photo into a three-panel comic strip, drawn by a
      model, and share it by a link anyone can open.
    </p>
    <p>
      <NuxtLink :to="{ name: 'strips' }">
        {{ isSignedIn ? 'Open your strips' : 'Sign in to start a strip' }}
      </NuxtLink>
    </p>
    <!-- … -->
  </div>
</template>
```

The strips page asks a signed-out visitor to sign in and brings them back, so the one link serves both.

### Model strips per workspace

A strip belongs to the workspace it was made in, so everyone in that workspace sees it and nobody else does. Write the schema. Later parts fill the photo, the job and the panels:

```ts [backend/schema.ts]
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'

const panel = v.object({ imageId: v.string(), caption: v.string() })

export default defineSchema({
  strips: defineTable({
    workspaceId: v.string(),
    authorId: v.string(),
    authorEmail: v.string(),
    idea: v.string(),
    ideaId: v.optional(v.string()),
    status: v.union(v.literal('draft'), v.literal('queued'), v.literal('ready')),
    photoId: v.optional(v.string()),
    jobId: v.optional(v.string()),
    panels: v.array(panel),
    cached: v.optional(v.boolean()),
    hidden: v.optional(v.boolean()),
  })
    .index('by_workspace', ['workspaceId'])
    .index('by_author', ['authorId']),

  cannedStrips: defineTable({
    ideaId: v.string(),
    jobId: v.optional(v.string()),
    panels: v.array(panel),
    ready: v.boolean(),
  }).index('by_ideaId', ['ideaId']),
})
```

The photo and the panel images live in the package's storage, not in your app's `_storage` table, so their ids are plain strings. `by_author` finds an account's strips for its export and its erasure ([Part 6](https://nuxt-backend.dev/docs/start/tutorial/deploy)). `ideaId`, `cached` and the `cannedStrips` table are for the canned ideas: a few ideas Panels suggests, which the public demo draws once and copies for free ([Part 6](https://nuxt-backend.dev/docs/start/tutorial/deploy)).

The scaffold's `backend/functions.ts` already exports the access tiers. `workspace` is the one Panels uses: its functions run only for a signed-in member, and `ctx.workspace` is the caller's active workspace, read fresh on every call.

```ts [backend/functions.ts]
import { createFunctions } from 'nuxt-backend/functions'
import { components } from './_generated/api'
import { action, mutation, query } from './_generated/server'
import { billing } from './billing'
import { rateLimiter } from './rateLimiter'

export const { authed, workspace, admin, withRole, withFeature, setUserRole } = createFunctions(
  { query, mutation, action },
  { components, billing, rateLimiter, limits: { authed: 'write', workspace: 'write' } },
)
```

The canned ideas go in `backend/demo.ts`, with `isDemo()`, which is true on a `sandbox` deployment, the public demo. The page reads them through `status`:

```ts [backend/demo.ts]
import { backendEnvironment } from 'nuxt-backend/app'
// …
import { internalMutation, type MutationCtx, query, type QueryCtx } from './_generated/server'
// …
export const isDemo = () => backendEnvironment() === 'sandbox'

export const TEMPLATE_URL = 'https://github.com/qruto/nuxt-backend/tree/main/templates/panels'

export const CANNED_IDEAS = [
  { id: 'surfing-cat', idea: 'A cat learns to surf' },
  { id: 'moon-bus', idea: 'The last bus on the moon' },
  { id: 'robot-baker', idea: 'A robot bakes bread' },
  { id: 'lighthouse-whale', idea: 'A lighthouse keeper adopts a lost whale' },
] as const

export function cannedIdea(id: string) {
  return CANNED_IDEAS.find(each => each.id === id) ?? null
}

const cacheRow = (ctx: QueryCtx, ideaId: string) =>
  ctx.db.query('cannedStrips').withIndex('by_ideaId', q => q.eq('ideaId', ideaId)).unique()

export async function cannedPanels(ctx: QueryCtx, ideaId: string) {
  const row = await cacheRow(ctx, ideaId)
  return row?.ready ? row.panels : null
}

export const status = query({
  args: {},
  handler: async (ctx) => {
    const demo = isDemo()
    const ideas = await Promise.all(CANNED_IDEAS.map(async ({ id, idea }) => ({
      id,
      idea,
      ready: (await cannedPanels(ctx, id)) !== null,
    })))
    return { demo, sharing: !demo, ownIdeaNeedsPasskey: demo, ideas, templateUrl: TEMPLATE_URL }
  },
})
```

Now write the strip functions. Each reads and writes only the caller's workspace:

```ts [backend/strips.ts]
import { backendError } from 'nuxt-backend/functions'
// …
import { v } from 'convex/values'
// …
import { cannedIdea, cannedPanels, isDemo } from './demo'
// …
import { workspace } from './functions'
// …
export const list = workspace.query({
  args: {},
  handler: async (ctx) => {
    const strips = await ctx.db
      .query('strips')
      .withIndex('by_workspace', q => q.eq('workspaceId', ctx.workspace.id))
      .order('desc')
      .take(50)
    return strips.filter(strip => !strip.hidden)
  },
})

export const get = workspace.query({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = await ctx.db.get('strips', id)
    if (strip?.workspaceId !== ctx.workspace.id || strip.hidden) return null
    // …
  },
})
// …
export const create = workspace.mutation({
  args: { idea: v.optional(v.string()), ideaId: v.optional(v.string()) },
  handler: async (ctx, { idea, ideaId }) => {
    if ((idea === undefined) === (ideaId === undefined)) throw backendError('invalid_input', { field: 'idea', reason: 'idea_or_ideaId' })
    let text: string
    if (ideaId !== undefined) {
      const canned = cannedIdea(ideaId)
      if (!canned) throw backendError('invalid_input', { field: 'ideaId', reason: 'unknown_idea' })
      text = canned.idea
    }
    else {
      if (isDemo() && ctx.user.signInMethod !== 'passkey') throw backendError('forbidden', { reason: 'passkey_required' })
      text = idea!.trim()
      if (text.length < 3 || text.length > 200) throw backendError('invalid_input', { field: 'idea', reason: 'idea_length' })
    }
    return ctx.db.insert('strips', {
      workspaceId: ctx.workspace.id,
      authorId: ctx.user.id,
      authorEmail: ctx.user.email,
      idea: text,
      ...(ideaId === undefined ? {} : { ideaId }),
      status: 'draft',
      panels: [],
    })
  },
})
```

- `get` ends with a line [Part 4](https://nuxt-backend.dev/docs/start/tutorial/generate) writes, once a strip has panels to show. Until then, end it with `return strip`.
- `create` takes either `{ idea }`, an idea of the author's own, or `{ ideaId }`, one of the canned ideas. A refusal names the field it is about: an idea under 3 or over 200 characters is `invalid_input` with `field: 'idea'` and the reason `idea_length`.
- On the public demo, the model calls are real and anyone may sign up, so an idea of one's own asks for a session signed in with a passkey: `forbidden`, reason `passkey_required`. A canned idea there is a free copy of panels drawn once. Everywhere else, the canned ideas are suggestions, drawn like any other idea.

Give the app a frame. `<AppShell>` renders the header, the workspace switcher, the notification bell, the account menu and every app-wide notice, and wraps the page in `<main>`. Your layout fills its slots:

```vue [app/layouts/default.vue]
<script setup lang="ts">
const pricing = useBackendPagePath('pricing')
// …
</script>

<template>
  <AppShell switcher>
    <template #brand>
      <NuxtLink :to="{ name: 'strips' }">
        Panels
      </NuxtLink>
    </template>
    <template #nav>
      <NuxtLink :to="{ name: 'strips' }">
        Strips
      </NuxtLink>
      <NuxtLink
        v-if="pricing"
        :to="pricing"
      >
        Credits
      </NuxtLink>
      <!-- … -->
    </template>
    <!-- … -->
    <slot />
  </AppShell>
</template>
```

`useBackendPagePath('pricing')` reads where the packaged pricing page is mounted, or `null` when the app turns it off.

Then the page that lists strips and starts a new one. `definePageMeta({ auth: true })` sends a visitor who is not signed in to the login page and back. The list waits for `useAuth().isReady`: on a page load the session is back a moment before the backend holds its token, and a signed-in read asked then is refused. The canned ideas are buttons above the form, and `useLabels('errors')` turns a refusal into a sentence in the reader's language:

```vue [app/pages/strips/index.vue]
<script setup lang="ts">
import { api } from '#backend/api'

definePageMeta({ auth: true })

const { isReady } = useAuth()
const strips = useQuery(api.strips.list, () => (isReady.value ? {} : 'skip'))
const demo = useQuery(api.demo.status, {})
// …
const create = useMutation(api.strips.create)
const { errorMessage } = useLabels('errors')
const idea = ref('')
const refusal = ref<string | null>(null)

async function start(args: { idea: string } | { ideaId: string }) {
  refusal.value = null
  try {
    const id = await create(args)
    idea.value = ''
    await navigateTo({ name: 'strips-id', params: { id } })
  }
  catch (error) {
    refusal.value = errorMessage(error)
  }
}
</script>

<template>
  <div class="page">
    <h1>Strips</h1>
    <section
      v-if="demo?.ideas.length"
      aria-labelledby="canned-heading"
    >
      <h2 id="canned-heading">
        Start from an idea
      </h2>
      <div class="row">
        <button
          v-for="canned in demo.ideas"
          :key="canned.id"
          type="button"
          :disabled="demo.demo && !canned.ready"
          @click="start({ ideaId: canned.id })"
        >
          {{ canned.idea }}{{ demo.demo && canned.ready ? ' (free)' : '' }}
        </button>
      </div>
    </section>
    <form
      class="row"
      @submit.prevent="start({ idea })"
    >
      <label for="idea">Idea for a new strip</label>
      <input
        id="idea"
        v-model="idea"
        placeholder="A cat learns to surf"
        required
        :aria-describedby="demo?.ownIdeaNeedsPasskey ? 'idea-passkey' : undefined"
      >
      <button
        type="submit"
        class="primary"
      >
        Start a strip
      </button>
      <p
        v-if="demo?.ownIdeaNeedsPasskey"
        id="idea-passkey"
        class="muted"
      >
        On the public demo, an idea of your own needs a passkey sign-in.
      </p>
      <p
        v-if="refusal"
        role="alert"
      >
        {{ refusal }}
      </p>
    </form>
    <!-- … -->
    <ul>
      <li
        v-for="strip in strips"
        :key="strip._id"
      >
        <NuxtLink :to="{ name: 'strips-id', params: { id: strip._id } }">
          {{ strip.idea }}
        </NuxtLink> · {{ strip.status }}
      </li>
    </ul>
  </div>
</template>
```

On the demo, a canned idea's button says it is free once its panels are drawn, and waits until then. The two gaps in this listing are an experiment the template runs: half of the people see example ideas under the form ([Roll out features](https://nuxt-backend.dev/docs/ship/operate/flags)). The `page`, `row`, `primary` and `muted` classes come from the template's `app/assets/main.css`.

Last, a page for one strip. Later parts add the photo, the drawing and the share link in its gap:

```vue [app/pages/strips/[id].vue]
<script setup lang="ts">
import { api } from '#backend/api'
import type { Id } from '#backend/dataModel'

definePageMeta({ auth: true })

const route = useRoute()
const id = computed(() => route.params.id as Id<'strips'>)
const { isReady } = useAuth()
const strip = useQuery(api.strips.get, () => (isReady.value ? { id: id.value } : 'skip'))
// …
</script>

<template>
  <div
    v-if="strip"
    class="page"
  >
    <h1>{{ strip.idea }}</h1>
    <!-- … -->
  </div>
  <div
    v-else-if="strip === null"
    class="page"
  >
    <p>This strip is not in your workspace.</p>
  </div>
</template>
```

**You should see** your idea at the top of [localhost:3000/strips](http://localhost:3000/strips) as soon as you press **Start a strip**, and its own page after it.

</steps>

## Check your work

- Open `/strips` in a private window. You land on `/login`, and after signing in you come back to `/strips`.
- Create a second workspace with the switcher in the header, and switch to it. The list is empty: strips belong to the workspace they were made in.
- Open `/strips` in two tabs and start a strip in one. The other tab shows it at once, since every query is live.
- Start a strip from a two-letter idea. The form says why it was refused.

## What you used

- `nuxt-backend dev --anonymous`, the local deployment with no account ([Run the dev loop](https://nuxt-backend.dev/docs/develop/dev-loop)).
- `<AuthForm>` and `useLoginFlow`, sign-in by code and passkey ([Sign users in](https://nuxt-backend.dev/docs/build/auth/sign-in)).
- `createFunctions` and its `workspace` tier ([Protect backend functions](https://nuxt-backend.dev/docs/build/auth/access/functions), [Scope tables to a workspace](https://nuxt-backend.dev/docs/build/data/read-write/workspace-scoped)).
- `backendError` and `useLabels('errors')` ([Handle errors](https://nuxt-backend.dev/docs/build/data/read-write/errors)).
- `definePageMeta({ auth: true })` ([Protect pages and routes](https://nuxt-backend.dev/docs/build/auth/access/pages)) and `useBackendPagePath` ([Packaged pages](https://nuxt-backend.dev/docs/build/ui/pages)).
- `<AppShell>` ([Build the app shell](https://nuxt-backend.dev/docs/build/ui/app-shell)).

## Next

[Part 2: sell credits](https://nuxt-backend.dev/docs/start/tutorial/credits) declares the credits a strip costs, and sells them on Polar's sandbox.


## Sitemap

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