<?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 Andrii Lobanov on Medium]]></title>
        <description><![CDATA[Stories by Andrii Lobanov on Medium]]></description>
        <link>https://medium.com/@aperteda?source=rss-ef7e25d2cc7a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z583xQhEEPuxUaFkacXOjg.jpeg</url>
            <title>Stories by Andrii Lobanov on Medium</title>
            <link>https://medium.com/@aperteda?source=rss-ef7e25d2cc7a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:51:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aperteda/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[A Practical Guide to Migrating Your MCP-Powered, Response-Streaming Gen-AI App to AWS]]></title>
            <link>https://medium.com/@aperteda/a-practical-guide-to-migrating-your-mcp-powered-response-streaming-gen-ai-app-to-aws-4c198bb4f0cc?source=rss-ef7e25d2cc7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c198bb4f0cc</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <dc:creator><![CDATA[Andrii Lobanov]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 16:02:23 GMT</pubDate>
            <atom:updated>2026-01-10T16:02:23.492Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary</h3><p>The <strong>Model Context Protocol (MCP)</strong> is rapidly gaining popularity, driven by the exponential growth of Generative AI. While a local setup may seem straightforward, deploying the solution can present numerous unexpected challenges. This article aims to share knowledge and insights on the possible implementation of the MCP</p><h3>What we are going to build</h3><p>This article aims to describe how to create a host serverless client connected to two MCP servers, all on AWS. Each MCP server provides one tool. One tool will detect a user’s location, and another tool will detect the weather in a specified location. But, before we begin, we’ll need some theory.</p><h3>Before we start</h3><p>To understand MCP, we first need to cover two foundational concepts. While modern agents often abstract away the details of <strong>function calling</strong>, it’s crucial to understand the mechanics because MCP is built on remote function calling (via stdio or HTTP). Additionally, we will look at how <strong>model response streaming</strong> works to provide context for our example.Model Response streaming</p><p><strong>Normal Invocation</strong> This method is trivial to implement but often inefficient for user experience. In a normal invocation, the server <strong>buffers</strong> the entire generation process. You send a request, and the system holds the connection open until the model hits a “stop token.” Only then does it return the full response as a single JSON payload.</p><p><strong>Streaming invocation</strong> — in case of streaming, instead of waiting for the full response, the model respond chunk by chunk. Generally, it’s more natural to the model, as, in it’s core, it’s purpose to predict the next token. After next token is predicted, model reinvoking itself with previsouly predicted token and make another prediction. In a streaming invocation, we are shipping each preditcion from a model to user, once availabe. So, in consuquence, user might predictions right away. However, the amount of time to make a full prediction will be more/less the same, as normal invocation. This happens, because, in essence, the model operates on streams. The normal invocation is just a way to ship the info to you in a c comfortable format. While this approach provides a clean, easy-to-parse format for your code, it is not alwayg good forreal-time systems. It forces the user to wait for the entire generation cycle (can take 9–30 sec) depending on complexity, before they see a response. In technical terms, time, until you’ll see first results called <strong>Time to First Token (TTFT)</strong></p><p><strong>Streaming Invocation</strong> is far more efficient for user perception. Instead of buffering the full response, model pushes data chunk-by-chunk. This approach is more natural for LLMs and aligns with their <strong>autoregressive</strong> nature. At its core, a model’s purpose is to predict the next token, append it to the context, and re-invoke itself to predict the subsequent one. Streaming simply exposes this internal loop to the user, shipping each prediction the moment it is available. Streaming drastically reduces <strong>Time to First Token (TTFT)</strong>, allowing users to read the content as it is being generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*UJTBimS_q40BwAraAM-qUQ.png" /><figcaption>Graphically comparison (Normal invocation VS streaming)</figcaption></figure><h3>Function calling</h3><p>To understand how function calling works, let’s start with a practical challenge. Imagine asking a Large Language Model (LLM): <strong>“What is the weather like at my location?”</strong></p><p>By default, the model lacks real-time access to your GPS coordinates or live meteorological data. To bridge this gap, we must provide it with specific “capabilities” in the form of functions:</p><ol><li>get_location_by_ip: Resolves the user&#39;s IP address into geographic coordinates.</li><li>get_weather: Fetches real-time atmospheric data for a specific coordinate.</li></ol><p>The model’s task is to act as an <strong>orchestrator</strong>, identifying that it cannot answer the question directly and instead determining the correct sequence of tools to execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*u6FDTYQhvtgyPPxAD5daPg.png" /></figure><p>The diagram above illustrates the multi-turn logic required for this scenario:</p><ul><li><strong>Step 1:</strong> The model analyzes the prompt and realizes it needs a location first.</li><li><strong>Step 2:</strong> It calls get_location_by_ip and receives the latitude/longitude.</li><li><strong>Step 3:</strong> It uses that output to trigger get_weather</li><li><strong>Step 4:</strong> It synthesizes the final data into a natural language response for the user.</li></ul><p>Let’s dive a little deeper on how this work</p><p>First, you must provide the model with a tools array. This informs the model of the functions available to it and their expected parameters. Invoke the model using converse_stream. You pass the system prompt, the message history, and your tool configuration.</p><pre>tool_definitions = [<br>  {<br>    &quot;toolSpec&quot;: {<br>      &quot;name&quot;: &quot;get_location_by_ip&quot;,<br>      &quot;description&quot;: &quot;Detects user location by user&#39;s ip adress&quot;,<br>      &quot;inputSchema&quot;: {<br>        &quot;json&quot;: {<br>          &quot;properties&quot;: {<br>            &quot;ip_adress&quot;: {<br>              &quot;type&quot;: &quot;string&quot;<br>            }<br>          },<br>          &quot;required&quot;: [<br>            &quot;ip_adress&quot;<br>          ],<br>          &quot;type&quot;: &quot;object&quot;<br>        }<br>      }<br>    }<br>  },<br>  {<br>    &quot;toolSpec&quot;: {<br>      &quot;name&quot;: &quot;get_weather&quot;,<br>      &quot;description&quot;: &quot;Detects weather by specified location, coordinates\\n\\nArgs:\\n    @param location (str): Location in format \&quot;latitude,longitude\&quot; (e.g. \&quot;50.4501,30.5234\&quot;)&quot;,<br>      &quot;inputSchema&quot;: {<br>        &quot;json&quot;: {<br>          &quot;properties&quot;: {<br>            &quot;location&quot;: {<br>              &quot;type&quot;: &quot;string&quot;<br>            }<br>          },<br>          &quot;required&quot;: [<br>            &quot;location&quot;<br>          ],<br>          &quot;type&quot;: &quot;object&quot;<br>        }<br>      }<br>    }<br>  }<br>]<br><br>response_stream = bedrock_runtime.converse_stream(<br>                modelId=model_id,<br>                system=[{<br>                    &#39;text&#39;: f&quot;&quot;&quot;Curent user&#39;s ip is {client_host}.&quot;&quot;&quot;,<br>                }],<br>                messages=messages,<br>                toolConfig={<br>                    &#39;tools&#39;: converted_tools<br>                }<br>            )</pre><p>When using stream invocation, the response arrives in chunks. You must aggregate these chunks to reconstruct the full tool call.</p><p><strong>contentBlockStart</strong>: Identifies that the model intends to use a tool and provides a toolUseId</p><pre>{<br>  &#39;contentBlockStart&#39;: {<br>    &#39;start&#39;: {<br>      &#39;toolUse&#39;: {<br>        &#39;toolUseId&#39;: &quot;tooluse_20Z9zl0BQWSXjFuLKdTJcA&quot;,<br>        &#39;name&#39;: &#39;get_location_by_ip&#39;<br>      }<br>    },<br>    &#39;contentBlockIndex&#39;: 1<br>  }<br>}</pre><p><strong>contentBlockDelta</strong>: Contains the incremental JSON string for the tool arguments. There will normally be multiple deltas</p><pre>{<br>  &quot;contentBlockDelta&quot;: {<br>    &quot;delta&quot;: {<br>      &quot;toolUse&quot;: {<br>        &quot;input&quot;: &quot;{\&quot;ip_adress\&quot;:\&quot;203.13.121.5\&quot;}&quot;<br>      }<br>    },<br>    &quot;contentBlockIndex&quot;: 1<br>  }<br>}</pre><p><strong>contentBlockStop</strong> Signals the end of that specific content block.</p><pre>{<br>  &quot;contentBlockStop&quot;: {<br>    &quot;contentBlockIndex&quot;: 1<br>  }<br>}</pre><p><strong>messageStop</strong>: If the stopReason is tool_use, the model is waiting for you to run the function and then to re-invoke the model.</p><pre>{&quot;messageStop&quot;: {&quot;stopReason&quot;: &quot;tool_use&quot;}}</pre><p>Now, from all those chunks, you’ll need to construct the toolUse call. This is needed for model to know, that the tool is actually being called</p><pre>{<br>   &quot;toolUse&quot;: <br>    {<br>        &quot;toolUseId&quot;: &quot;tooluse_20Z9zl0BQWSXjFuLKdTJcA&quot;, <br>        &quot;name&quot;: &quot;get_location_by_ip&quot;, <br>        &quot;input&quot;: {<br>            &quot;ip_adress&quot;: &quot;203.13.121.5&quot;<br>        }<br>    }<br>}</pre><p>Once you have the reconstructed input, execute the corresponding function get_location_by_ipin your backend.</p><pre>if tool_name == &quot;get_location_by_ip&quot;:<br>    tool_response = await get_location_by_ip(<br>        **arguments<br>    )</pre><p>Let’s say tool_response will return following json:</p><pre>{<br>  &quot;city&quot;: &quot;Warsaw&quot;,<br>  &quot;region&quot;: &quot;Mazovia&quot;,<br>  &quot;country&quot;: &quot;PL&quot;,<br>  &quot;loc&quot;: &quot;52.2298,21.0118&quot;<br>}</pre><p>As we have <strong>tool_response</strong> data, the only thing left, is that we need to tell the model, that now it has this data and re-invoke it. We can do it we are appending the following <strong>tool_result</strong> to messages array:</p><pre>{<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: [<br>      {<br>        &quot;toolResult&quot;: {<br>          &quot;toolUseId&quot;: &quot;tooluse_20Z9zl0BQWSXjFuLKdTJcA&quot;,<br>          &quot;content&quot;: [<br>            {<br>              &quot;json&quot;: {<br>                &quot;city&quot;: &quot;Warsaw&quot;,<br>                &quot;region&quot;: &quot;Mazovia&quot;,<br>                &quot;country&quot;: &quot;PL&quot;,<br>                &quot;loc&quot;: &quot;52.2298,21.0118&quot;<br>              }<br>            }<br>          ]<br>        }<br>      }<br>    ]<br>  }</pre><p><strong>Crucially</strong>, the toolUseId in your result must match the ID provided by the model</p><p><strong>The updated message history will look like this:</strong></p><ol><li><strong>User</strong>: “What’s the weather in my city?”</li><li><strong>Assistant</strong>: (The Tool Use request generated in step 3)</li><li><strong>User (Role)</strong>: The toolResult containing the data.</li></ol><pre>[<br>  {<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: [<br>      {<br>        &quot;text&quot;: &quot;What&#39;s the weather in my city?&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;role&quot;: &quot;assistant&quot;,<br>    &quot;content&quot;: [<br>      {<br>        &quot;toolUse&quot;: {<br>          &quot;toolUseId&quot;: &quot;tooluse_20Z9zl0BQWSXjFuLKdTJcA&quot;,<br>          &quot;name&quot;: &quot;location_by_ip_client_get_location_by_ip&quot;,<br>          &quot;input&quot;: {<br>            &quot;ip_adress&quot;: &quot;203.13.121.5&quot;<br>          }<br>        }<br>      }<br>    ]<br>  },<br>  {<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: [<br>      {<br>        &quot;toolResult&quot;: {<br>          &quot;toolUseId&quot;: &quot;tooluse_20Z9zl0BQWSXjFuLKdTJcA&quot;,<br>          &quot;content&quot;: [<br>            {<br>              &quot;json&quot;: {<br>                &quot;city&quot;: &quot;Warsaw&quot;,<br>                &quot;region&quot;: &quot;Mazovia&quot;,<br>                &quot;country&quot;: &quot;PL&quot;,<br>                &quot;loc&quot;: &quot;52.2298,21.0118&quot;<br>              }<br>            }<br>          ]<br>        }<br>      }<br>    ]<br>  }<br>]</pre><p>Re-invoke the model with the updated messages. If the model needs more information (e.g., now that it has the coordinates, it needs to call get_weather), it will trigger another tool_use stop reason. Repeat this process until the model responds with a final text answer (stopReason: end_turn).</p><pre>response_stream = bedrock_runtime.converse_stream(<br>    modelId=model_id,<br>    system=[{<br>        &quot;text&quot;: f&quot;Curent user&#39;s ip is {client_host}.&quot;, # system prompt<br>    }],<br>    messages=messages, # array of messages above<br>    toolConfig={<br>        &quot;tools&quot;: converted_tools<br>    }<br>)</pre><p>That’s, in essence a function calling</p><h3>MCP (Model-Context Protocol)</h3><p>At its core, <strong>MCP (Model Context Protocol)</strong> is essentially remote function calling. To understand its value, let’s imagine a world where MCP doesn’t exist. Suppose you are preparing to ship two different AI agents to your users. Both agents share a common requirement for function calling. For example, you have a <strong>Weather Agent</strong> that predicts local forecasts and a <strong>News Agent</strong> that aggregates local headlines. Both agents must determine the <strong>user’s location </strong>before they can provide any useful information.Ideally, you wouldn’t want to duplicate the location-detecting logic inside both agents. Instead, you would want to move the <strong>“Location Tool”</strong> to a centralized location where both agents can access it. This ensures that any updates or modifications to the code remain consistent across both applications.</p><p>When considering this architecture, two solutions come to mind:</p><ol><li><strong>Shared Libraries:</strong> Package the tool as a library (e.g., an <strong>npm</strong> or <strong>pip</strong> package) and import it directly into your code.</li><li><strong>HTTP Endpoints:</strong> Create a standalone web service and call it via an API whenever an agent needs a result.</li></ol><p>While these approaches solve the problem within a specific project, they create a new problem: If you want to use external tools developed by others, you’ll find that every developer has designed their API differently. To integrate them, you would have to write a custom “wrapper” or connector for every single tool, resulting in a <strong>“connector zoo”</strong> — a fragmented, unmanageable mess of specialized code.</p><p>This is exactly the problem <strong>MCP (Model Context Protocol)</strong> solves. It provides a standardized, universal API for sharing and invoking tools, allowing any agent to communicate with any tool server seamlessly, regardless of who built it</p><p>Today MCP has two main <strong>transports</strong></p><p><strong>stdio </strong>— in general, you could think about it as of something for local calls. Like the shared lib we’ve discussed above. The idea is that your server is a subprocess</p><p><strong>Streamable HTTP</strong> —the MCP server receives an HTTP connection and can handle multiple clients concurrently using different sessions. This is am advantage over stdio, where a new process spawned for each new client connection. By default, when the server receives the first connection from a client, it generates a unique session ID and assigns that session to the client. This session can then be used to store client-related information on the server. This is particularly useful because it allows the server to avoid retransmitting a large amount of redundant data, such as model context or client state, in subsequent requests within the same session. Note, that, even though, session is a default behaviour, having session is <strong>not a requirement</strong></p><p>Official MCP doc has a very good <a href="https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management">image</a> for the streamable HTTP transport with session:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFVzxBNOe6Bc6tXR9iLRCQ.png" /></figure><p><strong>SSE</strong> — There is also deprecated transport for SSE, but I don’t know anything about it and suggest you to know anything about it :)</p><p><strong>Custom transport — i</strong>n case, if you’ll have a specific requirements, you might also create your own transport. But that’s not be touched withing this article</p><p><strong>Tool conversion — </strong>MCP defines its own standard for tool APIs, which typically differs from the native tool definitions required by various model providers. Since MCP was developed by <strong>Anthropic</strong>, the protocol’s tool API maps 1:1 to the native Claude API. However, when working with <strong>Amazon Bedrock</strong>, the Converse API expects a specific structure called toolSpec. To use MCP-hosted tools with Bedrock, you must implement a <strong>converter</strong> that translates MCP schemas into the Bedrock-compatible JSON format.</p><pre>def mcp_2_bedrock_convertor(mcp_tool):<br>    return {<br>        &quot;toolSpec&quot;: {<br>            &quot;name&quot;: mcp_tool.name,<br>            &quot;description&quot;:  mcp_tool.description,<br>            &quot;inputSchema&quot;: {<br>                &quot;json&quot;: mcp_tool.inputSchema<br>            }<br>        }<br>    }</pre><p>For the refference, you can found MCP tool spec <a href="https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool">here</a>. With that knoweldge we are now ready to begin our talk on how to ship this to AWS</p><h3>Repository</h3><p>Link — <a href="https://github.com/aperteda-medium/MCP-demo">https://github.com/aperteda-medium/MCP-demo</a></p><p>This guide is mostly for you to follow the repo. However, I’ll try to explain as much details, as possible below</p><h3>Configuration</h3><p>You’ll need to create a .env file inside the MCP-fastapi-client directory. Below is an example of the required variables:</p><p>Environment Variables</p><ul><li><strong>MOCK_LOCAL_IP</strong> (Optional): Used for local testing. Since using 127.0.0.1 makes it difficult to detect a specific geographic location, you can use this to simulate a different IP address.</li><li><strong>IP_INFO_TOKEN</strong>: A token from <a href="https://ipinfo.io/">ipinfo.io</a>. This is required for one of our MCP servers. At the time of writing, these tokens are available for free.</li></ul><pre>MOCK_LOCAL_IP=203.13.121.5 # some ip for local testion only. Optional<br>IP_INFO_TOKEN=token_from_ip_info # Token from &quot;https://ipinfo.io/&quot;. Token is free </pre><p>We will also be using the <strong>Amazon Nova</strong> model from the EU region. As of this writing, this model is only accessible through an <strong>Inference Profile</strong>.</p><p>You can locate yours here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k98ijxvLVkiiuDUfPQxfHA.png" /></figure><h3>Prerequisites</h3><ul><li><strong>AWS Account &amp; Credentials</strong>: A valid AWS account is required. If you are unsure how to set up your credentials, please refer to <a href="https://medium.com/@aperteda/aws-secure-role-based-short-therm-authorisation-for-your-infrastructure-code-cdk-and-sdk-resources-7b2384f6c8d0">this article</a>.</li><li><strong>Docker &amp; Docker Compose</strong>: (Version used: 28.0.1)</li><li><strong>AWS CDK</strong>: (Version used: 2.1031.1)</li><li><strong>Python</strong>: (Version used: 3.11.11)</li><li><strong>Node.js</strong>: (Version used: 20.12.2)</li></ul><p><strong>Frontend</strong></p><p>Navigate to MCP-fe from project root folder and run</p><pre>npm install</pre><p>to install dependenices. Then, run the Frontend with following co</p><pre>npm run dev</pre><p><strong>Backend</strong></p><p>Open a <strong>new terminal window</strong> and stay in the project root folder. The backend requires AWS credentials to communicate with cloud services. Export your temporary credentials to your current shell session</p><pre>export AWS_ACCESS_KEY_ID=&quot;{somekey}&quot;<br>export AWS_SECRET_ACCESS_KEY=&quot;{somesecret}&quot;<br>export AWS_SESSION_TOKEN=&quot;{somesessiontoken}&quot;</pre><p>Once the credentials are set, use Docker to spin up the backend containers:</p><pre>docker compose up</pre><p>Once both processes are running, your local environment is active.</p><ul><li><strong>Frontend:</strong> Usually accessible at http://localhost:5173</li><li><strong>Backend:</strong> Docker will show active logs for the MCP services and your backend FastAPI client</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*nFelYdsih31fO2ncjLgPKg.gif" /></figure><h3>MCP on AWS</h3><p>Let’s consider our options for deploying this to AWS. While we could use ECS, EKS, or EC2, that might not be the most cost-effective way, especially as we are already utilizing a pay-as-you-go model to interact with the LLM.</p><p>Therefore, it makes to go serverless and deploying MCP servers/client via AWS Lambda.</p><p>AWS community provides its own library for running Model Context Protocol (MCP) servers on Lambda</p><p><a href="https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/tree/main">https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/tree/main</a>.</p><p>However, that library follows a more ‘Lambda-native’ approach. In this article, we will instead focus on a ‘lift-and-shift’ strategy using the Lambda <a href="https://github.com/awslabs/aws-lambda-web-adapter">Web Adapter library</a>, which is specifically designed to migrate server applications to AWS Lambda. Let’s examine the architecture to gain a deeper understanding of the implementation details.</p><h3>Target architecture</h3><p>First let’s look and the diagram, and then, let’s check, what to we have there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJxtHUr8U3ygGMsVYSwWcw.png" /></figure><p><strong>Frontend</strong></p><p>In our case, it’s a simple SPA app baked by <strong>React.js</strong> For more detail on how to host SPA on AWS reffer to this <a href="https://medium.com/@aperteda/serving-static-website-on-aws-with-private-s3-bucket-and-cloudfront-oac-origin-access-control-7b19292d82aa">article</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*8mFXXdxHjtQZL0ek8-EpLg.png" /></figure><p><strong>Backend (MCP client)</strong></p><p>First, let’ make a quick look on architecure of that piece of code. In that case, we have a MCP host client which speaks to bedrock and return the stream. It’s proxied through cloudfront protected with Origin Access Control. Let’s make a deeper look on that. Lambda is the fastAPI app with Lambda Web adapter, so we’ll be able to use Lambda Adapter. We’ll talk about it below in details. Also, our client lambda is what will be communicating with LLM (bedrock in our case)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*BwpEARaqroBCaqhYNvTyTQ.png" /></figure><p>We will also have an <strong>MCP Lambda client</strong> with response streaming enabled. Since Lambda streaming is not the primary theme of this article, I will not focus on every detail; however, I will provide all the necessary information for the implementation.</p><p>If you are using Lambda and want to enable HTTP <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-response-streaming.html">streaming</a>, you essentially have two options:</p><ol><li><strong>Native Lambda Streaming:</strong> Note that if you choose the native route, you are currently limited to <strong>Node.js</strong>. This may not be ideal in the AI space, where Python is the dominant language.</li><li><strong>Custom Runtime with Python:</strong> (Or any language of your choice). Python currently offers the broadest ecosystem for AI and Generative AI.</li></ol><p>Let’s assume we choose Python and a custom runtime. Since we already have an application running locally, the ideal scenario is a “lift and shift” with little to no code modification. For AWS Lambda, there is a framework for this called the <a href="http://Lambda Web Adapter"><strong>Lambda Web Adapter</strong></a>.</p><p>However, we still need to make specific configurations for AWS Lambda to support streaming. The only way to stream from a Lambda with a custom runtime is through a <strong>Function URL</strong>. A potential downside is that a Function URL creates a standalone endpoint that does not natively support Web Application Firewall (WAF) integration. To resolve this, we will use the Function URL to support streaming but avoid using it directly. Instead, we will <strong>proxy it through CloudFront</strong>. We can then use an IAM authorizer to ensure that any direct requests to the Function URL are rejected, protecting the endpoint if the URL is ever exposed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acuHkAeengIVcyh2PPRA9g.png" /></figure><p>To achieve this, we can create multiple <strong>CloudFront behaviors and origins</strong>. One of these behaviors will act as a proxy for our client Lambda, where the origin domain is the Lambda Function URL itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jq72193e6pYXxgc_AHHi3g.png" /></figure><p>As you can see, there is an Origin Access Control. You’ll need to create one for a lambdaURL. It may look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqasLgP10XhuwzP7IuJkuQ.png" /></figure><p>Our behaviour for this origin should look like more less like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFw18TXaZT1qieVEd7he3w.png" /></figure><p>Note, the for header request we should Cache Policy and Request Policy from recommended for Lambda URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QT85M6IMmgvgNVQ5IDaNEQ.png" /></figure><p>An important point to note is that since we have <strong>Origin Access Control (OAC)</strong> configured on our CloudFront behavior (and we are proxying through it), we must <strong>sign the request body</strong> for all requests containing a payload. The frontend code for this implementation might look like this</p><pre>  const calculateSha256 = async (message: string) =&gt; {<br>    const msgBuffer = new TextEncoder().encode(message);<br>    const hashBuffer = await crypto.subtle.digest(&quot;SHA-256&quot;, msgBuffer);<br>    const hashArray = Array.from(new Uint8Array(hashBuffer));<br>    const hashHex = hashArray<br>      .map((b) =&gt; b.toString(16).padStart(2, &quot;0&quot;))<br>      .join(&quot;&quot;);<br>    return hashHex;<br>  };</pre><p>Next, we need to inject this signature as a header in our frontend request. Additionally, please note that the <strong>Content-Type: application/json</strong> header is required to ensure the request body is properly parsed on the backend.</p><pre>    const streamResponse = await fetch(url, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;x-amz-content-sha256&quot;: sha256,<br>      },<br>      body: body,<br>    });</pre><p>Note that since we are using <strong>FastAPI</strong> for our backend, there is an interesting trick required to achieve a true streaming chunked response. Because FastAPI handles response chunking automatically under the hood, you may need to include a sleep function within your generator (yield) function to ensure the chunks are dispatched correctly. In your code, it should look like this:</p><pre> <br>import asyncio<br>import json<br>from typing import AsyncGenerator, Dict, Any<br><br>from fastapi import FastAPI<br>from fastapi.responses import StreamingResponse<br><br>app = FastAPI()<br><br><br>async def event_stream(response_stream: Dict[str, Any]) -&gt; AsyncGenerator[str, None]:<br>    &quot;&quot;&quot;<br>    Streams dict-based chunks as Server-Sent Events (SSE).<br>    &quot;&quot;&quot;<br><br>    for chunk in response_stream[&quot;stream&quot;]:<br>        text = chunk[&quot;contentBlockDelta&quot;][&quot;delta&quot;][&quot;text&quot;]<br><br>        yield f&quot;data: {json.dumps({&#39;text&#39;: text})}\n\n&quot;<br><br>        # Yield control back to the event loop<br>        await asyncio.sleep(0)<br><br><br>@app.post(&quot;/stream&quot;)<br>async def stream_endpoint():<br>    response_stream = ...  # Provided by upstream streaming source (LLM, SDK, etc.)<br><br>    return StreamingResponse(<br>        event_stream(response_stream),<br>        media_type=&quot;text/event-stream&quot;,<br>    )</pre><p><strong>Backend (MCP Servers)</strong></p><p>Let’s look at the MCP server diagram again. The requests will be sent from our client Lambda to CloudFront, which is backed by API Gateway. The client Lambda then receives the tool definition and reinvokes our MCP servers for tool invocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*COeguLbzCMSCq5_6TyBM3g.png" /></figure><p>Yes, we potentially could sent to the API Gateway directly, however, proxying throgh cloudfront gives us two things:</p><ol><li>We are keeping everything on one domain</li><li>We could have similair firewalls rules in a single point of our system</li></ol><p>The API Gateway then sent our request to a FastMCP server running on lambda. Now, here thing get intersting. FastMCP is an official SDK for MCP. If we are using HTTP transfer protocol (which we are doing here), by default FastMCP store the session. By defult, this session stores in memory.</p><p>The store path couldn’t be customised by the time of writing this article. That’s lead to an issue, as we are using lambda, which has read-only file system. Luckilly for us, we can also use a stateless MCP servers (i.e. without sessions. The code to for the MCP server without session might look like this. Be aware about imports, as from some version the imports has been changed</p><pre>from fastmcp import FastMCP<br><br>mcp = FastMCP(&quot;MCP-location-by-ip-server&quot;, stateless_http=True)</pre><p>The second problem we will face is that the FastMCP server expects our origin to have the root URL /mcp. In our case, however, we will be proxying it through CloudFront behaviors similarly to how we did for the streaming Lambda, meaning our root path will be api/v1/{mcp-server-name}/mcp. We’ll talk about how to resolve this in a second.</p><p>Essentially, we will have one behavior and one origin for both. The origin should be a standard configuration for API Gateway, looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHEAcK0sKzRVFTEwf8PZQw.png" /></figure><p>And the behaviour will be like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWYHOZ02lMI27S2dxbPetQ.png" /></figure><p>Note, that now we should use that now for Cache Policy and Request policy we need to use different params, optimised for API Gateway</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAWd4YVG2QBBhRRa4PlfkQ.png" /></figure><p>The important thing now is that because we are proxying through /api/v1/* and managing paths inside our API Gateway, we need to handle the routing as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*tlTEP8NDJYHttvnOVMfkNg.png" /></figure><p>The path to our MCP server will be something like /api/v1/weather-by-location-server. Remember that our FastMCP server expects /mcp with / as an origin. Therefore, we will need a way to add route parsing to it. Luckily, we can still achieve this by wrapping our FastMCP instance in a FastAPI application. This can be done as follows:</p><pre>from fastapi import FastAPI<br>from fastmcp import FastMCP<br>import uvicorn<br><br>app = FastAPI()<br>mcp = FastMCP(&quot;MCP-location-by-ip-server&quot;, stateless_http=True)<br><br>mcp_app = mcp.http_app(path=&#39;/mcp&#39;)<br>app = FastAPI(lifespan=mcp_app.lifespan) # wrapping MCP into fastAPI<br><br>app.mount((os.getenv(&quot;MCP_SERVER_PATH&quot;, &quot;/&quot;)), mcp_app)<br><br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(<br>        &quot;server:app&quot;,<br>        host=&quot;0.0.0.0&quot;,<br>        port=int(os.getenv(&quot;PORT&quot;, 8000)),<br>        reload=False,<br>    )</pre><p>The second issue we will face is that since we are proxying our requests through CloudFront, then API Gateway, and finally the Lambda service, the IP address received in the request data will not be the actual user’s IP. To overcome this, use the x-forwarded-for header in our client Lambda. To retrieve it, the code should look something like this:</p><pre>from fastapi import APIRouter, Request<br>from app.schemas.schema import PromptRequest # pydantic definittion from our code<br><br>@router.post(&quot;/bedrock-stream&quot;)<br>async def bedrock_stream(<br>        request: Request,<br>        body: PromptRequest<br>    ):<br>    client_host = mock_local_ip<br><br>    xff = request.headers.get(&quot;x-forwarded-for&quot;)<br>    if xff:<br>        client_host = xff.split(&quot;,&quot;)[0].strip()</pre><p><strong>Addional notes</strong></p><p>Note regarding the client Lambda from which we will invoke the MCP. Since a situation may arise where different MCP servers return the same tool name, the tool name for the MCP function will be updated to a combination of the server_name and the function_name. In our code, the call might look like this, where arguments is a dictionary containing the arguments:</p><pre>if tool_name == f&quot;{LOCATION_BY_IP_MCP_CLIENT_NAME}_get_location_by_ip&quot;:<br>    tool_response = await mcp_client.call_tool(<br>        f&quot;{LOCATION_BY_IP_MCP_CLIENT_NAME}_get_location_by_ip&quot;,<br>        arguments,<br>    )<br><br>elif tool_name == f&quot;{WEATHER_BY_LOCATION_MCP_CLIENT_NAME}_get_weather&quot;:<br>    tool_response = await mcp_client.call_tool(<br>        f&quot;{WEATHER_BY_LOCATION_MCP_CLIENT_NAME}_get_weather&quot;,<br>        arguments,<br>    )</pre><p>Note that for a classic tool, you need both a tool and an arguments description. If you are using <strong>FastMCP</strong>, these are described within the MCP decorator. For example, your tool might look like the following, where the description is actually contained inside the <strong>docstring</strong>:</p><pre>@mcp.tool()<br>async def get_weather(location: str):<br>    # Don&#39;t forget to add description for the tool, as it&#39;ll be used as model inference input<br>    &quot;&quot;&quot;<br>    Detects weather by specified location, coordinates<br><br>    Args:<br>        @param location (str): Location in format &quot;latitude,longitude&quot; (e.g. &quot;50.4501,30.5234&quot;)<br>    &quot;&quot;&quot;<br>    lat, lon = location.split(&#39;,&#39;)<br>    url = f&quot;https://api.open-meteo.com/v1/forecast?latitude={lat}&amp;longitude={lon}&amp;current=apparent_temperature,snowfall,showers,rain,precipitation,cloud_cover,pressure_msl,surface_pressure,weather_code&amp;forecast_days=1&quot;<br>    async with httpx.AsyncClient() as client:<br>        response = await client.get(url)<br>        data = response.json()<br>        return data</pre><h3>Architecture Summary</h3><ul><li><strong>Streaming Strategy:</strong> Use a <strong>Python custom runtime</strong> with <strong>Lambda Function URLs</strong> to bypass Node.js limitations.</li><li><strong>Security:</strong> Proxy the Function URL through <strong>CloudFront</strong> with <strong>Origin Access Control (OAC)</strong> and IAM authorization to protect the endpoint and integrate with <strong>WAF</strong>.</li><li><strong>Routing:</strong> Wrap <strong>FastMCP</strong> inside <strong>FastAPI</strong> to handle custom path prefixes (like /api/v1/) and use asyncio.sleep() to ensure reliable response chunking.</li><li><strong>Request Handling:</strong> Extract the true client IP using the X-Forwarded-For header and implement a server_name + function_name naming convention to avoid tool collisions.</li></ul><p>Now, with all those knoweledge I wish you to happy hacking with AWS serveless gen-AI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c198bb4f0cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS secure role-based short-therm authorisation for your infrastructure code, CDK and SDK resources]]></title>
            <link>https://medium.com/@aperteda/aws-secure-role-based-short-therm-authorisation-for-your-infrastructure-code-cdk-and-sdk-resources-7b2384f6c8d0?source=rss-ef7e25d2cc7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2384f6c8d0</guid>
            <category><![CDATA[iam-roles]]></category>
            <category><![CDATA[identity-management]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Andrii Lobanov]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 22:19:22 GMT</pubDate>
            <atom:updated>2025-07-01T22:19:22.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary</h3><p>Internet is full of tutorials on how to authorise on AWS. A lot of this tutorials suggests using IAM users. This provides the obvious security breach — if, by any reason, you credentials will leak, then 3-d party agent will be able to do anything with your AWS account in any amount of time. So, the general rule is — let’s not use IAM user’s permission until you are not 100% obligated of doing so.</p><p>Then, what’s the alternative? And the answer is IAM roles. Roles a short therm credentials which has secret rotation on timely bases. Even if those credentials will somehow be leaked, atacker still be restricted on time by doing harm to your system. Combine this with least privilege permission principle might give you enough security to start with and potentially keep you out of troubles</p><p>However, that’s raise a question. Where I can get this role permissions, which I then be able to use with my infrastructure code</p><h3>Target architecture</h3><p>General idea is following</p><ul><li>Users will receive a url, which they could use to receive a permission to a granted AWS accounts</li><li>Each logged-in user could have multiple account assigned AND each account could have multiple permission set assigned per user</li><li>Each permission set has unique combination of role and session name, which grants user an ability to perform action (like running terraform, AWS cli scripts and so on) once signed</li></ul><p>In real world, the access link is also often protected by organisation SSO system and there are managment and secondary AWS accounts. However, here, for simplicity, we’ll focus on single AWS account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*f18KjP0MP4VDxWN1XAzbYg.png" /></figure><h3>Implementation steps (AWS console)</h3><p>First, you need a root or admin access for this action. Normally, this action is done once under the root account.</p><p>In your AWS as root go to <a href="https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html">IAM Identity Center</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjO8hjJa0uxi8lhXS5Jbxg.png" /></figure><p>And enable it in your desired region. Note: the IAM Identity Center is allowed only once per account. This means enabling it in a specific region would restrict you from enabling another one in a different region. However, you can still manage permissions for other regions through the region where it’s hosted</p><p>Also, remember that you can manage access permissions from your IAM Identity Center for other AWS accounts. So, choose your main account and primary region carefully</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VS8UGZ5KqSMtdvo5Xr6Peg.png" /></figure><p>Now that we’ve enabled IAM Identity Center, let’s create the user we’ll use to access our AWS resources. Navigate to “<em>Users”</em>, then select “<em>Add user”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W80wOrpYh00ixMFvPlyrZg.png" /></figure><p>The only required section here is “<em>Primary Information”</em>. We can skip all other optional details for now, such as adding the user to a group. Just fill in the primary information and ignore any additional fields — we’ll handle those later after creating the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdSOoV8UI3SfFu7fEZU6Lg.png" /></figure><p>After you’ve created the user, you’ll receive a confirmation modal with the AWS console login URL and a temporary one-time password for login (or email instructions, if you selected this option instead)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISt_AXCVgRtjDxrinaDc2w.png" /></figure><p>Write down your temporary password and paste the login URL into your browser. After entering your username and email, and completing additional verification, you should see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmjUilIgvWMRF4mJ68unjQ.png" /></figure><p>This is expected since we haven’t set up any access for our user yet. Let’s proceed by creating a permission set and assigning an AWS account to our user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I93JRvmN1GpLl6ysDb8YFw.png" /></figure><p>For now, let’s select “AdministratorAccess” from the predefined permission sets. This permission will be assigned to our IAM role in AWS Identity and Access Management (IAM)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZlZ8oPR4PH4rXTBFfx-ZA.png" /></figure><p>For the “Specify permission set details” section:</p><ol><li>Leave the session duration at the default value of ‘1 hour’</li><li>Skip all remaining configuration options. Proceed to “create the permission set”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SddJuHKbkXEPCn6T4hvfw.png" /></figure><p>Now, we have everything needed to assign our user to AWS account, so our user will receive a role credentials, which they can use for AWS resources operations. Go to “AWS accounts” section, select you account and assign a user to it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4Lz3guVz29xUuOJ0l7dDA.png" /></figure><p>Under “Assign users and groups” choose “Users” tab, select your user and press “Next”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUn7D3961HpOK8sHKTIoiA.png" /></figure><p>Under “Select permission sets” check-in permission set, we’ve just created and press “Next” and “Submit” after review section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DB8HpVY7CQV40ISiCVXLEA.png" /></figure><p>After that, let’s find our account login URL. It’ll be under “Dashboard” and then “Setting summary” section. Open incognito tab (to avoid previous session cache) and paste it your browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8aAl_mzIhTDc5HOE4bFJQ.png" /></figure><p>After you’ll pass your new setted passwod and authorize, you should see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qUHp8gVlLsLsbvpNpiX0w.png" /></figure><p>If you click on “AdministratorAccess” you’ll land inside your AWS console with role-based temporary 1 hour permissions.</p><p>If you click to access keys, you’ll receive access keys, which you can use for AWS resources creation in the account</p><p>For now, let’s verify our credentials is working. Let’s try to list bucket from CLI without adding credentials from role and with them after. So, if I do nothing at that point and run:</p><pre>aws s3 ls</pre><p>This is output, which is expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41AuJCg55nLF0Q2w_-EbvA.png" /></figure><p>We’ll need to click on “Access keys” from the role, paste it to my terminal (could be any folder) and press “Enter”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAqJzJIipodoeGExhpYzxQ.png" /></figure><p>Now, we authorised as short-them federated role. Let’s repeat out previous command</p><pre>aws s3 ls</pre><p>It’ll returning the bucket I have. If you don’t have any buckets within your AWS account, it might be empty execution result. Which also good, as if you don’t receive an error, then your role is working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*c-EiojtEbMbC8veTcbRXTw.png" /></figure><p>This approach is good for using with AWS CDK, Terraform, CloudFormation or other IAC (Infrastructure as a Code) tools. Note, in reality you most likely will have multiple AWS accounts managed under IAM Identity center manament AWS account. However, if you only need one account, this should be enough to secure use IAM role in your development</p><h3>Clean-up</h3><p>Go to “settings” inside your IAM Identity Center console. Scroll down and select “managment” tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdyUqKwt96fLOIFc_6HTbA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2384f6c8d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving static website on AWS with private S3 bucket and Cloudfront OAC (Origin Access Control)]]></title>
            <link>https://medium.com/@aperteda/serving-static-website-on-aws-with-private-s3-bucket-and-cloudfront-oac-origin-access-control-7b19292d82aa?source=rss-ef7e25d2cc7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b19292d82aa</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[cloudfront]]></category>
            <dc:creator><![CDATA[Andrii Lobanov]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 14:27:33 GMT</pubDate>
            <atom:updated>2024-06-29T11:12:51.799Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary</h3><p>The reason, why this guide is created, is that most similar guides around the net normally violates one those best practices</p><ul><li>Suggesting you to make a<a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteAccessPermissionsReqd.html"> S3 bucket public</a>, which violates security and <a href="https://docs.aws.amazon.com/wellarchitected/latest/framework/sec_permissions_least_privileges.html">least privilege principle</a></li><li>Suggesting you to use legacy OAI, when there is a better and mode secure <a href="https://aws.amazon.com/about-aws/whats-new/2022/08/amazon-cloudfront-origin-access-control/">option</a> nowadays.</li><li>Completely ignoring <a href="https://stackoverflow.com/questions/16267339/s3-static-website-hosting-route-all-paths-to-index-html">bookmarking problem</a>. If user want’s to navigate to your website via bookmark, typically, he’ll response 403 access denied page, instead of giveback the routing control to your SPA app</li></ul><p>This guide will help to overcome those issues and create a static website or SPA, which follows AWS best practices</p><h3>Prerequisites</h3><ul><li>AWS account</li><li>Any static website build (we’ll use an angular 17 CLI starting page here, but it could be any SPA)</li></ul><h3>Repository</h3><p>If you are not new to the AWS world and familiar with CDK, the easiest option for you might be to deploy the CDK build from this repo. However, I suggest looking through the Implementation section to get an idea of potential troubleshooting issues.</p><p><a href="https://github.com/aperteda-medium/cloudfront-s3-sample"><em>https://github.com/aperteda-medium/cloudfront-s3-sample</em></a></p><h3>Target architecture</h3><p>The user is sending the request to Cloudfront. Cloudfront then, checks if the requested object exists in cache. If there is no, it signs the request with S<a href="https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html">igV4</a> and redirect it to S3. When S3 service receives a request, it makes the same steps to create a signature. If both signatures match, the request allow. Else, denied</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*CnuSkrXokukQMOE3fMyStQ.png" /></figure><h3>Implementation steps (AWS console)</h3><ol><li>Create S3 bucket for out website. Leave all settings default. Do <strong>NOT</strong> activate static website hosting feature. Leave <strong>Block <em>all</em> public access </strong>setting active. Let’s call this bucket <em>S3-website-bucket </em>in this tutorial and use this name further</li><li>Build your static website (if not builded yet) and upload the content of the build/dist folder to this bucket</li><li>Create another S3 bucket with same default settings for our website logs (it will be used for website logs). Let’s call it <em>S3-website-logs-bucket</em> in this tutorial</li><li>Create a Cloudfront distribution. Select your <em>S3-website-bucket </em>as a <strong>Origin domain </strong>setting. For the <strong>Origin access </strong>setting select the <strong>Origin Access Control, </strong>press<strong> Create new OAC </strong>and create it. Note OAC name has a restriction to be unique and at most 64 characters. It’s a best practice to name OAC same as an origin name, but it’s not a requirement. Especially, if your origin has more then 64 chars</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNkSuQp8LZirgVz3KHTLgQ.png" /></figure><p>5. For simplicity, in <strong>Web Application Firewall (WAF) </strong>select D<strong>o not enable security protections</strong></p><p>6. In <strong>settings</strong> section at the very bottom activate standard logging and specify the bucket, we’ve created at step 2 (<em>S3-website-logs-bucket) </em>and enable ACLs for this bucket</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TVuOvxiVxh2kJD2MrUNzA.png" /></figure><p>7. Press <strong>create a distribution</strong> and copy read-access bucket policy for our <em>S3-website-bucket. </em>This will<em> </em>allow Cloudfront to get static files from our S3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rU5-yT90K3ksAjf0haAVoA.png" /></figure><p>8. Go to our <em>S3-website-bucket. </em>Select <strong>Permissions</strong> tab, scroll to <strong>Bucket policy </strong>setting and press <strong>edit</strong>. Paste our copied policy and save. Normally, the policy will look like this</p><pre>{<br>  &quot;Version&quot;: &quot;2008-10-17&quot;,<br>  &quot;Id&quot;: &quot;PolicyForCloudFrontPrivateContent&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;AllowCloudFrontServicePrincipal&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;cloudfront.amazonaws.com&quot;<br>      },<br>      &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>      &quot;Resource&quot;: &quot;{s3bucketARN}/*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringEquals&quot;: {<br>          &quot;AWS:SourceArn&quot;: &quot;{cloudfrontARN}&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>If you are using provided sample, please change <em>“{s3bucketARN}”</em> and <em>“{cloudfrontARN}”</em> to your <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html">ARN</a>s</p><p><em>s3bucketARN</em> — arn of <em>S3-website-bucket </em>we’ve created at <strong>step 1</strong>.</p><p><em>cloudfrontARN — </em>arn of Cloudfront distribution we’ve created</p><p>Save your changes</p><p>9. Go back to Cloudfront distribution, we’ve created. Check, if it’s deployed (normally, after distribution is deployed, the timestamp will appear in “Last modified” column. If it is there, copy the <strong>Domain name</strong>, you’ve received and paste it the browser. Note, cloudfront is normally using <em>https://</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D91uNL0bQdzrjg85n5UwMw.png" /></figure><p>10. Most likely, you’ll see the standard <strong>Access Denied </strong>page. The reason, is that we didn’t specify the path to our html file in the Cloudfront.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXAN7CxfzXwnDpcB6ME2OQ.png" /></figure><p>Try to add to path to your Domain name in browser url. It should be your path in s3. In my case, the path is “<em>/angular-s3/browser/index.html</em>” so the link will be <a href="https://d2wdijbim5b01l.cloudfront.net/angular-s3/browser/index.html">https://d2wdijbim5b01l.cloudfront.net/angular-s3/browser/index.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7G6XzKBocP_5uaR_g98YA.png" /></figure><p>Now you might face an issue, where you’ll getting your html file back, but the access to related resources (.css, .js and other files, which are requested from index.html) is denied</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSrK3g-y-1muz3Mr0eGvlw.png" /></figure><p>Let’s fix it via adding path to our Cloudfront distribution</p><p>11. Go to our Cloudfront distribution created in previous step. Open “Origins” tab. Select our origin and press <strong>Edit</strong>, add your path and press <strong>save</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4gIwzlFBs-55gm8mKHSQA.png" /></figure><p>12. Go to <strong>General</strong> settings in your Cloudfront distributions and press <strong>edit </strong>and add<strong> index.hml </strong>as the your default root object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLe_1fMm6Xm7kJr5mNpIgg.png" /></figure><p>13. Wait until the distribution is deployed and navigate to browser with your Cloudfront distribution name and look’s like we have our static website hosted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwDmDnrKktmh1l9xmkb2WA.png" /></figure><p>But there is still one problem. While we can navigate through the app via history API, we might have issue with bookmarking specific page and revisit it browser.</p><p>Check this gif.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Ctfe9B9SI3so0nQA2tSS-g.gif" /></figure><p>The route “/user/bob” doesn’t exist, which lead us to “PageNotFoundComponent” as expected, when we press the button “Link to not found”. But when we are trying to go on this page via direct browsing, we are receiving 403 Access Denied error page. This will be the exact scenario, if user will decide to bookmark any of url from our SPA. So, let’s fix it</p><p>I’ve created a path in my build, which grabs all requests, which are not registered in routing. Basically, it look’s like this in the code:</p><pre>export const routes: Routes = [<br>    { path: &#39;&#39;, component: MainComponent },<br>    {  path: &#39;**&#39;, pathMatch: &#39;full&#39;, component: PageNotFoundComponent }<br>];</pre><p>So it’s expected we’ll see the <strong>PageNotFoundComponent </strong>instead of cloudfront 403 page. Let’s fix it</p><p>14. Go to your Cloudfront distribution, open <strong>Error pages </strong>tab and press <strong>Create error page response. </strong>Specify the <strong>HTTP error code </strong>as 403. <strong>Select Customize error response</strong> as <strong>Yes</strong>. Provide the path to the <strong>index.html </strong>in<strong> </strong>your SPA. Optionally, you could change <strong>HTTP Response code </strong>if you wish</p><p>Save the custom error, and wait, till your distribution will be deployed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJLNW2OHk6b-EDazzHzD3w.png" /></figure><p>Now, let’s enjoy the result 🎉🎉🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QMeETmCVmtX-rT3NSPZbMw.gif" /></figure><h3>Troubleshooting</h3><p>If you are updating files in your bucket, do not forget to invalidate Cloudfront cache. Go to your distribution and select <strong>Invalidations</strong> tab. Create invalidation with needed path. For all files, it’ll be like this “/*”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0Q18TRuyIU5ULG_1ciU6A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b19292d82aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>