<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Josh Thorne on Medium]]></title>
        <description><![CDATA[Stories by Josh Thorne on Medium]]></description>
        <link>https://medium.com/@joshua_thorne?source=rss-9172c40b72f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mWB3uSYwDklMAlYA6fJ1PQ.png</url>
            <title>Stories by Josh Thorne on Medium</title>
            <link>https://medium.com/@joshua_thorne?source=rss-9172c40b72f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:59:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joshua_thorne/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Serverless Book Recommendation System with Amazon Bedrock]]></title>
            <link>https://towardsaws.com/creating-a-serverless-book-recommendation-system-with-amazon-bedrock-48e1e189fb34?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e1e189fb34</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Tue, 27 May 2025 05:10:06 GMT</pubDate>
            <atom:updated>2025-05-27T05:10:06.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Serverless Book Recommendation System with Bedrock</h3><h4>Using Step Functions, Lambda, and Amazon Bedrock with Claude and Titan Models</h4><h3>Introduction</h3><p>In this article, we’ll walk through how to build a serverless book recommendation engine using Amazon Bedrock.</p><p>It’s important to note that the solution in this article might not be the best fit for every use case so make sure to explore other options before using it in a production environment!</p><p>Also, if you want to jump to the solution, I have pushed all the code to GitHub <a href="https://github.com/thornejosh/serverless-recommendation-example">here</a>.</p><h3>What Are We Building Exactly?</h3><p>In this article, we’re going to build a book recommendation system using Amazon Bedrock, Step Functions, and OpenSearch.</p><p>The great thing about this architecture?</p><p>Unlike traditional recommendation systems, we don’t need a massive pre-existing dataset with detailed book attributes. With this architecture, we can easily build the knowledge base as part of the workflow.</p><p>Here’s a look at the proposed architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjwnaqOeFtxOzfLGX2WLdA.png" /></figure><p>If you’re not familiar with any of the above services, don’t worry! We’ll give a quick overview of each before diving in.</p><p>We have two different state machines here with similar steps.</p><h4>️Store Book State Machine</h4><p>This state machine is responsible for storing a book’s representation (known as an embedding) in an OpenSearch collection.</p><p>Here’s how it works:</p><ol><li>The user provides the name of a book.</li><li>The system calls Amazon Bedrock and uses Claude 3.5 Sonnet to generate a description of the book.</li><li>A second call is made to Bedrock, this time using Titan, to generate an embedding of that description.</li><li>The embedding is passed to a Lambda function, which stores it in our OpenSearch collection.</li></ol><h4>Find Similar Books State Machine</h4><p>This state machine reuses some steps from the store book state machine, but instead searches OpenSearch for books similar to the one the user provides:</p><ol><li>The user provides the name of a book.</li><li>The system calls Amazon Bedrock and uses Claude 3.5 Sonnet to generate a description of the book.</li><li>A second call is made to Bedrock, this time using Titan, to generate an embedding of that description.</li><li>Instead of storing the embedding, we query OpenSearch using the k-nearest neighbour (k-NN) algorithm to find similar embeddings (i.e. books that are most like the one provided).</li></ol><p>Within each state machine, we’re taking advantage of direct integrations with Bedrock which means we don’t need to call a Lambda function to interact with the models. This will save us money and time!</p><p>Sounds great, right?</p><h3>So What Do These Services Actually Do?</h3><p>If you’re not familiar with some of the tools we’re using, here’s a quick breakdown:</p><ul><li><strong>Step functions</strong> lets you stitch services together into a workflow. It handles the logic and flow, like calling Bedrock, waiting for results, and passing data around.</li><li><strong>Amazon Bedrock</strong> gives you access to powerful foundation models without managing any infrastructure. We use it to generate book descriptions and embeddings with just an API call.</li><li><strong>Claude </strong>is a language model great at understanding and generating text. We use Claude 3.5 Sonnet to create detailed book descriptions from just a title.</li><li><strong>Titan</strong> is Amazon’s model for generating embeddings. It turns the book description into a vector we can use to compare books based on meaning.</li><li><strong>OpenSearch</strong> is our vector database. It stores the embeddings and lets us search for similar ones using the <a href="https://www.geeksforgeeks.org/k-nearest-neighbours/">k-nearest neighbour algorithm</a>.</li></ul><h3>Building the System</h3><p>We’ll build the entire system using AWS CDK with TypeScript and deploy it to AWS. To get started, here’s what you’ll need.</p><h4>Prerequisites</h4><ul><li><a href="https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html">An AWS account</a> (of course)</li><li><a href="https://docs.aws.amazon.com/cdk/v2/guide/home.html">CDK installed</a></li><li>AWS credentials configured (<a href="https://www.leapp.cloud/">I use Leaap for this</a>)</li><li>You will need to <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html">request access to the models</a> we use in this article</li><li>A blank CDK typescript project. You can follow <a href="https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html">this documentation to get started</a></li></ul><h4>Configuring the OpenSearch Collection</h4><p>The first thing we need to do is set up our OpenSearch collection and define it as a vector search collection. This is essential for our use case because we’ll be storing and searching embeddings (also known as vectors).</p><p>Here’s the CDK construct that does the job:</p><pre>// book-recommendations-collection.ts<br>import { Construct } from &quot;constructs&quot;;<br>import { aws_opensearchserverless as opensearchserverless } from &quot;aws-cdk-lib&quot;;<br>import { CfnCollection } from &quot;aws-cdk-lib/aws-opensearchserverless&quot;;<br><br>export class BookRecommendationCollection extends CfnCollection {<br>  constructor(<br>    scope: Construct,<br>    id: string,<br>    props: { principalArns: string[] }<br>  ) {<br>    super(scope, id, {<br>      name: &quot;book-recommendation-collection&quot;,<br>      type: &quot;VECTORSEARCH&quot;,<br>    });<br><br>    const { principalArns } = props;<br><br>    const collectionName = this.name;<br><br>    const securityPolicy = new opensearchserverless.CfnSecurityPolicy(<br>      this,<br>      &quot;BookRecommendationSecurityPolicy&quot;,<br>      {<br>        name: &quot;security-policy&quot;,<br>        type: &quot;encryption&quot;,<br>        description: &quot;Security policy for book recommendation collection&quot;,<br>        policy: JSON.stringify({<br>          Rules: [<br>            {<br>              ResourceType: &quot;collection&quot;,<br>              Resource: [`collection/${collectionName}`],<br>            },<br>          ],<br>          AWSOwnedKey: true,<br>        }),<br>      }<br>    );<br><br>    const networkPolicy = new opensearchserverless.CfnSecurityPolicy(<br>      this,<br>      &quot;BookRecommendationNetworkPolicy&quot;,<br>      {<br>        name: &quot;network-policy&quot;,<br>        type: &quot;network&quot;,<br>        description: &quot;Network policy for book recommendation collection&quot;,<br>        policy: JSON.stringify([<br>          {<br>            Rules: [<br>              {<br>                ResourceType: &quot;collection&quot;,<br>                Resource: [`collection/${collectionName}`],<br>              },<br>              {<br>                ResourceType: &quot;dashboard&quot;,<br>                Resource: [`collection/${collectionName}`],<br>              },<br>            ],<br>            AllowFromPublic: true,<br>          },<br>        ]),<br>      }<br>    );<br><br>    const accessPolicy = new opensearchserverless.CfnAccessPolicy(<br>      this,<br>      &quot;BookRecommendationAccessPolicy&quot;,<br>      {<br>        name: &quot;access-policy&quot;,<br>        type: &quot;data&quot;,<br>        description: &quot;Access policy for book recommendation collection&quot;,<br>        policy: JSON.stringify([<br>          {<br>            Description: &quot;Access policy for book recommendation collection&quot;,<br>            Rules: [<br>              {<br>                ResourceType: &quot;index&quot;,<br>                Resource: [`index/${collectionName}/*`],<br>                Permission: [<br>                  &quot;aoss:UpdateIndex&quot;,<br>                  &quot;aoss:DescribeIndex&quot;,<br>                  &quot;aoss:ReadDocument&quot;,<br>                  &quot;aoss:WriteDocument&quot;,<br>                  &quot;aoss:CreateIndex&quot;,<br>                ],<br>              },<br>              {<br>                ResourceType: &quot;collection&quot;,<br>                Resource: [`collection/${collectionName}`],<br>                Permission: [<br>                  &quot;aoss:DescribeCollectionItems&quot;,<br>                  &quot;aoss:CreateCollectionItems&quot;,<br>                  &quot;aoss:UpdateCollectionItems&quot;,<br>                ],<br>              },<br>            ],<br>            Principal: principalArns,<br>          },<br>        ]),<br>      }<br>    );<br><br>    this.addDependency(securityPolicy);<br>    this.addDependency(accessPolicy);<br>    this.addDependency(networkPolicy);<br>  }<br>}</pre><p>We’re doing three main things here:</p><ol><li><strong>Creating a vector search collection</strong><br> This tells OpenSearch to store and search embeddings, which is core to how our recommendation system works.</li><li><strong>Adding security and network policies</strong><br> We configure encryption using an AWS-owned key, and we define network access. For simplicity, we’re allowing public access, but in a real application, you’d probably want this locked down.</li><li><strong>Defining an access policy</strong><br> This gives specific IAM principals permissions to interact with the collection and its indexes. It covers everything from reading and writing documents to managing collection metadata.</li></ol><p>We can now create an instance of the collection directly in our CDK stack, like this:</p><pre>const lambdaIamRole = new Role(this, &quot;BookRecommendationLambdaRole&quot;, {<br>  description: &quot;Book recommendation lambda role&quot;,<br>  assumedBy: new ServicePrincipal(&quot;lambda.amazonaws.com&quot;),<br>  managedPolicies: [<br>    ManagedPolicy.fromAwsManagedPolicyName(<br>      &quot;service-role/AWSLambdaBasicExecutionRole&quot;<br>    ),<br>  ],<br>});<br><br>const collection = new BookRecommendationCollection(<br>  this,<br>  &quot;BookRecommendationCollection&quot;,<br>  {<br>    principalArns: [<br>      lambdaIamRole.roleArn,<br>      new AccountPrincipal(Stack.of(this).account).arn,<br>    ],<br>  }<br>);</pre><p>Here, we’re creating a Lambda IAM role so our Lambda functions can access the OpenSearch collection. We pass that role’s ARN, along with the account’s ARN, to the collection so they’re granted the right permissions.</p><h4>Creating the Store Book State Machine</h4><p>Next we will write the Lambda function code that stores an embedding in OpenSearch. We’ll begin by setting up a helper function that creates a connection to our OpenSearch collection.</p><pre>// get-open-search-client.ts<br>import { AwsSigv4Signer } from &quot;@opensearch-project/opensearch/aws&quot;;<br>import { Client } from &quot;@opensearch-project/opensearch&quot;;<br>import { defaultProvider } from &quot;@aws-sdk/credential-provider-node&quot;;<br><br>export const getOpenSearchClient = (collectionEndpoint: string) =&gt; {<br>  // Get region from environment variable or default to us-east-1<br>  const region =<br>    process.env.REGION_NAME || process.env.AWS_REGION || &quot;us-east-1&quot;;<br><br>  console.log(<br>    `Creating OpenSearch client for endpoint: ${collectionEndpoint} in region: ${region}`<br>  );<br><br>  const client = new Client({<br>    ...AwsSigv4Signer({<br>      region: region,<br>      service: &quot;aoss&quot;, // Specify &#39;aoss&#39; for OpenSearch Serverless<br>      getCredentials: () =&gt; {<br>        const credentialsProvider = defaultProvider();<br>        return credentialsProvider();<br>      },<br>    }),<br>    node: collectionEndpoint,<br>  });<br><br>  return client;<br>};</pre><p>This helper sets up an OpenSearch client with AWS SigV4 signing, which is required for connecting securely to OpenSearch Serverless. It also pulls the region from environment variables, which you’ll want to set during deployment.</p><p>Don’t forget to install the dependencies used here:</p><ul><li><a href="http://twitter.com/opensearch">@opensearch</a>-project/opensearch</li><li><a href="http://twitter.com/aws">@aws</a>-sdk/credential-provider-node</li></ul><p>Now that we have our OpenSearch client helper, we can use it in a Lambda function to store a book’s embedding in OpenSearch.</p><pre>// store-embedding.ts<br>import { Indices_Create_RequestBody } from &quot;@opensearch-project/opensearch/api&quot;;<br>import { getOpenSearchClient } from &quot;./helpers/getOpenSearchClient&quot;;<br><br>export const handler = async (event: any) =&gt; {<br>  const indexName = process.env.OPENSEARCH_INDEX_NAME || &quot;book-recommendations&quot;;<br><br>  // Get the collection endpoint from environment or from the collection itself<br>  const collectionEndpoint = process.env.OPENSEARCH_COLLECTION_ENDPOINT;<br><br>  if (!collectionEndpoint) {<br>    throw new Error(&quot;Collection endpoint is not defined.&quot;);<br>  }<br><br>  // Create OpenSearch client<br>  const client = getOpenSearchClient(collectionEndpoint);<br><br>  const embedding = event.embedding;<br>  const bookName = event.bookName;<br><br>  if (!embedding || !bookName) {<br>    throw new Error(&quot;Missing required parameters: embedding or bookName&quot;);<br>  }<br><br>  try {<br>    // Check if index exists, if not create it with proper mapping for vector search<br>    const indexExists = await client.indices.exists({ index: indexName });<br><br>    if (!indexExists.body) {<br>      // Create index with mapping for vector field<br>      const settings: Indices_Create_RequestBody = {<br>        settings: {<br>          index: {<br>            knn: true,<br>          },<br>        },<br>        mappings: {<br>          properties: {<br>            embedding: {<br>              type: &quot;knn_vector&quot;,<br>              dimension: embedding.length,<br>            },<br>            book_name: {<br>              type: &quot;text&quot;,<br>            },<br>          },<br>        },<br>      };<br><br>      await client.indices.create({<br>        index: indexName,<br>        body: settings,<br>      });<br>    }<br><br>    // Store the document with embedding and book name<br>    const response = await client.index({<br>      index: indexName,<br>      body: {<br>        embedding,<br>        book_name: bookName,<br>      },<br>    });<br><br>    return {<br>      statusCode: 200,<br>      message: &quot;Embedding stored successfully&quot;,<br>      response: response.body,<br>    };<br>  } catch (error) {<br>    console.error(&quot;Error storing embedding:&quot;, error);<br>    throw error;<br>  }<br>};</pre><p>In this code we are:</p><ul><li>Creating an OpenSearch client using the helper we defined earlier.</li><li>We check if the index exists. If not, we create it and enable k-nearest neighbour (kNN) search by setting knn: true.</li><li>The mapping defines two fields: embedding (as a knn_vector) and book_name (as plain text).</li><li>Finally, we store the embedding and book name as a new document in the index.</li></ul><p>The next step is to create our CDK code for the Store Book State Machine. There is a lot of code here but we will break it down below:</p><pre>// Common environment variables for Lambda functions<br>const lambdaEnvironment = {<br>  OPENSEARCH_COLLECTION_ENDPOINT: collection.attrCollectionEndpoint,<br>  OPENSEARCH_COLLECTION_NAME: &quot;book-recommendation-collection&quot;,<br>  OPENSEARCH_INDEX_NAME: &quot;book-recommendations&quot;,<br>  VECTOR_FIELD_NAME: &quot;embedding&quot;,<br>  REGION_NAME: cdk.Stack.of(this).region,<br>};<br><br>// Lambda function to store embeddings<br>const storeEmbeddingFn = new NodejsFunction(<br>  this,<br>  &quot;StoreEmbeddingFunction&quot;,<br>  {<br>    runtime: Runtime.NODEJS_20_X,<br>    handler: &quot;handler&quot;,<br>    entry: join(__dirname, &quot;lambda/store-embedding.ts&quot;),<br>    timeout: cdk.Duration.seconds(60),<br>    role: lambdaIamRole,<br>    environment: lambdaEnvironment,<br>  }<br>);<br><br>lambdaIamRole.addToPolicy(<br>  new PolicyStatement({<br>    effect: Effect.ALLOW,<br>    actions: [&quot;aoss:APIAccessAll&quot;],<br>    resources: [<br>      `arn:aws:aoss:${Stack.of(this).region}:${<br>        Stack.of(this).account<br>      }:collection/${collection.attrId}`,<br>    ],<br>  })<br>);<br><br>const stateMachineRole = new Role(this, &quot;StateMachineExecutionRole&quot;, {<br>  assumedBy: new ServicePrincipal(&quot;states.amazonaws.com&quot;),<br>});<br><br>stateMachineRole.addToPolicy(<br>  new PolicyStatement({<br>    effect: Effect.ALLOW,<br>    actions: [&quot;bedrock:InvokeModel&quot;],<br>    resources: [<br>      `arn:aws:bedrock:${<br>        cdk.Stack.of(this).region<br>      }::foundation-model/anthropic.claude-3-5-sonnet-20240620-v1:0`,<br>      `arn:aws:bedrock:${<br>        cdk.Stack.of(this).region<br>      }::foundation-model/amazon.titan-embed-text-v2:0`,<br>    ],<br>  })<br>);<br><br>const claudeModel = FoundationModel.fromFoundationModelId(<br>  this,<br>  &quot;ClaudeModel&quot;,<br>  FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20240620_V1_0<br>);<br><br>const claudeInput = TaskInput.fromObject({<br>  anthropic_version: &quot;bedrock-2023-05-31&quot;,<br>  max_tokens: 200,<br>  messages: [<br>    {<br>      role: &quot;user&quot;,<br>      content: [<br>        {<br>          type: &quot;text&quot;,<br>          text: stepfunctions.JsonPath.format(<br>            &#39;Please provide a detailed description of the book &quot;{}&quot;. Include plot summary, themes, and writing style.&#39;,<br>            stepfunctions.JsonPath.stringAt(&quot;$.bookName&quot;)<br>          ),<br>        },<br>      ],<br>    },<br>  ],<br>});<br><br>const titanModel = FoundationModel.fromFoundationModelId(<br>  this,<br>  &quot;TitanModel&quot;,<br>  FoundationModelIdentifier.AMAZON_TITAN_EMBED_TEXT_V2_0<br>);<br><br>// Create states for the store workflow<br>const getBookDescriptionForStore = new tasks.BedrockInvokeModel(<br>  this,<br>  &quot;Get Book Description For Store&quot;,<br>  {<br>    model: claudeModel,<br>    resultSelector: {<br>      &quot;description.$&quot;: &quot;$.Body.content[0].text&quot;,<br>    },<br>    resultPath: &quot;$.descriptionResult&quot;,<br>    body: claudeInput,<br>  }<br>);<br><br>const getEmbeddingForStore = new tasks.BedrockInvokeModel(<br>  this,<br>  &quot;Get Embedding For Store&quot;,<br>  {<br>    model: titanModel,<br>    resultSelector: {<br>      &quot;embedding.$&quot;: &quot;$.Body.embedding&quot;,<br>    },<br>    resultPath: &quot;$.embeddingResult&quot;,<br>    body: TaskInput.fromObject({<br>      inputText: stepfunctions.JsonPath.stringAt(<br>        &quot;$.descriptionResult.description&quot;<br>      ),<br>    }),<br>  }<br>);<br><br>const storeEmbedding = new tasks.LambdaInvoke(this, &quot;Store Embedding&quot;, {<br>  lambdaFunction: storeEmbeddingFn,<br>  resultPath: &quot;$.storeResult&quot;,<br>  payload: stepfunctions.TaskInput.fromObject({<br>    bookName: stepfunctions.JsonPath.stringAt(&quot;$.bookName&quot;),<br>    embedding: stepfunctions.JsonPath.stringAt(<br>      &quot;$.embeddingResult.embedding&quot;<br>    ),<br>  }),<br>});<br><br>// Workflow for storing book embeddings<br>const storeWorkflow = getBookDescriptionForStore<br>  .next(getEmbeddingForStore)<br>  .next(storeEmbedding);<br><br>// State machine for storing book embeddings<br>this.stateMachine = new stepfunctions.StateMachine(<br>  this,<br>  &quot;BookRecommendationStateMachine&quot;,<br>  {<br>    definitionBody: DefinitionBody.fromChainable(storeWorkflow),<br>    timeout: cdk.Duration.minutes(5),<br>    role: stateMachineRole,<br>  }<br>);</pre><p>Here’s what this code is doing:</p><ul><li>We define a Lambda function that stores the book embedding in OpenSearch using the helper we created earlier.</li><li>We give that Lambda permission to interact with the OpenSearch collection.</li><li>We create a Step Functions state machine that:</li></ul><ol><li>Uses Claude to generate a book description.</li><li>Passes the description to Titan to generate an embedding.</li><li>Calls the Lambda to store the embedding and book name.</li></ol><ul><li>Finally, we connect everything using CDK and deploy it with a role that has permission to call the Bedrock models.</li></ul><p>This sets up the core flow for storing books in our recommendation system.</p><h4>Creating the Find Similar Books State Machine</h4><p>For this state machine we will need to create a Lambda function that searches OpenSearch for similar books using a query.</p><pre>import { getOpenSearchClient } from &quot;./helpers/getOpenSearchClient&quot;;<br><br>export const handler = async (event: any) =&gt; {<br>  const indexName = process.env.OPENSEARCH_INDEX_NAME || &quot;book-recommendations&quot;;<br><br>  // Get the collection endpoint from environment<br>  const collectionEndpoint = process.env.OPENSEARCH_COLLECTION_ENDPOINT;<br><br>  if (!collectionEndpoint) {<br>    throw new Error(&quot;Collection endpoint is not defined.&quot;);<br>  }<br><br>  const client = getOpenSearchClient(collectionEndpoint);<br><br>  // Get embedding from event<br>  const embedding = event.embedding;<br>  const bookName = event.bookName;<br><br>  if (!embedding) {<br>    throw new Error(&quot;Missing required parameter: embedding&quot;);<br>  }<br><br>  try {<br>    // Search for similar books using k-NN query<br>    const searchResponse = await client.search({<br>      index: indexName,<br>      body: {<br>        size: 5, // Return top 5 results<br>        query: {<br>          knn: {<br>            embedding: {<br>              vector: embedding,<br>              k: 5,<br>            },<br>          },<br>        },<br>        // Exclude the original book from results if bookName is provided<br>        ...(bookName &amp;&amp; {<br>          post_filter: {<br>            bool: {<br>              must_not: {<br>                term: { book_name: bookName },<br>              },<br>            },<br>          },<br>        }),<br>      },<br>    });<br><br><br>    // Extract book names from results<br>    const results = searchResponse.body.hits.hits.map((hit: any) =&gt; ({<br>      bookName: hit._source.book_name,<br>      score: hit._score,<br>    }));<br><br>    return {<br>      statusCode: 200,<br>      similarBooks: results,<br>    };<br>  } catch (error) {<br>    console.error(&quot;Error searching for similar books:&quot;, error);<br>    throw error;<br>  }<br>};</pre><p>In this function:</p><ul><li>We create an OpenSearch client using our helper.</li><li>We send a k-nearest neighbour query using the provided embedding to find the top 5 similar vectors.</li><li>If a bookName is included, we filter it out from the results so the original book doesn&#39;t show up in its own recommendations.</li><li>We return a list of similar books along with their match scores.</li></ul><p>The next step is to create the CDK code for the Find Similar Books State Machine. This workflow is similar to the one we used for storing books, but instead of writing to OpenSearch, it queries for related titles based on embeddings.</p><pre>// Create states for the find similar books workflow<br>    const getBookDescriptionForFind = new tasks.BedrockInvokeModel(<br>      this,<br>      &quot;Get Book Description For Find&quot;,<br>      {<br>        model: claudeModel,<br>        resultSelector: {<br>          &quot;description.$&quot;: &quot;$.Body.content[0].text&quot;,<br>        },<br>        resultPath: &quot;$.descriptionResult&quot;,<br>        body: claudeInput,<br>      }<br>    );<br><br>    const getEmbeddingForFind = new tasks.BedrockInvokeModel(<br>      this,<br>      &quot;Get Embedding For Find&quot;,<br>      {<br>        model: titanModel,<br>        resultSelector: {<br>          &quot;embedding.$&quot;: &quot;$.Body.embedding&quot;,<br>        },<br>        resultPath: &quot;$.embeddingResult&quot;,<br>        body: TaskInput.fromObject({<br>          inputText: stepfunctions.JsonPath.stringAt(<br>            &quot;$.descriptionResult.description&quot;<br>          ),<br>        }),<br>      }<br>    );<br><br>    // Lambda function to find similar books<br>    const findSimilarBooksFn = new NodejsFunction(<br>      this,<br>      &quot;FindSimilarBooksFunction&quot;,<br>      {<br>        runtime: Runtime.NODEJS_20_X,<br>        handler: &quot;handler&quot;,<br>        entry: join(__dirname, &quot;lambda/find-similar-books.ts&quot;),<br>        timeout: cdk.Duration.seconds(60),<br>        role: lambdaIamRole,<br>        environment: lambdaEnvironment,<br>      }<br>    );<br><br>    // Step function task to find similar books<br>    const findSimilarBooks = new tasks.LambdaInvoke(<br>      this,<br>      &quot;Find Similar Books&quot;,<br>      {<br>        lambdaFunction: findSimilarBooksFn,<br>        resultPath: &quot;$.similarBooksResult&quot;,<br>        payload: stepfunctions.TaskInput.fromObject({<br>          bookName: stepfunctions.JsonPath.stringAt(&quot;$.bookName&quot;),<br>          embedding: stepfunctions.JsonPath.stringAt(<br>            &quot;$.embeddingResult.embedding&quot;<br>          ),<br>        }),<br>      }<br>    );<br><br>    // Workflow for finding similar books<br>    const findSimilarBooksWorkflow = getBookDescriptionForFind<br>      .next(getEmbeddingForFind)<br>      .next(findSimilarBooks);<br><br>    // State machine for finding similar books<br>    this.findSimilarBooksStateMachine = new stepfunctions.StateMachine(<br>      this,<br>      &quot;FindSimilarBooksStateMachine&quot;,<br>      {<br>        definitionBody: DefinitionBody.fromChainable(findSimilarBooksWorkflow),<br>        timeout: cdk.Duration.minutes(5),<br>        role: stateMachineRole,<br>      }<br>    );<br><br>    stateMachineRole.addToPolicy(<br>      new PolicyStatement({<br>        effect: Effect.ALLOW,<br>        actions: [&quot;lambda:InvokeFunction&quot;],<br>        resources: [<br>          storeEmbeddingFn.functionArn,<br>          findSimilarBooksFn.functionArn,<br>        ],<br>      })<br>    );</pre><p>This workflow follows the same pattern as our Store Book State Machine:</p><ul><li>It starts by calling Claude to generate a description for the input book.</li><li>Then it uses Titan to convert that description into an embedding.</li><li>Finally, it invokes a Lambda function that queries OpenSearch using a k-nearest neighbour search and returns a list of similar books.</li></ul><p>We also make sure the Step Functions role has permission to invoke both Lambdas.</p><p>With this in place, we now have the ability to recommend similar books based on their content, not just keywords or categories.</p><h3>Testing the Recommendation Engine</h3><p>To test our recommendation engine, we need to go through two main steps:</p><ol><li>Build the knowledge base by storing some books in the OpenSearch collection.</li><li>Search for recommendations using the books we’ve already stored.</li></ol><p>We can use the state machines for this.</p><h4>Storing Books in OpenSearch</h4><p>The Store Book workflow will allow us to populate our collection with book data.</p><p>To do this:</p><ol><li>Open the AWS Console and navigate to Step Functions<strong>.</strong></li><li>Select the Store Book State Machine.</li><li>Choose Start Execution and provide an input payload like the one below:</li></ol><pre>{<br>  &quot;bookName&quot;: &quot;The Call of the Wild&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ho9d9jSCWfMS_VH_kgQSyA.png" /></figure><p>You should then see the steps of the state machine progress in real time. If everything is configured correctly, the execution should succeed and display a view such as the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSZvJqXhBNQQdUdn1SFYtg.png" /></figure><p>If you click into one of the steps in the execution flow, you’ll be able to see the inputs and outputs at each stage, including the description generated by Claude and the embedding produced by Titan.</p><p>To build up a small knowledge base, I repeated this process multiple times using popular titles from this list:<br> 👉 <a href="https://www.penguin.co.uk/discover/articles/100-must-read-classic-books">100 Must-Read Classic Books — Penguin</a></p><p>Once you’ve populated your OpenSearch collection with a variety of books, it’s time to test the recommendation functionality!</p><h4>Searching for Recommendations</h4><p>Open the Find Similar Books State Machine in the AWS Step Functions console. You can invoke the state machine using any book name of your choosing. In my case, I used the book <strong>“</strong>Persuasion<strong>”</strong> as the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-MG1GOFLBOtu5fUJaPWMg.png" /></figure><p>Again, you’ll see the state machine progress in real time and (hopefully) complete successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HoQcDg9J4YQDZXlnHxdow.png" /></figure><p>Click into the final step of the execution and scroll down to the bottom of the output. Here, you’ll see a list of recommended books along with a confidence score for each match.</p><p>In my case, the confidence scores were relatively low since the collection I tested with was still pretty small. As you continue to add more books to your OpenSearch collection, you’ll start seeing better matches and higher confidence scores!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0equyqgmjem-vcYGuoGT_w.png" /></figure><p>Here’s another test I ran, this time using the book “Les Miserables” as the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaYwM3xOC0YU1kqrm47sEA.png" /></figure><p>As you can see this recommended a slightly different result with results more similar to Les Mis!</p><h3>Wrapping Up</h3><p>In this article, we built a serverless book recommendation system using Step Functions, Lambda, Amazon Bedrock, and OpenSearch. We created two workflows, one to store book embeddings and another to find similar titles.</p><p>Please feel free to have a look at the <a href="https://github.com/thornejosh/serverless-recommendation-example">full code here</a> and leave any feedback on my solution in the comments!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iu-L8rrRMl54i0mH-6oitg.png" /><figcaption>Model: ChatGPT-4o, prompt: A futuristic AI-themed illustration featuring a humanoid robot and floating books, visually representing the concept of a serverless book recommendation system powered by Bedrock.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e1e189fb34" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/creating-a-serverless-book-recommendation-system-with-amazon-bedrock-48e1e189fb34">Creating a Serverless Book Recommendation System with Amazon Bedrock</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 Amazon Bedrock Features You Need to Know About]]></title>
            <link>https://towardsaws.com/top-5-amazon-bedrock-features-you-need-to-know-about-9dd5cc1cb5a2?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd5cc1cb5a2</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 04:54:57 GMT</pubDate>
            <atom:updated>2025-04-28T07:29:41.925Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>My favourite Bedrock features and why you should use them</strong></h4><p>Building powerful Generative AI applications in the cloud is difficult, but it doesn’t have to be.</p><p>Amazon Bedrock gives you access to a wide range of foundational models through a simple, unified interface, along with powerful features that make development faster and easier.</p><p>Yet most people aren’t taking full advantage of everything Bedrock has to offer. In this article, we’ll explore the top five features you should know about.</p><h3>1. Experiment with the Bedrock Playground</h3><p>Choosing the best model, inference parameters and prompts for your application is challenging. Finetuning these settings is even more difficult, often being a repetitive and time-consuming process.</p><p>This is where the Amazon Bedrock Playground comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1b4NL2OhVFHl0MDy.png" /><figcaption><a href="https://aws.amazon.com/blogs/aws/amazon-bedrock-now-provides-access-to-anthropics-latest-model-claude-2-1/">https://aws.amazon.com/blogs/aws/amazon-bedrock-now-provides-access-to-anthropics-latest-model-claude-2-1/</a></figcaption></figure><p>The Bedrock Playground provides a clean, intuitive interface where you can experiment with different foundational models, prompts and parameters. It allows you to quickly test configurations and find the best setup for your requirements, without writing a single line of code.</p><p>Get started with the playgrounds <a href="https://docs.aws.amazon.com/sagemaker-unified-studio/latest/userguide/bedrock-playgrounds.html">here</a>!</p><h3>2. Manage Prompts with Prompt Management</h3><p>When working with Bedrock, you need to provide a prompt to your models.</p><p>A prompt is the input you give to a foundational model to guide its response, for example, a question, instruction, or a piece of context you want the model to complete or act on.</p><p>You can either hardcode the prompt directly into your codebase or store it in your AWS account, for example using the SSM Parameter Store. These are generally fine methods for managing your prompts.<br>However, AWS recommends an alternative approach: using the <a href="https://aws.amazon.com/bedrock/prompt-management/">Prompt Management feature</a> to store your prompts within Bedrock itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcrY-vrnCx-6c8Uo63kbog.png" /><figcaption><a href="https://aws.amazon.com/bedrock/prompt-management/">https://aws.amazon.com/bedrock/prompt-management/</a></figcaption></figure><p>Prompt Management enables you to version and share prompts easily, improving collaboration across teams. Instead of hardcoding prompts, you can reference them in your code using a unique identifier, making updates and maintenance much simpler.</p><p>You can also test your prompts using the Prompt Builder, allowing you to experiment with:</p><ul><li>Different foundational models</li><li>Various model configurations</li><li>Tool configurations and more</li></ul><h3>3. Control model behaviour with Guardrails</h3><p>When using Bedrock, you may want to ensure your models are safe, accurate and aligned with rules you define. For example, you might want your model to avoid certain topics, such as politics.</p><p>With Guardrails, you can:</p><ul><li>Filter out harmful or inappropriate content</li><li>Redact sensitive information</li><li>Apply automated reasoning to prevent hallucinations, helping to ensure model outputs are factual and correct</li></ul><p>One of the best parts? You can apply Guardrails to any model supported within Bedrock, giving you consistent, flexible control across your applications.</p><h3>4. Use Tools to provide external data to your models</h3><p>Sometimes, your models need additional information to generate accurate responses. Using Tools in Bedrock, you can enable models to request external data from your application.</p><p>For example, if your model needs to recommend movies based on a user’s favourites, it can ask your application to call a tool that fetches this data. The model doesn’t call the tool directly, it generates a request specifying the tool and parameters and your application handles the API call and returns the results.</p><h3>5. Build GenAI workflows easily with Bedrock Flows</h3><p>Bedrock Flows allows you to visually stitch together Bedrock’s capabilities (such as prompts, knowledge bases, guardrails and more) into complete AI workflows.</p><p>Using a simple drag-and-drop interface, you can design, deploy, and iterate on your workflows without writing complex code. Bedrock Flows is fully serverless, helping you move seamlessly from prototype to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eIKWHKD8M3WdBfUb.png" /><figcaption><a href="https://aws.amazon.com/bedrock/flows/">https://aws.amazon.com/bedrock/flows/</a></figcaption></figure><p>Even better, Bedrock Studio enables easy collaboration across teams, making it faster to build and refine AI applications together!</p><h3>In Summary</h3><p>In this quick article, we explored the five most important Bedrock features that I personally use and the features you should know about as you start your Generative AI journey with AWS.</p><p>Is there anything I’ve missed? Please leave a comment and I will check out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DmG8oiQJHiVwxrc8yuy9Q.png" /><figcaption>Generated with ChatGPT</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd5cc1cb5a2" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/top-5-amazon-bedrock-features-you-need-to-know-about-9dd5cc1cb5a2">Top 5 Amazon Bedrock Features You Need to Know About</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Amazon S3 Configurations You Need to Know]]></title>
            <link>https://levelup.gitconnected.com/5-amazon-s3-configurations-you-need-to-know-f4ac849ba99b?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4ac849ba99b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 14:16:17 GMT</pubDate>
            <atom:updated>2025-03-24T14:16:17.829Z</atom:updated>
            <content:encoded><![CDATA[<h4>Essential Settings for Optimising your Amazon S3 Storage Bucket</h4><h3>Introduction</h3><p>Amazon S3 is an object storage service that is managed by AWS. The service is ideal for hosting web applications, storing images, or supporting a variety of other use cases, all while conforming to industry best practices.</p><h3>1. Access Control</h3><p>When configuring your buckets, it is essential to set up access control correctly to ensure that data is not unintentionally exposed to unauthorised resources or actors. AWS provides several methods to grant or restrict access to your S3 buckets and objects:</p><ul><li><strong>Bucket Policy</strong>: A bucket policy is a JSON document attached to the bucket, allowing you to define who can access the bucket and its objects, what actions they can perform, and under what conditions (e.g., IP or encryption requirements).</li><li><strong>Access Control Lists (ACLs)</strong>: ACLs provide basic, object-level permissions (e.g. READ or WRITE) that can be granted to specific AWS accounts or predefined groups. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html">It is recommended to use other access control methods instead of ACLs</a>.</li><li><strong>Block Public Access: </strong>This feature acts as a safeguard, overriding bucket policies and ACLs to prevent public exposure of your data unless explicitly required for use cases like static website hosting.</li><li><strong>IAM Roles</strong>: Although not configured directly on the bucket, IAM roles can be attached to AWS resources like EC2 instances or Lambda functions, allowing those resources to securely access S3 buckets without embedding long-term credentials.</li></ul><h3>2. <strong>Data Durability and Resilience</strong></h3><p>Amazon S3 offers powerful features to ensure the durability, resilience, and availability of your data. These capabilities protect against accidental deletions, data corruption, and regional failures:</p><ul><li><strong>Versioning</strong>: Enable versioning on your S3 buckets to maintain multiple versions of an object. This safeguards against accidental overwrites or deletions, allowing you to restore previous versions when needed.</li><li><strong>Object Lock</strong>: Use Object Lock to enforce write-once-read-many (WORM) storage, making objects immutable for a specified retention period. This prevents modifications or deletions and is particularly valuable for regulatory compliance and long-term data retention.</li><li><strong>Cross-Region Replication (CRR)</strong>: Configure CRR to automatically replicate your bucket’s contents to another AWS Region. This ensures geographic redundancy, providing resilience against regional outages and supporting disaster recovery requirements.</li></ul><h3>3. Storage Classes</h3><p>An S3 storage class determines how data is stored and accessed, with variations in cost, retrieval speed, and durability. Depending on your data access patterns and retention requirements, you can select a class that aligns with your needs. Here are some of the primary storage classes:</p><ul><li><strong>S3 Standard</strong>: For frequently accessed data with low latency and high throughput.</li><li><strong>S3 Standard-Infrequent Access (IA)</strong>: Lower cost for data accessed less often but still requiring rapid retrieval.</li><li><strong>S3 Glacier: </strong>Cost-effective for archival data with retrieval times ranging from minutes to hours.</li></ul><h4><strong>Lifecycle Rules</strong></h4><p>Lifecycle rules automate cost optimisation by transitioning objects between storage classes or deleting them based on predefined criteria:</p><ul><li><strong>Transition Rules</strong>: Automatically move data to lower-cost storage classes after a specified period.</li><li><strong>Expiration Rules</strong>: Delete old or unnecessary objects to free up space and reduce costs.</li></ul><p>By choosing appropriate storage classes and setting up lifecycle rules, you can effectively manage costs while maintaining performance and accessibility for your data.</p><h3>4. Transfer Acceleration</h3><p>When your application experiences slow upload speeds to Amazon S3 — especially over long distances — Transfer Acceleration can significantly improve performance (by up to 500%).</p><p>It leverages Amazon CloudFront’s globally distributed edge locations to route data through optimised network paths. This helps reduce variability caused by internet routing and congestion.</p><p>The catch? While Transfer Acceleration can improve performance, it comes at an additional cost. It’s important to evaluate whether the performance gains are worth the added expense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTIsYZ91PHQsyv2p-Akxqg.png" /><figcaption>Transfer Acceleration Pricing as of March 2025</figcaption></figure><p>You can assess whether Transfer Acceleration is right for your use case using the official <a href="https://s3-accelerate-speedtest.s3-accelerate.amazonaws.com/en/accelerate-speed-comparsion.html">S3 Transfer Acceleration Speed Comparison Tool</a>.</p><h3>5. Requester Pays</h3><p>By default, the AWS account that owns an S3 bucket pays for all data transfer and request costs — even when the data is accessed by other users. Enabling Requester Pays shifts the cost burden to the requester. This is especially useful for open or research dataset hosting, as well as cross-account collaboration.</p><p>There are things to consider when activating requester pays:</p><ul><li><strong>Authenticated Requests: </strong>Requesters must use AWS credentials — anonymous access is not supported.</li><li><strong>Cost Responsibility:</strong> Only data transfer and request costs are shifted; storage costs remain with the bucket owner.</li><li><strong>Access Complexity:</strong> Managing access patterns — especially when combining public and private access — can become more complex with this setting.</li></ul><h3><strong>Conclusion</strong></h3><p>Amazon S3 offers a rich set of configurations to optimise for security, performance, cost-efficiency, and resilience. By leveraging these key features, you can tailor your storage solution to meet both operational and business needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fiDTOulGzQPbFB8MZRZQFQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4ac849ba99b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/5-amazon-s3-configurations-you-need-to-know-f4ac849ba99b">5 Amazon S3 Configurations You Need to Know</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The One OpenAI Feature That Changes How You Build AI Apps]]></title>
            <link>https://levelup.gitconnected.com/the-one-openai-feature-that-changes-how-you-build-ai-apps-563d40ca1648?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/563d40ca1648</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 18:10:26 GMT</pubDate>
            <atom:updated>2025-03-20T18:10:26.571Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop over-engineering prompts — use this instead</h4><p>Imagine this: you work for a company that lists vehicles on a marketplace. You are building out the latest feature your CTO has asked for.</p><p>Like many companies today, your CTO has jumped on the AI bandwagon. They have asked you to use OpenAI to generate a description of a car to compare it against other listings.</p><p>You decide to utilise the <a href="https://platform.openai.com/docs/overview">OpenAI API</a> with GPT-4o, and have been reading about prompt engineering to craft the best prompt for your application.</p><p>Reasonably, you have created a prompt similar to this:</p><blockquote>You are an expert automotive assistant that provides detailed specifications, features, and history of cars. Provide detailed information about the {car_make} {car_model} {car_year}. Include specifications, engine details, fuel efficiency, safety features, technology, and common issues.</blockquote><p>Unexpectedly, your model produces a verbose output when, really, you just want it to return a few values. After some prompt fine-tuning you are getting closer to a solution, however there is always something that is off with the output.</p><p>Ultimately, you want the model to return a structured output so it is compatible with other systems in your company — but no matter how much prompt engineering you do — you never seem to get the desired results.</p><h4>Enter structured outputs</h4><p>I have spent a lot of time in the above scenario, fine tuning my model to ensure it consistently returns a result in a desired output. In the above example I may just want the model to return the following type:</p><pre>type Car {<br>  carMake: string;<br>  carModel: string;<br>  carYear: number;<br>  engineSize: string;<br>  numberOfDoors: string;<br>}</pre><p>While it is easy enough to create a prompt for this simple example, for more complicated scenarios, it can be a lot more difficult and a lot less reliable.</p><p>Instead of relying solely on prompt engineering, there is a better alternative.</p><p><a href="https://platform.openai.com/docs/guides/structured-outputs?api-mode=chat">Structured outputs</a>, as they are called in the OpenAI API, ensure that your API responses conform to a specified format.</p><p>Here is an example code snippet showing it in action:</p><pre>from pydantic import BaseModel<br>from openai import OpenAI<br><br>client = OpenAI()<br><br>class Car(BaseModel):<br>    make: str<br>    model: str<br>    year: int<br>    engine_size: str<br>    number_of_doors: int<br><br>completion = client.beta.chat.completions.parse(<br>    model=&quot;gpt-4o-2024-08-06&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are an expert automotive assistant that provides information about cars. Provide details about the car.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;2009 Ford Fiesta&quot;},<br>    ],<br>    response_format=Car,<br>)<br><br>car_details = completion.choices[0].message.parsed</pre><p>First, we define the expected structured output. Then, we specify our prompt (notice how simple it is) and provide the car details.</p><p>Structured output ensures that our model produces a response that conforms to our JSON schema, resulting in something like this:</p><pre>{<br>  &quot;make&quot;: &quot;Ford&quot;,<br>  &quot;model&quot;: &quot;Fiesta&quot;,<br>  &quot;year&quot;: 2009,<br>  &quot;engine_size&quot;: &quot;1.4L I4&quot;,<br>  &quot;number_of_doors&quot;: &quot;5&quot;<br>}</pre><p>This predictable behaviour allows you to validate and test more easily while also making it possible to integrate your model with other systems.</p><h4>To summarise</h4><p>Most model providers will offer a similar solution to structured outputs. I cover Amazon Bedrocks alternative <a href="https://medium.com/towards-aws/building-a-serverless-document-extraction-service-with-bedrock-35433183e036">here</a>.</p><p>Use this feature to provide extra context to your model. It is a quick and powerful way to supercharge your models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXQ7efCz6ChnSrOu6o-PTw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=563d40ca1648" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-one-openai-feature-that-changes-how-you-build-ai-apps-563d40ca1648">The One OpenAI Feature That Changes How You Build AI Apps</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless Document Extraction Service with Bedrock]]></title>
            <link>https://towardsaws.com/building-a-serverless-document-extraction-service-with-bedrock-35433183e036?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/35433183e036</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 08:17:52 GMT</pubDate>
            <atom:updated>2025-03-14T08:22:20.080Z</atom:updated>
            <content:encoded><![CDATA[<h4>With architecture diagrams and code examples using CDK and TypeScript</h4><h3>Introduction</h3><p>In this article I show you how to build an OCR (optical character recognition) application that will scale to handle high loads using Serverless services.</p><h3>What Are We Building</h3><p>We are going to build a Serverless application on AWS that processes CVs when uploaded to an S3 bucket to extract key information. We will specify the information we want to be retrieved such as the candidate’s name, their highest level of education, employment history, and more.</p><p>Here is the architecture diagram for the application we will build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*FzvYPzwbiUE0LJ-9Kc4VTQ.png" /></figure><ol><li>The user uploads their PDF CV to an S3 bucket</li><li>A Lambda is triggered by an S3 event when the PDF is uploaded</li><li>The Lambda extracts the key information according to our schema utilising Claude Sonnet in Bedrock using Claude 3 Sonnet</li><li>The structured output is then saved to a DynamoDB table for further processing</li></ol><p>There are many moving parts in our application — we will go through each step and the code required to get there. By the way, you can skip ahead and <a href="https://github.com/thornejosh/bedrock-cv-extractor">access the full code here</a>.</p><h3>Creating the Infrastructure</h3><p>We will use CDK and TypeScript to build the application. If you haven’t used CDK before, I encourage you to follow <a href="https://docs.aws.amazon.com/cdk/v2/guide/hello_world.html">the docs</a> to get started.</p><p>We will first update our stack to create an S3 bucket to store the PDF CVs:</p><pre>const cvExtractorBucket = new Bucket(this, &quot;CVExtractorBucket&quot;, {<br>  removalPolicy: RemovalPolicy.DESTROY,<br>  autoDeleteObjects: true,<br>});</pre><p>The removal policy has been configured to delete our S3 bucket on teardown, even if our bucket contains data. This is useful for development as we want to quickly spin up and tear down environments, but it is recommended to retain your data in production to prevent against accidental deletion.</p><p>Next, we will create a DynamoDB table to store the result of our data extraction:</p><pre>const cvExtractorTable = new Table(this, &quot;CVExtractorTable&quot;, {<br>      partitionKey: { name: &quot;id&quot;, type: AttributeType.STRING },<br>      billingMode: BillingMode.PAY_PER_REQUEST,<br>      removalPolicy: RemovalPolicy.DESTROY,<br>    });</pre><p>Again, we have the same removal policy for easy cleanup.</p><p>We then create our Lambda function with the necessary permissions to:</p><ul><li>Read the CV file from S3</li><li>Write data to the DynamoDB table</li><li>Invoke Bedrock to extract data from our CV document</li></ul><pre>// Create Lambda function<br>const processCvFunction = new NodejsFunction(this, &quot;ProcessCVFunction&quot;, {<br>  runtime: Runtime.NODEJS_18_X,<br>  handler: &quot;handler&quot;,<br>  entry: join(__dirname, &quot;lambda/processCv.ts&quot;),<br>  environment: {<br>    BUCKET_NAME: cvExtractorBucket.bucketName,<br>    TABLE_NAME: cvExtractorTable.tableName,<br>  },<br>  timeout: Duration.minutes(5),<br>});<br><br>// Grant Lambda permissions to read from S3<br>cvExtractorBucket.grantRead(processCvFunction);<br><br>// Grant Lambda permissions to write to DynamoDB<br>cvExtractorTable.grantWriteData(processCvFunction);<br><br>// Add Bedrock permissions to Lambda role<br>processCvFunction.addToRolePolicy(<br>  new PolicyStatement({<br>    effect: Effect.ALLOW,<br>    actions: [&quot;bedrock:InvokeModel&quot;],<br>    resources: [<br>      `arn:aws:bedrock:${<br>        Stack.of(this).region<br>      }::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0`,<br>    ],<br>  })<br>);</pre><p>The last step is to ensure that our S3 bucket invokes the Lambda function whenever a document is uploaded:</p><pre>cvExtractorBucket.addEventNotification(<br>  EventType.OBJECT_CREATED,<br>  new LambdaDestination(processCvFunction)<br>);</pre><p>This will deploy the infrastructure for our application but we still need to write the Lambda handler code to extract the CV data. We will do this in the next step!</p><h3>Writing the Lambda Handler</h3><p>In this section, we will create the necessary logic to perform our data extraction.</p><h4>Fetching the PDF File from S3</h4><p>Our Lambda will be invoked by an S3 event that contains the object and key of the uploaded PDF file. This will enable us to download the PDF file.</p><p>Using the AWS SDK S3 Client, we download the data from S3 and transform it into a buffer:</p><pre>const getDocumentFromS3 = async (<br>  bucket: string,<br>  key: string<br>): Promise&lt;Uint8Array&gt; =&gt; {<br>  try {<br>    const getObjectCommand = new GetObjectCommand({<br>      Bucket: bucket,<br>      Key: key,<br>    });<br><br>    const response = await s3Client.send(getObjectCommand);<br>    const content = await response.Body?.transformToByteArray();<br><br>    if (!content) {<br>      throw new Error(&quot;No content found in CV file&quot;);<br>    }<br><br>    return content;<br>  } catch (error) {<br>    console.error(&quot;Error retrieving document from S3:&quot;, error);<br>    throw new Error(<br>      `Failed to retrieve document from S3: ${<br>        error instanceof Error ? error.message : String(error)<br>      }`<br>    );<br>  }<br>};</pre><h4>Performing the OCR</h4><p>Once we have the data from S3 in a buffer format, we can pass it to Bedrock to extract the necessary data.</p><p>However, we need to ensure that our data is returned in a structured format, conforming to a specified schema.</p><p>We are going to create a JSON schema to specify the information we want to extract from the CV:</p><pre>const CVDataSchema = {<br>  type: &quot;object&quot;,<br>  properties: {<br>    fullName: {<br>      type: &quot;string&quot;,<br>      description: &quot;The full name of the candidate&quot;,<br>    },<br>    email: {<br>      type: &quot;string&quot;,<br>      format: &quot;email&quot;,<br>      description: &quot;The email address of the candidate&quot;,<br>    },<br>    phoneNumber: {<br>      type: &quot;string&quot;,<br>      description: &quot;The contact phone number of the candidate&quot;,<br>    },<br>    location: {<br>      type: &quot;string&quot;,<br>      description: &quot;The geographic location of the candidate&quot;,<br>    },<br>    professionalSummary: {<br>      type: &quot;string&quot;,<br>      description:<br>        &quot;A summary of the candidate&#39;s professional background and expertise&quot;,<br>    },<br>    workExperience: {<br>      type: &quot;array&quot;,<br>      items: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          companyName: {<br>            type: &quot;string&quot;,<br>            description: &quot;Name of the company where the candidate worked&quot;,<br>          },<br>          position: {<br>            type: &quot;string&quot;,<br>            description: &quot;Job title or position held by the candidate&quot;,<br>          },<br>          startDate: {<br>            type: &quot;string&quot;,<br>            description: &quot;Start date of employment&quot;,<br>          },<br>          endDate: {<br>            type: &quot;string&quot;,<br>            description: &quot;End date of employment&quot;,<br>          },<br>          isCurrentPosition: {<br>            type: &quot;boolean&quot;,<br>            description:<br>              &quot;Indicates if this is the candidate&#39;s current position&quot;,<br>          },<br>          responsibilities: {<br>            type: &quot;array&quot;,<br>            items: {<br>              type: &quot;string&quot;,<br>            },<br>            description: &quot;List of job responsibilities&quot;,<br>          },<br>        },<br>        required: [&quot;companyName&quot;, &quot;position&quot;, &quot;startDate&quot;, &quot;responsibilities&quot;],<br>      },<br>      description: &quot;The candidate&#39;s work history&quot;,<br>    },<br>    education: {<br>      type: &quot;array&quot;,<br>      items: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          institution: {<br>            type: &quot;string&quot;,<br>            description: &quot;Name of the educational institution attended&quot;,<br>          },<br>          degree: {<br>            type: &quot;string&quot;,<br>            description: &quot;Type of degree obtained&quot;,<br>          },<br>          fieldOfStudy: {<br>            type: &quot;string&quot;,<br>            description: &quot;Major or field of study&quot;,<br>          },<br>          graduationDate: {<br>            type: &quot;string&quot;,<br>            description: &quot;Date of graduation&quot;,<br>          },<br>        },<br>        required: [&quot;institution&quot;, &quot;degree&quot;, &quot;fieldOfStudy&quot;],<br>      },<br>      description: &quot;The candidate&#39;s educational background&quot;,<br>    },<br>  },<br>  required: [&quot;fullName&quot;, &quot;email&quot;, &quot;workExperience&quot;, &quot;education&quot;],<br>  additionalProperties: false,<br>};</pre><p>We are creating a JSON Schema directly here, but it would be better to use a schema builder such as <a href="https://zod.dev/">Zod</a> or <a href="https://yup-docs.vercel.app/docs/intro">Yup</a>.</p><p>We will also need to create a detailed prompt for our model so it has enough context to perform the data extraction accurately:</p><pre>const cvExtractorPrompt = `# CV Data Extraction Task<br><br>I&#39;m providing a CV/resume document, and I need you to carefully extract structured information according to our schema.<br><br>## Instructions:<br>1. Thoroughly analyze the entire CV/resume document<br>2. Extract ALL relevant information that fits our schema<br>3. Structure the data exactly according to our provided schema<br>4. Use the CVDetailsSchema tool to submit your extracted data<br><br>## Guidelines for Specific Fields:<br>- Professional Summary: Create a concise 2-3 sentence summary if not explicitly provided<br>- Work Experience: <br>  * Extract detailed responsibilities and achievements from bullet points<br>  * Format dates consistently (YYYY-MM format if possible)<br>  * Mark current position appropriately<br>  * If resume uses phrases like &quot;Present&quot; or &quot;Current,&quot; set isCurrentPosition to true<br>- Education: Format degree information consistently (e.g., &quot;Bachelor of Science&quot;, &quot;Master of Arts&quot;)<br>  * Convert degree abbreviations to full names (e.g., &quot;BS&quot; to &quot;Bachelor of Science&quot;)<br><br>## Handling Edge Cases:<br>- If information is ambiguous, use your best judgment and prioritize accuracy<br>- If required fields are missing (fullName, email, workExperience, education), provide placeholder text indicating &quot;Not found in document&quot;<br>- For missing optional fields, simply omit them<br>- If dates are unclear, use approximate dates and note uncertainty<br><br>## Example Output Structure:<br>Here&#39;s how a properly extracted CV might look (abbreviated example):<br><br>\`\`\`json<br>{<br>  &quot;fullName&quot;: &quot;Jane Smith&quot;,<br>  &quot;email&quot;: &quot;jane.smith@email.com&quot;,<br>  &quot;phoneNumber&quot;: &quot;555-123-4567&quot;,<br>  &quot;location&quot;: &quot;Seattle, WA&quot;,<br>  &quot;professionalSummary&quot;: &quot;Senior software engineer with 8 years of experience in cloud architecture and distributed systems. Specialized in AWS infrastructure and microservices design.&quot;,<br>  &quot;workExperience&quot;: [<br>    {<br>      &quot;companyName&quot;: &quot;Tech Solutions Inc.&quot;,<br>      &quot;position&quot;: &quot;Senior Software Engineer&quot;,<br>      &quot;startDate&quot;: &quot;2020-06&quot;,<br>      &quot;isCurrentPosition&quot;: true,<br>      &quot;responsibilities&quot;: [<br>        &quot;Led development of cloud-native microservices using AWS Lambda and API Gateway&quot;,<br>        &quot;Implemented CI/CD pipelines using GitHub Actions&quot;<br>      ],<br>    }<br>  ],<br>}<br>\`\`\`<br><br>Please focus on extracting ALL relevant information while maintaining high accuracy. The extracted data will be used for candidate evaluation, so completeness and correctness are essential.`;</pre><p>This is most likely not the best prompt for our model but it is a good starting point. Prompt engineering is a vital component of building a reliable OCR application. I recommend <a href="https://www.youtube.com/watch?app=desktop&amp;v=-Hjw0_PMyfQ&amp;t=0">this short video from AWS</a> to learn more about prompt engineering!</p><p>We can now create a <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/tool-use.html">Bedrock Tool</a> that ensures the response from Bedrock conforms to our JSON schema. We will pass this tool and the prompt into a ConverseCommand:</p><pre>const extractCvData = async (buffer: Uint8Array): Promise&lt;CVData&gt; =&gt; {<br>  const modelId = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;;<br><br>  const jsonTool: Tool = {<br>    toolSpec: {<br>      name: &quot;CVDetailsSchema&quot;,<br>      description:<br>        &quot;Contains a schema for the details to be extracted from the cv&quot;,<br>      inputSchema: {<br>        json: CVDataSchema,<br>      },<br>    },<br>  };<br><br>  const command = new ConverseCommand({<br>    modelId,<br>    messages: [<br>      {<br>        role: ConversationRole.USER,<br>        content: [<br>          {<br>            document: {<br>              name: &quot;cv&quot;,<br>              format: DocumentFormat.PDF,<br>              source: {<br>                bytes: buffer,<br>              },<br>            },<br>          },<br>          {<br>            text: cvExtractorPrompt,<br>          },<br>        ],<br>      },<br>    ],<br>    toolConfig: {<br>      tools: [jsonTool],<br>    },<br>  });<br><br>  try {<br>    const response = await bedrockClient.send(command);<br><br>    const contentBlocks = response.output?.message?.content;<br>    if (!contentBlocks) {<br>      throw new Error(<br>        &quot;Bedrock response did not contain expected content blocks&quot;<br>      );<br>    }<br><br>    const toolUseContentBlock = contentBlocks.find(<br>      (contentBlock) =&gt; contentBlock.toolUse !== undefined<br>    );<br><br>    if (!toolUseContentBlock?.toolUse?.input) {<br>      throw new Error(&quot;Could not find tool use content in Bedrock response&quot;);<br>    }<br><br>    // Get the raw response from the tool<br>    return toolUseContentBlock.toolUse.input as CVData;<br>  } catch (error) {<br>    console.error(&quot;Error during Bedrock AI extraction:&quot;, error);<br>    throw new Error(<br>      `Failed to extract CV data: ${<br>        error instanceof Error ? error.message : String(error)<br>      }`<br>    );<br>  }<br>};</pre><h4>Saving the Result to DynamoDB</h4><p>Once we have the structured data, we will store it in DynamoDB to be used by other services. The following code uses the AWS SDK DynamoDB Client to saved the data in a new record:</p><pre>const storeCvDataInDynamoDB = async (<br>  fileName: string,<br>  data: CVData<br>): Promise&lt;void&gt; =&gt; {<br>  try {<br>    if (!process.env.TABLE_NAME) {<br>      throw new Error(&quot;TABLE_NAME environment variable is not defined&quot;);<br>    }<br><br>    await dynamoClient.send(<br>      new PutItemCommand({<br>        TableName: process.env.TABLE_NAME,<br>        Item: {<br>          id: { S: randomUUID() },<br>          fileName: { S: fileName },<br>          analysisResult: { S: JSON.stringify(data) },<br>          timestamp: { S: new Date().toISOString() },<br>        },<br>      })<br>    );<br>  } catch (error) {<br>    console.error(&quot;Error storing CV data in DynamoDB:&quot;, error);<br>    throw new Error(<br>      `Failed to store CV data: ${<br>        error instanceof Error ? error.message : String(error)<br>      }`<br>    );<br>  }<br>};</pre><h4>Putting it all Together</h4><p>Nice! We have created the code for all the steps of our service. We can now call each step in order from our Lambda handler:</p><pre>export const handler = async (event: S3Event) =&gt; {<br>  try {<br>    // Validate input<br>    if (!event.Records || event.Records.length === 0) {<br>      throw new Error(&quot;No records found in S3 event&quot;);<br>    }<br><br>    // Get the S3 bucket and key from the event<br>    const bucket = event.Records[0].s3.bucket.name;<br>    const key = decodeURIComponent(<br>      event.Records[0].s3.object.key.replace(/\+/g, &quot; &quot;)<br>    );<br><br>    // Get the CV file from S3<br>    const cvContent = await getDocumentFromS3(bucket, key);<br><br>    // Extract the CV information using Bedrock<br>    const data = await extractCvData(cvContent);<br><br>    // Store the analysis results in DynamoDB<br>    await storeCvDataInDynamoDB(key, data);<br><br>    return {<br>      statusCode: 200,<br>      body: JSON.stringify({<br>        message: &quot;CV processed successfully&quot;,<br>        result: data,<br>      }),<br>    };<br>  } catch (error) {<br>    console.error(&quot;Error processing CV:&quot;, error);<br><br>    return {<br>      statusCode: 500,<br>      body: JSON.stringify({<br>        message: &quot;Error processing CV&quot;,<br>        error: error instanceof Error ? error.message : String(error),<br>      }),<br>    };<br>  }<br>};</pre><h3>Testing the Application</h3><p>To test the application, feel free to upload your own CV to the S3 bucket or, in my case, I downloaded a <a href="https://www.canva.com/create/resumes/">free CV template from canva</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xktf3iwiQbPkCgs9AfVf0g.png" /></figure><p>Upload the PDF to the S3 bucket we have provisioned. You can then navigate to the DynamoDB table to see the parsed CV data as a new record.</p><p>The above CV resulted in the following structured output:</p><pre><br>{<br>  details: {<br>    fullName: &#39;Olivia Wilson&#39;,<br>    email: &#39;hello@reallygreatsite.com&#39;,<br>    phoneNumber: &#39;+123-456-7890&#39;,<br>    location: &#39;123 Anywhere St., Any City&#39;,<br>    professionalSummary: &#39;Experienced and results-driven Marketing Manager with a proven track record in developing and executing successful marketing strategies. I am seeking a challenging role where I can contribute my skills in strategic planning, team leadership, and creative problem-solving to achieve business objectives.&#39;,<br>    workExperience: [<br>      {<br>        companyName: &#39;Borcelle Studio&#39;,<br>        position: &#39;Marketing Manager &amp; Specialist&#39;,<br>        startDate: &#39;2030&#39;,<br>        isCurrentPosition: true,<br>        responsibilities: [<br>          &#39;Led the development and implementation of comprehensive marketing strategies that resulted in a 20% increase in brand visibility and a 15% growth in sales within the first year.&#39;,<br>          &#39;Successfully launched and managed multiple cross-channel campaigns, including digital marketing, social media, and traditional advertising, resulting in improved customer acquisition and retention rates.&#39;,<br>          &#39;Conducted market research to identify emerging trends and consumer preferences, providing valuable insights for product development and positioning.&#39;,<br>          &#39;Oversaw the creation of engaging content for various platforms, collaborating with internal teams and external agencies to ensure brand consistency and relevance.&#39;<br>        ]<br>      },<br>      {<br>        companyName: &#39;Fauget Studio&#39;,<br>        position: &#39;Marketing Manager &amp; Specialist&#39;,<br>        startDate: &#39;2025&#39;,<br>        endDate: &#39;2029&#39;,<br>        responsibilities: []<br>      },<br>      {<br>        companyName: &#39;Studio Shodwe&#39;,<br>        position: &#39;Marketing Manager &amp; Specialist&#39;,<br>        startDate: &#39;2024&#39;,<br>        endDate: &#39;2025&#39;,<br>        responsibilities: [<br>          &#39;Developed and executed targeted marketing campaigns, resulting in a 25% increase in lead generation.&#39;,<br>          &#39;Implemented SEO strategies that improved website traffic by 30%, enhancing online visibility and positioning the company.&#39;,<br>          &#39;Collaborated with sales teams to create effective sales collateral, presentations, and promotional materials.&#39;<br>        ]<br>      }<br>    ],<br>    education: [<br>      {<br>        institution: &#39;Borcelle University&#39;,<br>        degree: &#39;Master of Business Management&#39;,<br>        fieldOfStudy: null,<br>        graduationDate: &#39;2030&#39;<br>      },<br>      {<br>        institution: &#39;Borcelle University&#39;,<br>        degree: &#39;Bachelor of Business Management&#39;,<br>        fieldOfStudy: null,<br>        graduationDate: &#39;2029&#39;,<br>        gpa: &#39;3.8/4.0&#39;<br>      }<br>    ]<br>  }<br>}</pre><p>As you can see the result is very accurate! Feel free to update the model, schema and prompt to fine-tune the application for your needs.</p><h3>Wrapping Up</h3><p>In this article we created a simple Serverless CV OCR application using Amazon Bedrock. You can use the code snippets to create a reliable OCR application for your needs!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fLHFCdTocbH_h01xpGzP_A.png" /><figcaption>Model: <a href="https://openart.ai/create?mode=create&amp;ai_model=openart/OpenArt_SDXL">OpenArt SDXL</a>, Prompt: A clean and modern illustration of a document being scanned with AI-powered OCR. The document has a few glowing lines of extracted text. A subtle cloud icon in the background represents serverless processing. The color scheme is minimalistic with shades of blue and white, conveying a tech-focused theme.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35433183e036" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/building-a-serverless-document-extraction-service-with-bedrock-35433183e036">Building a Serverless Document Extraction Service with Bedrock</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Your Staging Site on AWS with Basic Authentication]]></title>
            <link>https://towardsaws.com/secure-your-staging-site-on-aws-with-basic-authentication-c58e1364c605?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58e1364c605</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 06:10:12 GMT</pubDate>
            <atom:updated>2024-11-26T06:10:12.019Z</atom:updated>
            <content:encoded><![CDATA[<h4>SERVERLESS SECURITY</h4><h4><strong>How to Use Lambda@Edge for Simple and Effective Access Control</strong></h4><h3>Introduction</h3><p>When developing a web application, you will likely have a staging site to test and preview the code before deploying to production. Typically, you want to restrict public access to this site to prevent exposure of unreleased features or potential vulnerabilities while still allowing access for stakeholders and team members.</p><p>A straightforward way to achieve this is by implementing basic authentication, which restricts access to users who know the valid credentials. In this article, we will guide you through setting up basic authentication for a site hosted on Amazon S3 and served via Amazon CloudFront.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RII6NWwg4zkVJgRgptvF1A.png" /><figcaption>Basic authentication on a staging site</figcaption></figure><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oitTVwl-_-XsddbsjaeMTg.png" /></figure><p>The website will be hosted on Amazon S3, served via Amazon CloudFront, and secured with a Lambda@Edge function:</p><ol><li><strong>Amazon S3</strong>: The website’s static files (HTML, CSS, JavaScript, images, etc.) are hosted in an Amazon S3 bucket, which provides a reliable, scalable, and cost-effective storage solution.</li><li><strong>Amazon CloudFront</strong>: A Content Delivery Network (CDN) that serves the website to users with low latency and high performance. It also adds an additional layer of security, including HTTPS support and customisable caching.</li><li><strong>Lambda@Edge</strong>: A serverless function that operates at the edge of the AWS network. In this architecture, Lambda@Edge is used to intercept incoming HTTP requests, verify authentication credentials, and block unauthorised users from accessing the site.</li></ol><p>When a user tries to access the site, their request is routed through CloudFront. CloudFront forwards the request to the Lambda@Edge function, which checks the credentials against the configured basic authentication logic. If the credentials are valid, the request is allowed to proceed to the S3 bucket, where the static content is served. If authentication fails, the function denies the request, and the user receives an HTTP 401 Unauthorised response.</p><blockquote>You can find the complete source code used in this article <a href="https://github.com/thornejosh/articles-protected-aws-site">here</a>.</blockquote><h3><strong>Creating the Website</strong></h3><p>In this section, we will set up our environment using AWS CDK (Cloud Development Kit) to deploy infrastructure and Next.js for our website. We will create two CDK stacks: one for the Lambda@Edge function and another for the S3 and CloudFront configuration.</p><h3><strong>The Backend</strong></h3><h4>1. <strong>Initialise the CDK Application</strong></h4><p>Start by initialising your CDK application using the following command:</p><pre>cdk init app --language=typescript</pre><p>This will generate a boilerplate project structure for your CDK application, including a default stack.</p><h4>2. <strong>Set Up a Separate Stack for Lambda@Edge</strong></h4><p>Since Lambda@Edge functions must be deployed in the us-east-1 region (regardless of where the rest of your infrastructure is hosted), you will need to create a new stack specifically for the Lambda@Edge function. This stack will contain the logic for authenticating incoming requests.</p><p>Create a new file for your stack (e.g. edge-function-stack.ts) and add the following code:</p><pre>import * as cdk from &quot;aws-cdk-lib&quot;;<br>import { Construct } from &quot;constructs&quot;;<br>import * as cloudfront from &quot;aws-cdk-lib/aws-cloudfront&quot;;<br>import * as lambda from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import * as path from &quot;path&quot;;<br><br>export class EdgeFunctionStack extends cdk.Stack {<br>  public readonly authFunction: cloudfront.experimental.EdgeFunction;<br><br>  constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br>    super(scope, id, props);<br><br>    // Create Lambda@Edge function for basic authentication<br>    this.authFunction = new cloudfront.experimental.EdgeFunction(this, &quot;AuthFunction&quot;, {<br>      runtime: lambda.Runtime.NODEJS_18_X,<br>      handler: &quot;index.handler&quot;,<br>      code: lambda.Code.fromAsset(path.join(__dirname, &quot;auth-handler&quot;)),<br>    });<br>  }<br>}</pre><h4>3. Create the Authentication Logic</h4><p>Under the lib directory, create a folder named auth-handler and an index.js file inside the folder. Add the following code:</p><pre>const handler = async (event) =&gt; {<br>    const request = event.Records[0].cf.request;<br>    const headers = request.headers;<br>    const username = &quot;admin&quot;;<br>    const password = &quot;password123&quot;; <br>    <br>    // Decode Authorization header<br>    const authHeader = headers.authorization;<br>    const expectedAuth = &#39;Basic &#39; + Buffer.from(`${username}:${password}`).toString(&#39;base64&#39;);<br>    <br>    if (authHeader &amp;&amp; authHeader[0].value === expectedAuth) {<br>        return request; // Pass the request to the origin if authentication succeeds<br>    }<br><br>    // Return 401 Unauthorized if authentication fails<br>    }<br>    <br>    return {<br>        status: &#39;401&#39;,<br>        statusDescription: &#39;Unauthorized&#39;,<br>        headers: {<br>            &#39;www-authenticate&#39;: [{ key: &#39;WWW-Authenticate&#39;, value: &#39;Basic realm=&quot;Enter your credentials&quot;&#39; }],<br>            &#39;content-type&#39;: [{ key: &#39;Content-Type&#39;, value: &#39;text/plain&#39; }]<br>        },<br>        body: &#39;Unauthorized&#39;<br>    };<br>};<br>exports.handler = handler;</pre><h4>4. Add the CloudFront and S3 CDK Code</h4><p>Now that the authentication function is ready, configure the S3 bucket and CloudFront distribution. Update the first stack with the following S3 and CloudFront code:</p><pre>import * as cdk from &quot;aws-cdk-lib&quot;;<br>import { Construct } from &quot;constructs&quot;;<br>import * as s3 from &quot;aws-cdk-lib/aws-s3&quot;;<br>import * as cloudfront from &quot;aws-cdk-lib/aws-cloudfront&quot;;<br>import * as origins from &quot;aws-cdk-lib/aws-cloudfront-origins&quot;;<br>import * as s3deploy from &quot;aws-cdk-lib/aws-s3-deployment&quot;;<br>import * as path from &quot;path&quot;;<br><br>interface ProtectedAwsSiteStackProps extends cdk.StackProps {<br>  existingEdgeFunction: cloudfront.experimental.EdgeFunction;<br>}<br><br>export class ProtectedAwsSiteStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props?: ProtectedAwsSiteStackProps) {<br>    super(scope, id, props);<br><br>    // Create an S3 bucket to host the website<br>    const siteBucket = new s3.Bucket(this, &quot;ProtectedSiteBucket&quot;, {<br>      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,<br>      removalPolicy: cdk.RemovalPolicy.DESTROY,<br>      autoDeleteObjects: true,<br>    });<br><br>    if (!props?.existingEdgeFunction) {<br>      throw new Error(&#39;existingEdgeFunction is required&#39;);<br>    }<br><br>    // Create CloudFront distribution<br>    const distribution = new cloudfront.Distribution(<br>      this,<br>      &quot;ProtectedSiteDistribution&quot;,<br>      {<br>        defaultBehavior: {<br>          origin: new origins.S3Origin(siteBucket),<br>          edgeLambdas: [<br>            {<br>              functionVersion: props?.existingEdgeFunction?.currentVersion,<br>              eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,<br>            },<br>          ],<br>        },<br>        defaultRootObject: &quot;index.html&quot;,<br>        errorResponses: [<br>          {<br>            httpStatus: 404,<br>            responseHttpStatus: 404,<br>            responsePagePath: &quot;/404.html&quot;,<br>          },<br>        ],<br>      }<br>    );<br><br>    // Deploy site contents to S3<br>    new s3deploy.BucketDeployment(this, &quot;ProtectedSiteBucketDeployment&quot;, {<br>      sources: [s3deploy.Source.asset(path.join(__dirname, &quot;../my-site/out&quot;))],<br>      destinationBucket: siteBucket,<br>      distribution,<br>      distributionPaths: [&quot;/*&quot;],<br>    });<br><br>    // Output the CloudFront URL<br>    new cdk.CfnOutput(this, &quot;DistributionDomainName&quot;, {<br>      value: distribution.domainName,<br>      description: &quot;CloudFront distribution domain name&quot;,<br>    });<br>  }<br>}</pre><h4>5. <strong>Link the Stacks</strong></h4><p>To pass the Lambda@Edge function into the main stack (which contains the S3 and CloudFront configuration), you will need to modify your application entry point in the bin folder. Update the CDK application file to the following:</p><pre>#!/usr/bin/env node<br>import &quot;source-map-support/register&quot;;<br>import * as cdk from &quot;aws-cdk-lib&quot;;<br>import { ProtectedAwsSiteStack } from &quot;../lib/protected-aws-site-stack&quot;;<br>import { EdgeFunctionStack } from &quot;../lib/edge-function-stack&quot;;<br><br>const app = new cdk.App();<br><br>// Create the Edge function stack in us-east-1<br>const edgeFunctionStack = new EdgeFunctionStack(<br>  app,<br>  &quot;ProtectedAwsSiteEdgeFunctionStack&quot;,<br>  {<br>    env: {<br>      region: &quot;us-east-1&quot;, // Lambda@Edge functions must be deployed to us-east-1<br>    },<br>  }<br>);<br><br>// Create the main stack for S3 and CloudFront, linking the authentication function<br>new ProtectedAwsSiteStack(app, &quot;ProtectedAwsSiteStack&quot;, {<br>  crossRegionReferences: true,<br>  existingEdgeFunction: edgeFunctionStack.authFunction,<br>  env: {<br>    region: &quot;eu-west-1&quot;, // Region for the main stack<br>  },<br>});</pre><h4><strong>Summary</strong></h4><p>With this update, you now have all the necessary backend code to:</p><ul><li>Host your website in an S3 bucket.</li><li>Protect the site with basic authentication enforced by a Lambda@Edge function.</li></ul><p>Now, let’s create the frontend code for the website.</p><h3>Creating the Frontend</h3><h4>1. Create a Next.js Application</h4><p>To create the frontend for your site, run the following command to create a new Next.js application:</p><pre>npx create-next-app my-site</pre><p>Accept all the default options when prompted. This will generate a basic Next.js application in the my-site directory.</p><h4>2. Update the Build Configuration</h4><p>Modify the next.config.ts file in your Next.js project to enable static export functionality. Replace its contents with the following code:</p><pre>import type { NextConfig } from &quot;next&quot;;<br><br>const nextConfig: NextConfig = {<br>  output: &quot;export&quot;<br>  /* config options here */<br>};<br><br>export default nextConfig;</pre><p>Setting output: &quot;export&quot; tells Next.js to generate a static export of your site during the build process, which is suitable for deployment to Amazon S3.</p><h4>3. Build the Site</h4><p>Update the root package.json file in your project root by adding the following script under the “scripts” section:</p><pre>“build:site”: “cd my-site &amp;&amp; npm run build”</pre><p>Run the following command to build your site:</p><pre>npm run build:site</pre><p>Once the command completes, your static files will be available in the my-site/out directory, ready for deployment.</p><h3><strong>Deploy the Backend and Frontend</strong></h3><p>Ensure that you have run npm run build:site in the previous section and make sure your AWS credentials are configured, then deploy your stacks using CDK:</p><pre>cdk deploy --all</pre><p>This command will deploy both the Lambda@Edge stack and the CloudFront/S3 stack. It will also upload your site files to the S3 bucket and set up the necessary configurations.</p><p>After the deployment completes, the terminal will display the CloudFront distribution URL. Use this URL to access your site. Open the CloudFront URL in your browser. When prompted for credentials, enter:</p><ul><li><strong>Username</strong>: admin</li><li><strong>Password</strong>: password123</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RII6NWwg4zkVJgRgptvF1A.png" /><figcaption>Basic auth screen</figcaption></figure><p>When the authentication succeeds, you will be able to view your deployed Next.js site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7fdhb_NgXjKgWZIOCwW6g.png" /><figcaption>NextJS screen shown after entering the correct credentials</figcaption></figure><h3><strong>Conclusion</strong></h3><p>In this article, we created a staging site hosted on AWS with basic authentication for access control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1DaNHvsVaRYDXKpc" /><figcaption>Photo by <a href="https://unsplash.com/@sasun1990?utm_source=medium&amp;utm_medium=referral">Sasun Bughdaryan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58e1364c605" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/secure-your-staging-site-on-aws-with-basic-authentication-c58e1364c605">Secure Your Staging Site on AWS with Basic Authentication</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Codify Your AWS Architecture Diagrams Today]]></title>
            <link>https://towardsaws.com/codify-your-aws-architecture-diagrams-today-6b517f0ad30b?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b517f0ad30b</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 06:09:29 GMT</pubDate>
            <atom:updated>2024-11-26T06:09:29.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>AWS ARCHITECTURE</h4><h4><strong>Learn Why Writing AWS Architecture Diagrams as Code Improves Collaboration, Accuracy, and Scalability</strong></h4><h3>Introduction</h3><p>There are many tools available for creating architecture diagrams, with some of my personal favourites being <a href="https://icepanel.io/">IcePanel</a> and <a href="https://app.diagrams.net/">draw.io</a>. These tools excel at visually capturing the state of your system, helping developers understand what the system does and how its components interact.</p><p>However, drag-and-drop interfaces come with certain limitations, making code-based architecture diagrams a more effective alternative.</p><h3>What are Code-Based Architecture Diagrams?</h3><p>Code-based architecture diagrams are exactly what they sound like: diagrams created by writing code. Using a library, you define the architecture in code, and the library transforms it into a visual representation.</p><p>For example, <a href="https://mermaid.js.org/">Mermaid</a>, a JavaScript-based diagramming tool, allows you to create architecture diagrams programmatically. Here’s an example of code you might write with Mermaid:</p><pre>flowchart TD<br>    A[Christmas] --&gt;|Get money| B(Go shopping)<br>    B --&gt; C{Let me think}<br>    C --&gt;|One| D[Laptop]<br>    C --&gt;|Two| E[iPhone]<br>    C --&gt;|Three| F[fa:fa-car Car]</pre><p>This code would then be compiled into the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQ872Ot7_0tCs5ma3YS8uw.png" /></figure><h3>Why Should You Codify Your Architecture Diagrams?</h3><ol><li><strong>Easy Access and Modifications: </strong>Static diagrams in formats like PNG or JPG can be hard to modify without the original files from tools like Draw.io or Lucidchart. Codifying diagrams allows teams to store them in version control systems like GitHub, making them accessible and editable by anyone.</li><li><strong>Version History and Evolution: </strong>Storing diagrams as code enables version history tracking, allowing you to see changes over time and easily revert to previous versions if needed.</li><li><strong>Improved Visual Consistency: </strong>Code-based diagrams use libraries or tools to automatically arrange components, eliminating manual effort and ensuring professional, clean layouts.</li><li><strong>Assistance with Generative AI: </strong>Codified diagrams can be leveraged by AI tools to build services, provide recommendations, or optimise designs — far more effectively than static images.</li><li><strong>Simpler and Faster Updates: </strong>Making updates is as simple as editing code, saving significant time compared to manually adjusting components, especially for large-scale changes.</li></ol><h3>Creating an Architecture Diagram Using Python Diagrams</h3><p><a href="https://diagrams.mingrammer.com/">Python Diagrams</a> is a powerful library for programmatically creating architecture diagrams. It’s especially useful for serverless architectures, where the components and their interactions can be complex.</p><p>Here’s how you can create a simple serverless architecture diagram using Python Diagrams:</p><h4><strong>1. Install the Diagrams Library</strong></h4><p>Ensure you have Python installed, then install the Diagrams library using pip:</p><pre>pip install diagrams</pre><h4><strong>2. Write Your Serverless Architecture Diagram</strong></h4><p>Below is an example of a basic AWS serverless architecture diagram, illustrating an API Gateway connected to a Lambda function and a DynamoDB table:</p><pre>from diagrams import Diagram<br>from diagrams.aws.compute import Lambda<br>from diagrams.aws.database import Dynamodb<br>from diagrams.aws.network import APIGateway<br><br>with Diagram(&quot;Serverless Architecture&quot;, show=True):<br>    APIGateway(&quot;API Gateway&quot;) &gt;&gt; Lambda(&quot;Lambda Function&quot;) &gt;&gt; Dynamodb(&quot;DynamoDB Table&quot;)</pre><p>Compiling the code will result in the following architecture diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*4G-7icOVuzvGmtI0VpF5Cw.png" /></figure><h3>Conclusion</h3><p>Codifying architecture diagrams offers a more efficient, collaborative, and scalable approach to system design. Unlike static tools, diagrams as code are easy to version control, update, and integrate with modern workflows, including AI-powered tools.</p><p>By adopting this practice, you can create accurate, dynamic diagrams that evolve alongside your systems, making them invaluable assets for your team. Start codifying your architecture diagrams today to unlock these benefits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b517f0ad30b" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/codify-your-aws-architecture-diagrams-today-6b517f0ad30b">Codify Your AWS Architecture Diagrams Today</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Amazon Q Save You 4,500 Developer-Years of Work?]]></title>
            <link>https://levelup.gitconnected.com/can-amazon-q-save-you-4-500-developer-years-of-work-5569e15dc17d?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5569e15dc17d</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 23:28:33 GMT</pubDate>
            <atom:updated>2024-11-24T23:28:33.387Z</atom:updated>
            <content:encoded><![CDATA[<h4>GENERATIVE AI</h4><h4><strong>Evaluating the Effectiveness of Amazon Q by Asking it to Develop a Simple Serverless E-Commerce Application</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlEN55exAl8XcNlzstpzfQ.png" /></figure><h3>Introduction</h3><p>Generative AI applications are becoming increasingly popular in software development. Recent advancements in AI tools like ChatGPT, Claude 3.5 Sonnet, and the VSCode fork <a href="https://www.cursor.com/">Cursor</a>, have made it easier than ever to integrate AI into your development workflow, dramatically boosting productivity.</p><p>Amazon has entered this space with <a href="https://aws.amazon.com/q/">Amazon Q</a>, an AI assistant specifically designed to enhance the software development processes. According to <a href="https://x.com/ajassy/status/1826608791741493281">Amazon’s CEO</a>, the company saved 4,500 developer-years of work during a Java upgrade project using Amazon Q. Yes, you read that right — 4,500 years.</p><p>In this article, we’ll put Amazon Q to the test by asking it to develop a simple serverless e-commerce application.</p><h3>What Can Amazon Q Actually Do?</h3><p>The best way to work with Amazon Q is by integrating it with VSCode via an extension. Once installed, Amazon Q offers features similar to Cursor but with some additional capabilities that make it stand out. Here’s what Amazon Q can do:</p><ul><li><strong>Answer questions about AWS services:</strong> Quickly resolve doubts or learn about various AWS offerings without leaving your IDE.</li><li><strong>Explain what your code does:</strong> Gain a deeper understanding of your codebase with clear explanations.</li><li><strong>Generate code for you:</strong> Create boilerplate or even complex functionality with AI-generated snippets.</li><li><strong>Debug and fix code:</strong> Spot issues in your code and fix them effortlessly.</li><li><strong>Write tests for your code:</strong> Generate unit tests to ensure your code functions as intended.</li><li><strong>Refactor your code:</strong> Improve your code’s structure and readability with AI-powered suggestions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q99757LXrwY7dgKYrufpYw.png" /></figure><p>The VSCode extension includes a dedicated chat window that provides interactive suggestions for improving or modifying your code.</p><h3>Generating a simple Serverless Application with Amazon Q</h3><p>To see the effectiveness of Amazon Q in real-world software development, we will task the assistant with creating a serverless e-commerce application — entirely without manual coding involvement.</p><h4>Preface</h4><p>We have been approached by a client to create a simple API that can save and retrieve items for an e-commerce application. The application must have a minimal total cost of ownership, as it will be managed by a small development team with limited AWS expertise. The application should be built according to the Well-Architected Framework. The team has TypeScript knowledge.</p><blockquote><strong>Tip:</strong> Want to follow along? Install the <a href="https://marketplace.visualstudio.com/items?itemName=AmazonWebServices.amazon-q-vscode">Amazon Q extension</a> for Visual Studio Code to try out its features and replicate the steps in this article.</blockquote><h4>Initialising the App</h4><p>To ensure the application remains maintainable for the team, we want to generate infrastructure as code (IaC) that can be easily modified in the future. We asked Amazon Q for its recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMJcNfVpWv3aUYg5683Gnw.png" /></figure><p>Amazon Q suggested using the AWS Cloud Development Kit (CDK) — AWS’s open-source IaC framework. CDK is a solid choice for our client’s requirements, as it aligns with their TypeScript expertise and offers a high degree of flexibility.</p><p>Next, we asked Amazon Q how to get started with CDK. It provided clear and actionable steps:</p><pre>npm install -g aws-cdk<br>mkdir my-cdk-app<br>cd my-cdk-app<br>cdk init app - language typescript<br>cdk bootstrap</pre><blockquote><strong>Tip:</strong> If you want to run the cdk bootstrap and cdk deploy commands, ensure that your <a href="https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-configure.html">AWS credentials are configured</a> to deploy resources to your account.</blockquote><h4>Creating the Service</h4><p>With our template CDK project set up, it’s time to generate the service. In the initial discussion with Amazon Q, it recommended using a combination of API Gateway, Lambda, and DynamoDB — a widely-used pattern for building serverless applications.</p><p>We asked Amazon Q to generate the CDK code for these services.</p><blockquote><strong>Tip:</strong> Use the /dev command in the Amazon Q chat window to quickly generate code for your services.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUGmrjsOL3x4SJ-aJoKy2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*GPJDrskhCtyIJ-0hAQtzpw.png" /></figure><p>Amazon Q provided a step-by-step summary of the changes it suggests you should make to your codebase. After a few minutes, it generated detailed code suggestions, which I reviewed and accepted.</p><p>You can access the full generated code on GithHub <a href="https://github.com/thornejosh/amazon-q-e-commerce-backend">here</a>. Below is the content of the my-cdk-app-stack.ts file that was generated:</p><pre>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as apigateway from &#39;aws-cdk-lib/aws-apigateway&#39;;<br>import * as lambda from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import * as dynamodb from &#39;aws-cdk-lib/aws-dynamodb&#39;;<br>import * as nodejsLambda from &#39;aws-cdk-lib/aws-lambda-nodejs&#39;;<br><br>export class MyCdkAppStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br>    super(scope, id, props);<br><br>    // DynamoDB table<br>    const table = new dynamodb.Table(this, &#39;ItemsTable&#39;, {<br>      partitionKey: { name: &#39;id&#39;, type: dynamodb.AttributeType.STRING },<br>      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,<br>    });<br><br>    // Lambda function<br>    const itemsFunction = new nodejsLambda.NodejsFunction(this, &#39;ItemsHandler&#39;, {<br>      entry: &#39;lambda/items.ts&#39;,<br>      handler: &#39;handler&#39;,<br>      environment: {<br>        TABLE_NAME: table.tableName,<br>      },<br>    });<br><br>    // Grant the Lambda function read/write permissions to the DynamoDB table<br>    table.grantReadWriteData(itemsFunction);<br><br>    // API Gateway<br>    const api = new apigateway.RestApi(this, &#39;ItemsApi&#39;, {<br>      restApiName: &#39;Items Service&#39;,<br>    });<br><br>    const items = api.root.addResource(&#39;items&#39;);<br>    const getAllIntegration = new apigateway.LambdaIntegration(itemsFunction);<br>    items.addMethod(&#39;GET&#39;, getAllIntegration);<br>    items.addMethod(&#39;POST&#39;, getAllIntegration);<br><br>    const singleItem = items.addResource(&#39;{id}&#39;);<br>    const getSingleIntegration = new apigateway.LambdaIntegration(itemsFunction);<br>    singleItem.addMethod(&#39;GET&#39;, getSingleIntegration);<br>    singleItem.addMethod(&#39;PUT&#39;, getSingleIntegration);<br>    singleItem.addMethod(&#39;DELETE&#39;, getSingleIntegration);<br>  }<br>}</pre><p>I then installed the necessary packages that Amazon Q used in the Lambda handler:</p><pre>npm install aws-lambda aws-sdk @types/aws-lambda --save-dev</pre><h4>Deploying and Testing the Service</h4><p>Next, I attempted to deploy the generated setup to my AWS account using the cdk deploy command to see if it would work on the first try. The deployment failed with the following error:</p><pre>ERROR: Cannot connect to the Docker daemon at unix:///Users/joshthorne/.docker/run/docker.sock. <br>Is the docker daemon running?</pre><p>To troubleshoot, I turned to Amazon Q for assistance. It quickly analysed the error and provided the following response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2JES-4BRJ2zvVD-hTKh9w.png" /></figure><p>I followed Amazon Q’s advice and started <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> on my machine. After that, I reran the cdk deploy command. This time, the deployment succeeded, and the console output provided me with the endpoint of my service.</p><p>To verify that the deployed service was functioning correctly, I conducted the following tests:</p><ul><li>Adding an item to the database using PUT \items\{id}</li><li>Fetching an item from the backend using GET \items\{id}</li><li>Fetching multiple items with GET \items</li><li>Deleting an item with DELETE \items\{id}</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4y3poMkMUxWbyjHHk_gpw.png" /></figure><p>All the tests succeeded, demonstrating that Amazon Q had successfully generated the complete service on the first attempt.</p><h4>Creating Unit Tests</h4><p>With the application code successfully generated and validated, it was time to test another feature of Amazon Q — generating unit and integration tests for the application.</p><p>I asked Amazon Q to write both unit and integration tests for my code, providing it with the API Gateway endpoint. Amazon Q generated the test code, and I installed the axios, which it used in the integration tests to make API calls to my service.</p><p>I then tried to run the tests however they failed due to some typing issues. I asked Amazon Q to fix the issues however after a few iterations it seemed incapable of solving the problem, notably having issues with mocking out various services.</p><p>When I attempted to run the tests, they failed due to typing issues related to mocking the services. I turned to Amazon Q for assistance in resolving these errors, but despite several iterations, it was unable to fully resolve the problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoMxZaWVkd-cbIHgH9ny0Q.png" /></figure><h3>Analysis</h3><p>While using Amazon Q, I had successfully turned client requirements into a solution that solves the problem.</p><ul><li><strong>Architectural Decision: </strong>The architecture that Amazon Q wanted to use was a perfect choice for the clients needs and followed the Well-Architectured Framework.</li><li><strong>Generating Code:</strong> Amazon Q successfully generated the service on the first try. Additionally, it generated multiple files in one go — a capability I’ve found challenging with Cursor in the past.</li><li><strong>Testing:</strong> Amazon Q generated some tests successfully, but it struggled with mocking imports, leading to typing issues in most cases.</li><li><strong>Debugging:</strong> The assistant effectively resolved my Docker issue on the first try. However, unlike Cursor, it lacks the ability to click on errors in the terminal or code editor for additional context, requiring you to manually paste error details into the chat window.</li><li><strong>Time : </strong>Amazon Q took significantly longer to respond to prompts than other assistants I’ve used — some responses left me waiting several minutes.</li><li><strong>Barrier to entry</strong>: It seemed like there was little thought to how users gained accessed to Amazon Q. The free tier requires an Amazon Builders account, while the paid developer tier needs an AWS account. The Builders login is confusing, and setting up an AWS account for advanced features seems excessive for developers not already using AWS.</li></ul><h3>So Should I Use Amazon Q?</h3><p>Currently I use Amazon Q every day — it is extremely effective at generating code for AWS applications over it’s competitors. I typically use it to generate the initial code for my projects and any major changes to my existing projects. Anything outside this scope and you are better off using another model as the response time to prompts is particularly long.</p><p>If you’ve had a different experience with Amazon Q or used features I didn’t cover, feel free to share your thoughts in the comments. I’d be happy to revisit and explore them!</p><p>In case you missed it the GitHub code is located <a href="https://github.com/thornejosh/amazon-q-e-commerce-backend">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5569e15dc17d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/can-amazon-q-save-you-4-500-developer-years-of-work-5569e15dc17d">Can Amazon Q Save You 4,500 Developer-Years of Work?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Amazon CloudFront Configurations You Should Set]]></title>
            <link>https://levelup.gitconnected.com/6-amazon-cloudfront-configurations-you-should-set-851684e79c2f?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/851684e79c2f</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 22:17:39 GMT</pubDate>
            <atom:updated>2024-10-29T22:17:39.386Z</atom:updated>
            <content:encoded><![CDATA[<h4>Essential Settings for Optimising your Amazon CloudFront Distribution</h4><h3>Introduction</h3><p>Amazon CloudFront is AWS’s content delivery network (CDN) offering, designed to deliver content with low latency and robust security through a global network of <a href="https://aws.amazon.com/cloudfront/features/">edge locations</a>. By caching content at the edge, CloudFront reduces data transfer costs and enhances speed, making it ideal for global content delivery. As a serverless service integrated with AWS, it requires minimal management, but optimising its configurations is essential. This article covers key settings to help you get the most out of CloudFront in terms of performance, security, and cost.</p><h3>1. Assign a Custom Domain Name</h3><p>CloudFront serves as the entry point for your content or APIs, and by default, AWS provides a CloudFront URL for accessing your distribution. However, this URL consists of random characters, making it less user-friendly. Assigning a custom domain name and SSL/TLS certificate improves accessibility to your service.</p><blockquote><strong>Tip:</strong> Use <a href="https://aws.amazon.com/route53/">Amazon Route 53</a> to easily provision a custom domain name, and <a href="https://aws.amazon.com/certificate-manager/">AWS Certificate Manager (ACM)</a> to create and manage SSL/TLS certificates.</blockquote><h3>2. Configure Caching</h3><p>Caching is a core feature in CloudFront, allowing content to be stored at edge locations (data centers strategically placed closer to your users). By caching responses at the edge, CloudFront reduces the need to retrieve data from the origin server (your application), resulting in faster response times and reduced load on your backend.</p><p>To optimise caching, you’ll need to configure a <strong>cache policy</strong> within your CloudFront distribution, specifying details like:</p><ul><li><strong>Cache Key</strong>: A cache key uniquely identifies objects in your cache. Customise it with HTTP headers, cookies, or query strings to ensure CloudFront correctly distinguishes between different types of content. For example, you might include specific query strings if you want dynamic content variations based on user input.</li><li><strong>Time to Live (TTL)</strong>: TTL determines how long CloudFront stores an object in the cache before expiring it. Set an appropriate TTL to balance fresh content delivery with performance; a longer TTL is beneficial for static content, while a shorter TTL might suit rapidly changing data.</li></ul><blockquote><em>Before you go any further, if you are finding this article useful, please clap and </em><a href="https://medium.com/@joshua_thorne"><em>follow</em></a><em> today! 👏</em></blockquote><h3>3. Georestriction and Price Classes</h3><p>CloudFront offers options to control where your content is delivered, helping you balance performance with cost:</p><ul><li><strong>Georestriction</strong>: Control content access based on specific countries. You can create an allow list to permit access only for selected countries (e.g., United States) or use a deny list to block access in restricted regions. This feature helps meet regulatory requirements and manage content rights in specific areas.</li><li><strong>Price Classes</strong>: Define the geographic distribution of edge locations to manage costs and performance. Lower price classes limit edge locations, reducing costs but potentially increasing latency for users farther from these locations. Higher price classes increase the number of edge locations globally, minimising latency but potentially raising costs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rtlw3jiVZGYrIY2dC8o5Tg.png" /><figcaption><a href="https://aws.amazon.com/cloudfront/pricing/">https://aws.amazon.com/cloudfront/pricing/</a></figcaption></figure><p>These features can be useful if you need to control content distribution based on copyright laws, licensing agreements, or regulatory requirements.</p><h3>4. Logging and Monitoring</h3><p>Effective logging and monitoring are essential for troubleshooting errors and understanding usage patterns within your CloudFront distribution. CloudFront offers two primary options to provide this visibility:</p><ul><li><strong>S3 Logging</strong>: Configure CloudFront to store detailed logs of each user request in an Amazon S3 bucket. These logs provide insights into traffic patterns, help identify performance bottlenecks, and enable tracing of specific requests for efficient issue diagnosis.</li><li><strong>CloudWatch Metrics</strong>: Enable CloudWatch metrics for real-time insights into your distribution’s traffic and performance. You can easily create dashboards to monitor total requests, error rates, and more. <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/viewing-cloudfront-metrics.html#monitoring-console.distributions">Learn more about CloudFront metrics here</a>.</li></ul><p>With S3 logging and CloudWatch metrics, you gain comprehensive monitoring, empowering you to optimise your CloudFront distribution for improved performance and user experience.</p><h3>5. Origin Configuration</h3><p>In CloudFront, the origin is the source of the content that CloudFront delivers to users. This could be an Amazon S3 bucket, an HTTP server, an AWS Elastic Load Balancer, or another AWS service like Amazon EC2. Properly configuring the origin is essential for optimising performance, reliability, and security.</p><ul><li><strong>Headers, Cookies, and Query Strings</strong>: Control which headers, cookies, and query strings CloudFront forwards to the origin. This allows you to maximise caching efficiency and reduce unnecessary traffic to your origin, lowering latency and costs.</li><li><strong>Origin Failover</strong>: Set up a secondary origin, such as another server or an Amazon S3 bucket, to act as a failover if the primary origin becomes unavailable.</li><li><strong>Origin Protocol Policy</strong>: Configure the protocol policy to HTTPS-only to enforce secure connections between CloudFront and the origin.</li></ul><h3>6. Lambda@Edge and CloudFront Functions</h3><p>CloudFront offers edge customisation with Lambda@Edge and CloudFront Functions, enabling code execution closer to users for improved performance and personalisation.</p><ul><li><strong>Lambda@Edge</strong>: Run Node.js or Python code at edge locations for advanced tasks, such as personalised content and custom authentication. Triggered by key events like viewer requests (user requests to CloudFront) and origin requests (CloudFront fetching from the origin), Lambda@Edge allows for deeper customisation, including request modifications before reaching the cache or origin server. Ideal for complex logic but may incur additional costs.</li><li><strong>CloudFront Functions</strong>: Execute lightweight JavaScript code for high-frequency, simple tasks like modifying HTTP headers or URL rewriting. Limited to viewer request and viewer response events, CloudFront Functions offer low-latency and cost-effective customisation for straightforward operations.</li></ul><h3>Conclusion</h3><p>Amazon CloudFront provides a comprehensive set of configurations to enhance content delivery, security, and cost management. By leveraging CloudFront’s powerful caching, geographical controls, monitoring, and customisable settings, you can create a highly efficient, secure, and globally accessible distribution. These optimisations make CloudFront an invaluable tool for delivering reliable and performant content, helping you meet the demands of a global audience with ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jbz9ZJuWyNgsOG5P" /><figcaption>Photo by <a href="https://unsplash.com/@dianamia?utm_source=medium&amp;utm_medium=referral">C Dustin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=851684e79c2f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/6-amazon-cloudfront-configurations-you-should-set-851684e79c2f">6 Amazon CloudFront Configurations You Should Set</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Serverless Full Stack Web Application in 5 Minutes]]></title>
            <link>https://levelup.gitconnected.com/creating-a-serverless-full-stack-web-application-in-5-minutes-00ae5a937370?source=rss-9172c40b72f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/00ae5a937370</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sst]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Josh Thorne]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 00:58:36 GMT</pubDate>
            <atom:updated>2024-10-28T00:58:36.112Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using SST to Create a Hello World Full Stack Web Application</h4><h3>Introduction</h3><p>SST (Serverless Stack) has quickly become one of my favourite frameworks for building serverless applications on AWS. What sets SST apart is its developer-friendly infrastructure-as-code (IaC) components, which can be written in the same language as your application logic — whether that’s TypeScript, Python, Go, or others. Unlike many frameworks that rely on CloudFormation, SST utilises Terraform and Pulumi under the hood, offering a different approach to infrastructure management (Read more <a href="https://sst.dev/blog/moving-away-from-cdk">here</a>).</p><p>The best thing about SST is how seamlessly it integrates with various services, making it easy to build full-stack web applications. In this article, I’ll guide you through the process of building a full-stack web application using SST.</p><blockquote><strong>Tip:</strong> The SST documentation can be challenging to navigate, as multiple versions of SST exist under different domain names. For the purposes of this article, we will be using the latest version of SST, which you can learn more about here: <a href="https://sst.dev/docs">https://sst.dev/docs</a>.</blockquote><h3>Getting Started</h3><h4>Prerequisites</h4><ul><li>An <a href="https://aws.amazon.com/resources/create-account/">AWS account</a>.</li><li><a href="https://nodejs.org/">Node.js installed</a>.</li></ul><h3>Setting up the Codebase</h3><p>To get started with the service, we will begin by creating a Next.js application. Run the following commands to create your Next.js app (pick all the default options):</p><pre>npx create-next-app@latest aws-nextjs<br>cd aws-nextjs</pre><p>Next, we’ll add SST to the project:</p><pre>npx sst@latest init</pre><p>At this point, you should see some pre-generated code for your application.</p><h4>What Your Folder Structure Should Look Like</h4><p>In the /app folder, you will find the frontend code. If you’re familiar with developing Next.js applications, this should feel familiar. Feel free to modify the code as needed.</p><p>You can now run npm run dev and navigate to <a href="http://localhost:3000/">http://localhost:3000/</a> in your browser to see the Next.js application in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyKAo2Tft4x7xxbxLzgx4g.png" /></figure><p>However, the main code we are interested in is the SST config file (sst.config.ts):</p><pre>export default $config({<br>  app(input) {<br>    return {<br>      name: &quot;aws-nextjs&quot;,<br>      removal: input?.stage === &quot;production&quot; ? &quot;retain&quot; : &quot;remove&quot;,<br>      home: &quot;aws&quot;,<br>    };<br>  },<br>  // <br>  async run() {<br>    new sst.aws.Nextjs(&quot;MyWeb&quot;);<br>  },<br>});</pre><p>This code defines what resources we are going to deploy to AWS:</p><ul><li>app(input) : This function defines the configuration of the app.</li><li>removal: input?.stage === &quot;production&quot; ? &quot;retain&quot; : &quot;remove&quot; : This ensures that in production resources are retained during teardown to avoid disrupting live users. In non-production stages, resources will be automatically removed on teardown.</li><li>async run() : This function defines the resources we want to deploy.</li><li>new sst.aws.Nextjs(&quot;MyWeb&quot;); : This deploys a Next.js application. SST can automatically detect our frontend code and will upload it to AWS.</li></ul><h3>Deploying the Application</h3><p>We can see our web application running locally, but now we have the SST code to host it on AWS. The next step is to configure your AWS credentials and deploy the application to AWS.</p><p>First, you’ll need to configure your AWS credentials before deploying your application. You can follow the steps in the <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html">AWS documentation on setting up credentials</a>.</p><p>Once your credentials are set, you can deploy the application by running:</p><pre>npx sst deploy</pre><blockquote><strong>Tip:</strong> You can also use the sst remove command to delete your stack and all the resources deployed to AWS.</blockquote><p>Once the deployment is complete, you should see a confirmation message indicating that your application has been deployed, along with an output containing the site URL. Copy this MyWeb URL and paste it into your browser, and you should see the same application that you ran locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLGeurOpraExDqFqQGmZ6w.png" /></figure><p>Your Next.js application is now hosted on AWS. While most infrastructure-as-code (IaC) frameworks, such as AWS SAM or CDK, rely on CloudFormation to deploy services, SST utilises Terraform and Pulimi. This means it bypasses CloudFormation and instead makes direct API calls to AWS to provision your resources.</p><p>You can inspect your deployed resources by navigating through the AWS Management Console, for example, by going to the S3 dashboard to see the bucket hosting your site.</p><blockquote>Before you go any further, if you are finding this article useful, please clap and <a href="https://medium.com/@joshua_thorne">follow</a> today! 👏</blockquote><h3>Adding an API</h3><p>While having a static website is great, you might want to extend your application by adding an API so the frontend can interact with backend data and perform computations. Here’s how you can set up a simple API in SST.</p><h4>Step 1: Create a Lambda Function</h4><p>Start by creating a function.ts file in the root of your project. This file will contain the logic for a simple &quot;Hello World&quot; Lambda function:</p><pre>export const handler = async () =&gt; {<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      message: &quot;Hello, World!&quot;,<br>    }),<br>  };<br>};</pre><p>This Lambda function simply returns a JSON response with a “Hello, World!” message.</p><h4>Step 2: Add the API to the SST Configuration</h4><p>Now, we’ll add the API to the run() method in your SST configuration file (sst.config.ts). This will link our Lambda function to an API Gateway.</p><p>Update the run() method as follows:</p><pre>async run() {<br>    new sst.aws.Nextjs(&quot;MyWeb&quot;);<br><br>    const api = new sst.aws.ApiGatewayV2(&quot;Api&quot;);<br>    api.route(&quot;GET /&quot;, {<br>      handler: &quot;function.handler&quot;,<br>    });<br>  }</pre><p>In this code, we:</p><ul><li>Create an API Gateway using the sst.aws.ApiGatewayV2 construct.</li><li>Define a route (GET /) that triggers the handler function from the function.ts file.</li></ul><h4>Step 3: Testing Locally with SST’s Local Environment</h4><p>Before deploying the function to AWS, SST provides a powerful local environment to help you test AWS resources quickly and efficiently. This helps shorten the feedback loop and accelerates development.</p><p>To test locally, run the following command:</p><pre>npx sst dev</pre><p>This will deploy your application in a local simulation. Once the local deployment is complete, SST will provide an API endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWt5pDybOKzpAY0EUgBmYg.png" /></figure><h4>Step 4: Testing the API</h4><p>Copy the generated API endpoint and paste it into your browser, or use a tool like Postman to make a GET request. You should see the &quot;Hello, World!&quot; message in the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-aJsi4hUarEPUP7B6hvnw.png" /></figure><h4>Step 5: Make Changes and See Immediate Feedback</h4><p>To see the speed of the local development feedback loop, update the return statement in function.ts, for example:</p><pre>export const handler = async () =&gt; {<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      message: &quot;Hello, SST!&quot;,<br>    }),<br>  };<br>};</pre><p>Save the file, and re-run the GET request to the API endpoint. You should immediately see the updated response. This demonstrates how efficiently you can iterate on your API without needing to fully redeploy to AWS each time.</p><h4>Step 6: Integrating with the Frontend</h4><p>You can also connect this API with your locally running Next.js application, creating a full end-to-end local setup. This allows you to test the integration between your frontend and backend in real time before deploying to AWS.</p><h4>Step 7: Deploying the API to AWS</h4><p>Once you’re happy with your API and ready to deploy it to AWS, simply run:</p><pre>npx sst deploy</pre><p>SST will provision the necessary AWS resources, such as Lambda, API Gateway, and any other services defined in your configuration. After the deployment is complete, SST will output the URL for your live API endpoint.</p><p>Copy the live API URL and test it in your browser or Postman, just as you did locally. You should now see the same response, but this time your API is hosted in the cloud.</p><h3>Next Steps</h3><p>Congratulations! You’ve successfully built and deployed a full-stack serverless application using SST. Now that your application is live, here are some next steps to enhance and expand it:</p><ol><li><strong>Custom Domain and SSL</strong>: Add a custom domain to your application using AWS Route 53 for domain management and AWS Certificate Manager (ACM) for SSL certificates. This will ensure your site is accessible over HTTPS.</li><li><strong>Authentication and Authorisation</strong>: Implement user authentication with Amazon Cognito to secure your API and protect sensitive data. SST integrates seamlessly with AWS services, making it easy to add authentication to your app.</li><li><strong>Database Integration</strong>: Extend your application by integrating a database such as AWS DynamoDB or Amazon RDS. SST makes it simple to provision these resources and connect them to your Lambda functions for dynamic, data-driven apps.</li><li><strong>Monitoring and Logging</strong>: Set up monitoring and logging for your application using AWS CloudWatch and X-Ray. These tools will help you track performance, troubleshoot issues, and keep an eye on your application’s health.</li></ol><p>By following these steps, you can continue refining your serverless application and prepare it for production-level use. Explore the <a href="https://sst.dev/docs">SST documentation</a> for more advanced features and use cases.</p><h3>Conclusion</h3><p>In this article, we explored how SST simplifies building and deploying full-stack serverless applications on AWS, using Next.js for the frontend and a Lambda-powered API for the backend. With its developer-friendly local environment and seamless integration with AWS through Terraform, SST makes it easy to manage both infrastructure and code. Now that your application is live, you can continue enhancing it, confident in SST’s ability to streamline both development and deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbBzDmBDhDGdrlkO2gWKsA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00ae5a937370" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-a-serverless-full-stack-web-application-in-5-minutes-00ae5a937370">Creating a Serverless Full Stack Web Application in 5 Minutes</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>