Hosting Your Serverless Website Using AWS

Arish AhmadArish Ahmad
6 min read

Note: This guide requires a web domain to host the website.

Step 1: Creating a S3 Bucket

  1. Open the AWS Management Console and navigate to the S3.

  2. Click Create Bucket.

  3. Give it a suitable name.

  4. Scroll and click Create Bucket.

  5. Copy the following and create an index.html file.

     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Demo Website</title>
     </head>
     <body>
         <div class="container">
             <h1>You're truly welcome!</h1>
             <h2>Do like the Blog if you find the tutorial helpful.</h2>
             <ul class="social-links">
                 <li><a href="https://arishahmad.hashnode.dev/hosting-your-serverless-website-using-aws" target="_blank">Blog</a></li>
             </ul>
             <h3 id="views">Views</h3>
         </div>
         <script src="script.js"></script>
     </body>
     </html>
    
  6. Upload this file in the S3 bucket.

Step 2: Creating CloudFront distribution.

  1. Navigate to CloudFront in the AWS Management Console.

  2. Click Create a CloudFront distribution.

  3. Select the S3 bucket you just created under the Origin domain.

  4. Under Origin access click Origin access control settings.

  5. Click Create new OAC -> Create.

  6. Under Web Application Firewall (WAF) select Do not enable security protections.

  7. Scroll and click Create distribution.

    This screen will pop up.

  8. Click Copy policy.

    If the Copy policy option doesn't appear.

    1. Open the distribution.

    2. Click on Origins.

    3. Select the origin and click Edit.

    4. Scroll and click Copy policy.

Step 3: Updating S3 bucket policy

  1. Navigate to S3 in the AWS Management Console.

  2. Open the bucket.

  3. Click on Permissions.

  4. On Bucket policy click Edit.

  5. Paste the policy and click Save changes.

Step 4: Set up Route53

  1. Navigate to Route 53 Dashboard in the AWS Management Console.

  2. Click Create hosted zone.

  3. Enter the Domain name.

  4. Select Public hosted zone under Type.

  5. Scroll and click Create hosted zone.

  6. Select the record with NS type, Record details will open up.

  7. Copy each value of this record and add this to the Nameserver. This option will be provided by the platform where you bought the domain.

Step 5: Editing the CloudFront

  1. Open the CloudFront distribution.

  2. Select the distribution and Click Edit on Settings.

  3. Select Add items under Alternate domain name (CNAME).

  4. Enter the domain on which you want to host the website (Example: If your domain name is example.com then enter demo.example.com).

  5. Scroll and click Request certificate. A new tab will open up.

  6. Click Next.

  7. Enter .<your domain name> (Example: If your domain name is example.com, enter *.example.com).

  8. Scroll and click Request.

    Your new certificate might continue to display a status of Pending validation for up to 30 minutes.

  9. Open the Certificate.

  10. Click Create records in Route 53.

  11. Click Create records.

    You can check the new route must be added in the hosted zone.

    Now wait till the status of certificate is not Issued.

  12. Go back to the CloudFront tab, and select the newly created Custom SSL certificate.

  13. Enter index.html under the Default root object.

  14. Scroll and click Save changes.

Step 6: Create a record in the Hosted Zone.

  1. Open the hosted zone in Route53.

  2. Click Create record.

  3. In record name enter the subdomain. This should be same as the alternate domain name you entered in the CloudFront distribution.

  4. Enable the Alias.

  5. Choose Alias to CloudFront distribution and select the distribution you created.

  6. Click Create Record.

  7. Now visit the alternate domain name, and you will see the hosted website. This might take few minutes until the CloudFront distribution is ready.

Step 7: Set up the DynamoDB

  1. Navigate to DynamoDB in the AWS Management Console.

  2. Click Create table.

  3. Enter a suitable name.

  4. Endet id in Partition key.

  5. Scroll and click Create Table.

  6. Select the table, go to Actions -> Explore items.

  7. Click Create item.

  8. Enter value 0 in id Attribute.

  9. Select Add new attribute -> Number.

  10. Enter the Attribute name as views and enter value 0.

  11. Click Create item.

Step 8: Create the Lambda Function

  1. Navigate to AWS Lambda in the AWS Management Console.

  2. Click Create a function.

  3. Enter a suitable Function name.

  4. Select Python 3.8 in Runtime.

  5. Select Create a new role with basic Lambda permissions in the Execution role.

  6. In Advanced settings click Enable function URL and NONE in Auth Type.

  7. Check the Configure cross-origin resource sharing (CORS).

  8. Scroll and click the Create function.

  9. Copy the following code.

     import json
     import boto3
     dynamodb = boto3.resource('dynamodb')
     table = dynamodb.Table('demo-table')
     def lambda_handler(event, context):
         response = table.get_item(Key={
             'id':'0'
         })
         views = response['Item']['views']
         views = views + 1
    
         print(views)
    
         response = table.put_item(Item={
             'id':'0',
             'views': views
         })
    
         return views
    
  10. Paste this file in the code area.

    Note: Change the table name in this file.

  11. Save the file then Click Deploy.

  12. Click Configuration -> Permissions.

  13. Click on the role, a new tab will open up.

  14. Click Addpermissions -> Attach policies.

  15. Search and select AmazonDynamoDBFullAccess.

  16. Click Add permissions.

  17. Now Come back to the Lambda tab.

  18. Click Code and then click Test.

  19. Enter a suitable name, then click Save.

  20. Now click Test again, and you can see the response.

Step 9: Creating the JS file

  1. Copy the following code.

     let counter = document.getElementById("views");
    
     async function updateCounter() {
         try {
             let response = await fetch("lambda_function_url");
             if (!response.ok) {
                 throw new Error('Network response was not ok');
             }
             let data = await response.json();
             console.log(data);
             counter.innerHTML = `Views: ${data}`;
         } catch (error) {
             console.error('Failed to fetch data:', error);
             counter.innerHTML = 'Failed to load views';
         }
     }
    
     updateCounter();
    
  2. Create a file named script.js file, and paste the code.

  3. Copy the Lambda function URL and replace lambda_function_url in the file with the URL.

  4. Now upload this script.js file in the S3 bucket.

Step 10: Finishing Up

Visit the Alternate domain name you entered in the CloudFront. You can see the hosted website and with each reload the view counter will increase. You can also check the increased value of views in the dynamoDB.

If the changes are not visible you may need to create an Invalidation.

  1. Open the CloudFront distribution you created.

  2. Click Invalidations -> Create invalidation.

  3. Type /* and click Create invalidation.

  4. Wait while the status is in progress.

  5. Reload the website, and you'll be able to see the changes.

0
Subscribe to my newsletter

Read articles from Arish Ahmad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arish Ahmad
Arish Ahmad

Final-year BTech student specializing in software development. Completed a Flutter internship and amassed three years of project experience, crafting Threads clone, Stream Arbiter, Ticketify, and Google Docs. Proficient in C++, having successfully solved 250+ LeetCode questions.