Front-End Web & Mobile
From Build to Embed: Creating and Embedding GenAI Apps with AWS Amplify, CDK, and Amazon Q Business
In a enterprise landscape, custom applications play a critical role in improving operations, enhancing productivity, and centralizing knowledge within the organization. However, these tools often lack intelligent, conversational interfaces that help users access relevant information faster and more intuitively. Traditional dashboards and search bars fall short when it comes to interpreting complex queries or surfacing contextual insights from vast organizational data.
Generative AI offers a powerful solution to this challenge. By embedding conversational experiences directly into developer-controlled applications, organizations can enable users to ask questions in natural language and receive precise, actionable responses. Amazon Q Business delivers this capability via a secure, embeddable HTML inline frame (iframe)—without the burden of managing large language model infrastructure.
This blog is aimed at developers building custom or enterprise-owned applications—whether knowledge portals, support dashboards, or internal web tools. It shows how to embed a generative AI-powered conversational experience using Amazon Q Business, AWS Amplify Gen 2, and the AWS Cloud Development Kit (CDK). Embedding Amazon Q Business into applications requires access to the application’s source code and is not supported in third-party SaaS platforms where embedding custom code is not possible.
The presented approach enables:
- Conversational access to internal documents and knowledge bases.
- Secure integration with enterprise identity management systems.
- Scalable, AI-driven search without complex backend implementations.
- Rapid deployment using AWS Amplify’s capabilities for frontend and backend development.
With Amazon Q Business and AWS Amplify, you can quickly add generative AI to your apps—to boost productivity, reduce manual effort, and accelerate decision-making.
Figure 1 Submitting a prompt to Amazon Q Business iframe.
To embed a generative AI assistant into your internal application, you’ll leverage the following AWS services:
- AWS Amplify: A comprehensive set of tools and services that help developers build, deploy, and manage secure full-stack applications. It simplifies frontend and backend development by integrating tightly with services like Amazon Cognito for authentication, Amazon S3 for storage, and the CDK for building additional AWS infrastructure.
- Amazon Cognito: A managed service for adding authentication and authorization to your app. Cognito supports user sign-up, sign-in, and access control, and can be federated through an external identity provider (IdP) for enterprise access management.
- AWS IAM Identity Center: IAM Identity Center allows secure, centralized access management for your internal users. It supports identity federation with enterprise providers like Okta, Microsoft Entra ID, Ping Identity, and others. This enables your organization to enforce unified authentication policies and ensure only authorized users can interact with the embedded AI assistant.
- Amazon Q Business: A managed generative AI service that can be embedded via iframe into internal applications. Q Business connects to enterprise data sources, such as Amazon S3, and enables natural language querying through an intelligent assistant interface. It supports secure access and integrates with IAM Identity Center for federated enterprise use.
- Amazon Simple Storage Service (S3): A durable and scalable object storage service used to store internal documents, PDFs, manuals, or any unstructured content. These files act as the knowledge base that powers the Amazon Q Business assistant, enabling contextual responses to employee queries.
Figure 2 From Build to Embed Architecture Diagram
Prerequisites
- An AWS account: Note that AWS Amplify is part of the AWS Free Tier.
- Install: npm (v9 or later), and git (v2.14.1 or later).
- A Text Editor: For this guide we will use VSCode, but you can use your preferred IDE.
- Sample Dataset: Upload any PDF or explore sample data sets available on Kaggle.
- IAM Identity Center: You must enable an IAM Identity Center instance and add a user to your Identity Center directory.
Cloning the Repo
Step 1: Navigate to the repository on AWS Samples and fork it to your GitHub repositories.
Step 2: Clone the app by running the command below in your terminal.
git clone https://github.com/<YOUR_GITHUB_USERNAME>/sample-build-and-embed-genai-apps.git
Step 3: Access the newly cloned repository in VSCode by executing the commands below in your terminal.
cd sample-build-and-embed-genai-apps
code . -r
VSCode will open the repository folder, including the Amplify folder, which contains the app code that you’ll review in the next section.
Figure 3 Opening code in VSCode.
Step 4: Install the required packages, including the Amplify Gen 2 packages, by running the following command:
npm install
The Amplify Backend
In the final app (as seen in the gif at the beginning of the post), users log into the application, click the chatbot icon, authenticate with federated access (via the iframe to access Q Business web experience), and finally are able to begin asking questions to Amazon Q Business. The code for this is in the repository you cloned. Here, you’ll go over the key steps for creating your Amplify-developed and hosted search engine app.

Figure 4 Amplify Gen 2 Project Folder Structure.
In the amplify/auth/resource.ts
file (Figure 5), authentication is configured to require users to log in with their email to access the application and upload files. By enabling email-based login, you ensure only verified users can interact with sensitive data and functionalities.
import { defineAuth } from '@aws-amplify/backend';
export const auth = defineAuth({
loginWith: {
email: true,
},
});
Figure 5 defineAuth in amplify/auth/resource.ts
In the amplify/storage/resource.ts
file (Figure 6), Amplify storage is configured to enable secure, user-scoped file management. The defineStorage
function instantiates the storage resource with a user-friendly name q-datasource-bucket
and applies access control to the protected/{entity_id}/*
path. This configuration allows authenticated users to read files within their own scoped directory, while granting the file owner permissions to read, write, and delete their content.
import { defineStorage } from "@aws-amplify/backend";
export const storage = defineStorage({
name: "q-datasource-bucket",
access: (allow) => ({
'protected/{entity_id}/*': [
allow.authenticated.to(['read']),
allow.entity('identity').to(['read', 'write', 'delete'])
]
})
});
Figure 6 defineStorage in amplify/storage/resource.ts
In the amplify/backend.ts
(Figure 7) file, you import the CDK libraries to configure key aspects of your application. The aws-iam
module is used to manage permissions, aws-kms
handles encryption and key management, and aws-qbusiness
integrates Amazon Q Business into your stack. Each library plays a specific role in ensuring your application is secure and properly integrated with AWS services.
import * as iam from 'aws-cdk-lib/aws-iam';
import * as kms from 'aws-cdk-lib/aws-kms';
import * as q from 'aws-cdk-lib/aws-qbusiness';
Figure 7 import CDK libraries in amplify/backend.ts
Next, use the backend.createStack()
(Figure 8) method to direct the backend to generate a new CloudFormation Stack to house custom resources. With AWS Amplify Gen 2, you can create custom resources using the CDK, enabling the use of services beyond the Amplify library, with stacks backed by CloudFormation templates for scalability. For example, you could create a Generative AI stack for AI-related services, ensuring logical organization before adding custom AWS resources. Now, you can begin defining custom AWS resources!
export const customResource = backend.createStack("CustomResourceStack");
Figure 8 define backend stack for custom resources in amplify/backend.ts
During the CustomResourceStack
deployment, you’ll see several IAM roles, trust policies, and inline access policies being created—all of which are critical for enabling Amazon Q Business to function securely and interact with other AWS services. These include:
- Service Access Role (QApplicationServiceAccessRole) for Amazon Q Business to emit logs and metrics via CloudWatch.
- Web Experience Roles (QWebExperienceRole and QWebExperienceRole) for enabling the embedded assistant to function with full application context and user interactions.
- Data Source Role (QBusinessS3Role) specifically for allowing Amazon Q Business to read documents from the S3 bucket provisioned by Amplify Storage.
Each role includes a trust policy defining who can assume the role, and a series of fine-grained permissions granting access to specific actions and resources. You can view the full required policy structure for Amazon Q Business data sources in the IAM roles documentation for Amazon Q Business connectors.
Setting Up Amazon Q Business
With all foundational IAM roles and policies in place, you’re ready to define the Amazon Q Business application, the core component that powers the embedded generative AI assistant. In your amplify/backend.ts
(Figure 9) file, using the CDK, you can instantiate it declaratively with the necessary configuration, subscription plan, and IAM integration:
export const qapp = new q.CfnApplication(customResource, "Qapp", {
displayName: "Qapp",
description: "CDK instantiated Amazon Q Business App",
autoSubscriptionConfiguration: {
autoSubscribe: "ENABLED",
defaultSubscriptionType: "Q_LITE"
},
identityType: "AWS_IAM_IDC",
roleArn: `arn:aws:iam::${customResource.account}:role/aws-service-role/qbusiness.amazonaws.com/AWSServiceRoleForQBusiness`,
/* REPLACE WITH YOUR IAM IDENTITY CENTER ARN */
// identityCenterInstanceArn: "arn:aws:sso:::instance/",
});
Figure 9 defining Q Business Application in amplify/backend.ts
This step formally creates the Q Business application and associates it with the service-linked role (AWSServiceRoleForQBusiness). Be sure to substitute your IAM Identity Center ARN before deployment to enable federated access for users.
Creating an Index
Indexes in Amazon Q Business are used to store, organize, and retrieve enterprise data efficiently. You need an index to enable structured querying of stored documents, allowing the chatbot to retrieve relevant responses based on user queries. The following CDK code in your amplify/backend.ts
(Figure 10) sets up an index within your Amazon Q Business application:
export const qIndex = new q.CfnIndex(customResource, "QIndex", {
displayName: "QIndex",
description: "CDK instantiated Amazon Q Business App index",
applicationId: qapp.attrApplicationId,
capacityConfiguration: {
units: 1,
},
type: "STARTER",
});
Figure 10 defining Q Business Index in amplify/backend.ts
Here, the STARTER index type is selected, which is a basic configuration suitable for testing and small-scale deployments. For production use, a higher tier like ENTERPRISE would be necessary to ensure scalability, availability, and support for advanced features—see the Amazon Q Business pricing and tiers for guidance.
Creating a Retriever
Retrievers enhance the search capabilities by fetching relevant documents from the index. In Amazon Q Business, a retriever connects to the index and ensures that queries return meaningful responses. The following CDK code in your amplify/backend.ts
(Figure 11) sets up a retriever within your Amazon Q Business application:
export const qRetriever = new q.CfnRetriever(customResource, "QRetriever", {
displayName: "QRetriever",
applicationId: qapp.attrApplicationId,
type: "NATIVE_INDEX",
configuration: {
nativeIndexConfiguration: {
indexId: qIndex.attrIndexId,
},
}
});
Figure 11 defining Q Business Retriever in amplify/backend.ts
This retriever is configured to work with the previously created qIndex
, ensuring efficient retrieval of indexed content for Amazon Q Business.
Defining a Data Source
A data source is where the Amazon Q Business application retrieves data for its knowledge base. In this case, the data source is an Amazon S3 bucket defined earlier in the Amplify Storage configuration amplify/storage/resource.ts
and referenced in the amplify/backend.ts
(Figure 12) file. This bucket stores documents that Amazon Q Business will index and analyze.
export const qDataSource = new q.CfnDataSource(customResource, "QDataSource", {
displayName: `${backend.storage.resources.bucket.bucketName}`,
applicationId: qapp.attrApplicationId,
indexId: qIndex.attrIndexId,
configuration: {
type: "S3",
syncMode: "FULL_CRAWL",
connectionConfiguration: {
repositoryEndpointMetadata: {
BucketName: backend.storage.resources.bucket.bucketName
}
},
repositoryConfigurations: {
document: {
fieldMappings: [
{
indexFieldName: "s3_document_id",
indexFieldType: "STRING",
dataSourceFieldName: "s3_document_id"
}
]
}
},
},
roleArn: qBusinessS3Role.roleArn
});
Figure 12 defining Q Business Data Source in amplify/backend.ts
The key elements in this setup:
- syncMode: “FULL_CRAWL” ensures that all documents in the S3 bucket are indexed.
- Field mappings define how document metadata is structured for indexing.
Creating the Amazon Q Business Web Experience
The Web Experience in amazon Q business is a frontend that allows users to interact with Amazon Q Business embedded in a customized chatbot. This component is defined in your amplify/backend.ts
(Figure 13) file and defines how the chatbot interface appears and functions, including allowed website origins, branding, and authentication.
export const qWebExperience = new q.CfnWebExperience(customResource, "QWebExperience", {
applicationId: qapp.attrApplicationId,
origins: [
/* REPLACE WITH YOUR AMPLIFY DOMAIN URL */
"https://main..amplifyapp.com",
],
samplePromptsControlMode: "ENABLED",
subtitle: "AnyCompany Generative AI Assistant",
title: "AnyCompany Q App",
welcomeMessage: "Welcome to your Amazon Q Business Application!",
roleArn: qWebExperienceRole.roleArn
});
Figure 13 defining Q Business Web Experience in amplify/backend.ts
Web Experience Configuration
- Origins: Specifies the website domains permitted to embed the chatbot via an <iframe>. Ensure that your Amplify app’s deployed URL is correctly listed here.
- samplePromptsControlMode: Enables storing predefined sample prompts within the chatbot UI.
- title & subtitle: Sets the chatbot’s display name and additional descriptions.
- welcomeMessage: The first message users see when they open the chat window.
Amazon Q Business and Frontend Integration
After configuring the web experience, you can now embed your Amazon Q Business web experience using an iframe. In src/components/qframe.tsx
(Figure 14), the src is dynamically populated from the amplify_outputs.json
file, which contains the deployed URL of your Q Web Experience exported by the backend. Users are prompted to authenticate in a new browser tab, after which the chat session continues within the embedded iframe.
import React from 'react';
import rawOutputs from '../../amplify_outputs.json';
const outputs = rawOutputs as unknown as {
custom: {
q_business_url: string;
};
};
const QFrame: React.FC = () => {
const qBusinessDeployedURL = outputs.custom.q_business_url;
return (
<iframe
src={qBusinessDeployedURL}
title="Chatbot"
className="QFrame"
/>
);
};
export default QFrame;
Figure 14 Embeds Amazon Q Business via iframe using config URL.
Running the App
Step 1: Amplify provides each developer with a personal cloud sandbox environment, offering isolated development spaces for rapid building, testing, and iteration. To initiate a cloud sandbox environment, open a new terminal window and execute the following command:
npx ampx sandbox
Step 2: Execute the following command to start a localhost development server.
npm run dev
After running the previous command to start the application, use the ‘Create Account‘ feature of the Amplify Authenticator component, and provide an email address and password. After finalizing user setup via a confirmation email, log in to gain access to the application. (Figure 15)
Figure 15 Logging in using the Amplify Authenticator component during local development testing.
After interacting with the app on the development server, stop the sandbox environment by pressing Ctrl + C in the terminal. Then enter “npx ampx sandbox delete” and confirm by entering ‘Y‘ when prompted to delete resources in the sandbox environment. (Figure 16)
Figure 16 Deleting all resources in the Amplify sandbox environment
Deploying backend resources
With the app functioning as expected, deploy your backend resources by following the steps in “Getting Started with Deploying an App to Amplify Hosting“. Ensure that GitHub is selected as the repository for deployment.
Update Amplify Domain Endpoint
In your backend CDK code, navigate to amplify/backend.ts
and replace the placeholder in the origins field with your actual Amplify domain. You can find this domain in the Amplify console under the app name you created in the previous section. (Figure 17)
origins: [
"https://main.<AMPLIFY_APP_ID>.amplifyapp.com",
],
Figure 17 Updating the origins field in the CDK backend code with your Amplify app’s deployed domain.
Upload Sample Data
After deploying and signing into the application, upload sample data by accessing the app domain URL generated by Amplify. After uploading files, confirm the upload by checking the public/ folder within the Storage section of the AWS Amplify console. (Figure 18)
Figure 18 Uploading sample data in deployed app.
Configure User Access to Q Business Web Experience
Next, for your Qapp, you need to assign a user who can log in to the embedded web experience. This user should have been created during the prerequisites using IAM Identity Center. To add a new or existing user, in the Amazon Q Business console, select your Qapp, then navigate to the User access section and click Manage user access, followed by Add groups and users. (Figure 19)
Figure 19 Assigning user access via IAM Identity Center.
If the user already exists, choose Assign existing users and groups and search for the user you want to assign. Once added, confirm your selection to grant access to the Amazon Q Business web experience. (Figure 20)
Figure 20 Granting access to existing IAM Identity Center users.
Sync S3 Data to Q Business Index
After uploading your sample document, sync the Amazon S3 bucket with the Amazon Q Business index to store and retrieve your data. From the Amazon Q Business console, navigate to Data Sources, select amplify-your-unique-bucket-name. Then, select Sync now (Figure 21).
Figure 21 Syncing uploaded S3 data to Q Business index.
Once the data source sync completes and the last sync status shows “completed“, you’re almost ready to begin using your Amazon Q Business web experience. Before proceeding, make sure to sign in. After a successful sign-in, you’ll see a “Sign in Complete” message. At that point, you can return to your application—authentication is now complete. (Figure 22)
Figure 22 Confirming sign-in completion for authentication.
Now that you are signed in, start querying your Amazon Q Business web experience directly through your application! (Figure 23)
Figure 23 Querying Amazon Q Business in your application.
Cleaning Up
To remove the AWS Identity Center console instance, go to “Settings“, and open the “Management” tab. Under the “Delete IAM Identity Center instance” section, select “Delete” to remove it.
Lastly, within the AWS Amplify console, select “View app” for the application you created following this blog. Then, select “App Settings” followed by “General Settings.” Finally, select “Delete app” to remove the application and associated backend resources. Note, Amplify will delete all backend resources created as a part of your project.
Conclusion
In this blog, we explained the key steps for integrating Amazon Q Business into a custom application: setting up the frontend with AWS Amplify, configuring the Q Business application using the CDK, and embedding the chatbot via an iframe. By leveraging these AWS Services and tools, you can create an AI-powered search experience that improves user interaction and knowledge accessibility.
Now it’s your turn! Embed conversational AI into your applications and unlock new levels of productivity and decision-making with Amazon Q Business. Then, supercharge your development workflow with Amazon Q Developer. Harness the power of generative AI and cloud computing to accelerate your development and quickly build modern applications that drive innovation.