

# Tutorial: Create a full-stack app

In this tutorial, you build a notes app with Next.js and an AWS Amplify backend. Users sign up, and each user adds and reads their own notes. You run the app on your computer, and then deploy it to AWS.

## Prerequisites
<a name="_prerequisites"></a>

You need the following:
+ AWS credentials for your AWS account, and permissions for Amplify. To check your credentials, run `aws sts get-caller-identity`. If the command fails, sign in with `aws sso login` or `aws configure`. For the permissions, see [Give your account permissions](security_iam_id-based-policy-examples.md#setup-permissions).
+ The latest version of the AWS Command Line Interface (AWS CLI) v2, which includes the `aws amplifygen3` subcommand. To check, run `aws amplifygen3 help`. If the command isn’t found, install or update the AWS CLI by following [Installing or updating to the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) in the *AWS CLI User Guide*.
+ Node.js 22.12 or later, and npm 10 or later. To check, run `node --version` and `npm --version`.
+ Docker or Finch, running, to run the backend on your computer. To check Docker, run `docker info`. For more information, see [Docker and Finch](backend-local-runtimes.md).

## Step 1: Set up your app
<a name="_step_1_set_up_your_app"></a>

Create a Next.js app, and then initialize Amplify with a backend in it:

```bash
npx create-next-app@latest notes-app --ts --app --eslint --no-tailwind --no-src-dir --import-alias "@/*" --use-npm --yes
cd notes-app
aws amplifygen3 local init --type fullstack
```

The `local init` command only creates files on your machine. Amplify doesn’t create anything in AWS until you deploy. The command writes `amplify.jsonc`, creates the `migrations/` folder, and installs the Amplify backend client packages. It names the app after the folder. To choose another name, add `--app` followed by the name.

You should see a new `amplify.jsonc` file in your app folder. The file’s `deploy` section tells Amplify how to build your app, and its `backend` section turns on the backend. For more information, see [Configuration file](build-settings-configuration.md).

Email and password sign-in is on by default, so you don’t need to configure auth for this tutorial. To change it, see [Email and password](backend-auth-password.md).

**Note**  
This tutorial uses the `aws amplifygen3` commands. The `npm create amplify` and `npx ampx sandbox` commands are for Amplify Gen 2, not for AWS Amplify.

## Step 2: Create the notes table
<a name="_step_2_create_the_notes_table"></a>

In this step, you create the table that stores the notes.

1. Run the following command to create a migration file:

   ```bash
   aws amplifygen3 local migration create --description "create notes"
   ```

1. Open the new file in `migrations/`, and replace its contents with the following SQL. The SQL creates the table, grants signed-in users access to it, and adds row-level security (RLS) policies. The grant lets signed-in users read and write the table. The policies limit each user to their own notes.

   ```sql
   create table public.notes (
     id         bigint generated always as identity primary key,
     owner_id   text not null default auth.uid(),
     body       text not null,
     created_at timestamptz not null default now()
   );
   create index notes_owner_id_idx on public.notes (owner_id);
   
   alter table public.notes enable row level security;
   create policy "own_select" on public.notes for select to authenticated using ((select auth.uid()) = owner_id);
   create policy "own_insert" on public.notes for insert to authenticated with check ((select auth.uid()) = owner_id);
   create policy "own_update" on public.notes for update to authenticated
     using ((select auth.uid()) = owner_id) with check ((select auth.uid()) = owner_id);
   create policy "own_delete" on public.notes for delete to authenticated using ((select auth.uid()) = owner_id);
   
   grant select, insert, update, delete on public.notes to authenticated;
   ```

## Step 3: Connect the app to the backend
<a name="_step_3_connect_the_app_to_the_backend"></a>

In this step, you create a backend client from the backend URL and the publishable key.

1. Replace the contents of `next.config.ts` with the following code:

   ```ts
   import type { NextConfig } from "next";
   
   const nextConfig: NextConfig = {
     env: {
       AMPLIFY_BACKEND_URL: process.env.AMPLIFY_BACKEND_URL,
       AMPLIFY_BACKEND_PUBLISHABLE_KEY: process.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY,
     },
   };
   
   export default nextConfig;
   ```

   Amplify sets `AMPLIFY_BACKEND_URL` and `AMPLIFY_BACKEND_PUBLISHABLE_KEY`. The `aws amplifygen3 local run` command sets them for the local backend, and each deployment sets them for its environment’s backend branch. The `env` setting makes them available in browser code. Both values are safe to use in browser code. Keep private keys, such as a key that bypasses RLS, out of browser code.

1. Create the file `lib/backend.ts` with the following code:

   ```ts
   import { createClient } from '@aws-amplifygen3/backend-client-js'
   
   let client: ReturnType<typeof createClient> | undefined
   
   export function backend() {
     client ??= createClient(process.env.AMPLIFY_BACKEND_URL!, process.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY!)
     return client
   }
   ```

## Step 4: Build the page
<a name="_step_4_build_the_page"></a>

In this step, you write a page where users sign up, sign in, add notes, and sign out.

Replace the contents of `app/page.tsx` with the following code. Keep the `'use client'` line at the top, so that the client SDK runs in the browser.

```tsx
'use client'

import { useEffect, useState } from 'react'
import { backend } from '@/lib/backend'

type Note = { id: number; body: string }

export default function Home() {
  const [email, setEmail] = useState<string | null>(null)
  const [notes, setNotes] = useState<Note[]>([])
  const [message, setMessage] = useState('')

  async function loadNotes() {
    const { data } = await backend().from('notes').select('id, body').order('id')
    setNotes(data ?? [])
  }

  useEffect(() => {
    backend().auth.getSession().then(({ data }) => {
      setEmail(data.session?.user.email ?? null)
      if (data.session) loadNotes()
    })
  }, [])

  async function signUp(form: FormData) {
    const { error } = await backend().auth.signUp.email({
      email: String(form.get('email')),
      password: String(form.get('password')),
    })
    if (error) return setMessage(error.code ?? 'Sign-up failed')
    location.reload()
  }

  async function signIn(form: FormData) {
    const { error } = await backend().auth.signIn.email({
      email: String(form.get('email')),
      password: String(form.get('password')),
    })
    if (error) return setMessage(error.code ?? 'Sign-in failed')
    location.reload()
  }

  async function addNote(form: FormData) {
    await backend().from('notes').insert({ body: String(form.get('body')) })
    loadNotes()
  }

  async function signOut() {
    await backend().auth.signOut()
    location.reload()
  }

  if (!email) {
    return (
      <form action={signUp}>
        <h1>Notes</h1>
        <input name="email" type="email" placeholder="Email" required />
        <input name="password" type="password" placeholder="Password" required minLength={8} />
        <button>Sign up</button>
        <button formAction={signIn}>Sign in</button>
        <p>{message}</p>
      </form>
    )
  }

  return (
    <main>
      <h1>Notes for {email}</h1>
      <form action={addNote}>
        <input name="body" placeholder="New note" required />
        <button>Add</button>
      </form>
      <ul>{notes.map((note) => <li key={note.id}>{note.body}</li>)}</ul>
      <button onClick={signOut}>Sign out</button>
    </main>
  )
}
```

## Step 5: Run the app on your computer
<a name="_step_5_run_the_app_on_your_computer"></a>

In this step, you run the app and its backend on your computer.

1. Run the following command:

   ```bash
   aws amplifygen3 local run
   ```

   The command starts the local backend, applies your migration, and starts the dev server. You should see `Local: http://localhost:3000`.

1. Open `http://localhost:3000`, sign up with an email address and a password, and add a note.

For more information, see [Develop locally](backend-local.md).

## Step 6: Deploy to preview
<a name="_step_6_deploy_to_preview"></a>

Run the following command:

```bash
aws amplifygen3 deploy
```

The first deploy creates the app and its backend in your AWS account. The build runs in the cloud, from the `deploy` section of `amplify.jsonc`, and Amplify applies your migration to the `preview` environment’s backend branch. Amplify doesn’t upload your local `node_modules` folder. When the deploy finishes, you should see a `Visit:` line with your preview URL, such as `https://preview-xxxx--notes-app.amplify.app`, where `xxxx` is the preview ID that Amplify assigns. Open the URL, and sign up again. This backend branch has its own database and users, so your local users and notes stay on your computer.

## Step 7: Deploy to production
<a name="_step_7_deploy_to_production"></a>

To deploy your app to production, run the following command. If you want to check your changes first, open your preview URL. The deploy also applies your migration to the production database.

```bash
aws amplifygen3 deploy --env production
```

You should see a `Visit:` line with your production URL, `https://notes-app.amplify.app`. After you change your code, run `aws amplifygen3 deploy` again. The `deploy` command uses `preview` unless you add `--env production`.

## Clean up
<a name="_clean_up"></a>

To stop the local backend, run `aws amplifygen3 local stop`. Your local data stays on your computer.

Your app, its environments, and its backend stay in your AWS account until you delete them.

**Deleting the app is permanent**  
The following command deletes the app, all of its environments, and its backend. That includes the database, the automated backups, and the users of every branch, including `production`. You can’t undo this action.

Run the following command. Replace `notes-app` with the name of your app.

```bash
aws amplifygen3 app delete --app notes-app --yes
```

## Next steps
<a name="_next_steps"></a>

To keep building the app, see the following pages:
+  [Tables and migrations](backend-data.md) – Change your tables.
+  [Secure your data](backend-rls.md) – Write RLS policies.
+  [Read data](backend-data-api-query.md) – Filter, sort and page through your rows.
+  [Email and password](backend-auth-password.md) – Add sign-in, verification and password reset.