Initialize AWS Amplify
Now we'll add AWS Amplify Gen 2 to our Nuxt application. This involves creating the backend configuration files and connecting them to our frontend.
Step 1: Create the Amplify Backend Structure
In Amplify Gen 2, you define your backend in an amplify/ folder
using TypeScript. Let's create this structure.
First, install the Amplify backend package:
npm install @aws-amplify/backend @aws-amplify/backend-cli
Create the amplify directory structure:
mkdir amplify; mkdir amplify\auth; mkdir amplify\data
Step 2: Create the Auth Resource
Create amplify/auth/resource.ts:
// amplify/auth/resource.ts
import { defineAuth } from '@aws-amplify/backend';
/**
* Define and configure your auth resource
* This creates an Amazon Cognito User Pool for authentication
*/
export const auth = defineAuth({
loginWith: {
email: true, // Users sign in with email
},
// Optional: Add additional user attributes
userAttributes: {
preferredUsername: {
required: false,
mutable: true,
},
},
});
This configuration tells Amplify to create a Cognito User Pool where users can sign up and sign in using their email address. Cognito will handle email verification, password requirements, and token management.
Step 3: Create the Data Resource
Create amplify/data/resource.ts:
// amplify/data/resource.ts
import { type ClientSchema, a, defineData } from '@aws-amplify/backend';
/**
* Define your data schema
* Each model becomes a DynamoDB table with GraphQL API
*/
const schema = a.schema({
Todo: a
.model({
content: a.string().required(),
completed: a.boolean().default(false),
priority: a.enum(['low', 'medium', 'high']),
})
// Only the owner (creator) can access their todos
.authorization((allow) => [allow.owner()]),
});
// Export the schema type for TypeScript support
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({
schema,
authorizationModes: {
defaultAuthorizationMode: 'userPool',
},
});
Understanding the Data Schema
| Code | What it does |
|---|---|
a.model({...}) |
Defines a data model (becomes a DynamoDB table) |
a.string().required() |
A required string field |
a.boolean().default(false) |
A boolean field with default value |
a.enum([...]) |
An enumerated type (one of the listed values) |
.authorization(allow => [...]) |
Defines who can access this data |
allow.owner() |
Only the user who created the record can access it |
Step 4: Create the Backend Definition
Create amplify/backend.ts to tie everything together:
// amplify/backend.ts
import { defineBackend } from '@aws-amplify/backend';
import { auth } from './auth/resource';
import { data } from './data/resource';
/**
* Main backend definition
* Combines all resources (auth, data, functions, etc.)
*/
defineBackend({
auth,
data,
});
Step 5: Configure Amplify in Nuxt
Create a plugin to configure Amplify on the client side. Create plugins/amplify.client.ts:
// plugins/amplify.client.ts
import { Amplify } from 'aws-amplify';
import outputs from '../amplify_outputs.json';
export default defineNuxtPlugin(() => {
// Configure Amplify with the generated outputs
Amplify.configure(outputs);
});
The amplify_outputs.json file will be generated when we run the
sandbox. The plugin won't work until then, which is expected.
Step 6: Update TypeScript Configuration
Update nuxt.config.ts to handle the Amplify imports:
// nuxt.config.ts
export default defineNuxtConfig({
compatibilityDate: '2024-11-01',
devtools: { enabled: true },
modules: ['@nuxtjs/tailwindcss'],
typescript: {
strict: true,
},
// Handle Amplify imports
vite: {
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser',
},
},
define: {
'window.global': {},
},
},
});
Step 7: Start the Sandbox
Now let's deploy your backend to a sandbox environment. This creates real AWS resources for development.
npx ampx sandbox
The first run will:
- Bootstrap CDK in your AWS account (if not already done)
- Build your backend definition
- Deploy CloudFormation stacks for auth and data
- Generate
amplify_outputs.jsonwith configuration
The initial sandbox creation takes longer because it's creating all the AWS resources. Subsequent changes are much faster (30 seconds to 2 minutes).
When complete, you'll see output like:
✔ Deployed
amplify-amplifytonuxtapp-yourname-sandbox-abc123
amplify_outputs.json file successfully written to the project.
Watching for file changes...
Step 8: Verify the Generated File
Check that amplify_outputs.json was created. It should look something like:
{
"version": "1.3",
"auth": {
"user_pool_id": "us-east-1_xxxxxxxx",
"user_pool_client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
"aws_region": "us-east-1"
},
"data": {
"url": "https://xxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql",
"aws_region": "us-east-1",
"default_authorization_type": "AMAZON_COGNITO_USER_POOLS"
}
}
The amplify_outputs.json file contains your specific AWS configuration
and should not be committed to Git. Add it to your .gitignore:
# .gitignore additions
amplify_outputs.json
.amplify/
Step 9: Test the Frontend
Keep the sandbox running in one terminal. In a new terminal, start Nuxt:
npm run dev
Open http://localhost:3000. The page should load without errors. Check the browser console (F12) to verify there are no Amplify-related errors.
Understanding What Happened
When you ran npx ampx sandbox, Amplify:
- Read your
amplify/backend.tsand resource definitions - Generated AWS CDK code based on your configuration
- Created a CloudFormation stack in your AWS account
- Provisioned:
- A Cognito User Pool (for authentication)
- A DynamoDB table (for Todo data)
- An AppSync GraphQL API (for data operations)
- IAM roles and policies (for security)
- Generated
amplify_outputs.jsonfor your frontend
Cleaning Up (When Done for the Day)
When you're done developing, stop the sandbox with Ctrl+C. The resources
stay running until you explicitly delete them:
npx ampx sandbox delete
This removes all sandbox resources. You can recreate them anytime with
npx ampx sandbox.
Summary
✅ You Have:
- Created the
amplify/folder with auth and data resources - Defined a Todo model with owner-based authorization
- Started the sandbox and deployed to AWS
- Connected your Nuxt frontend to the Amplify backend