Skip to content

Free Website Hosting with Azure

Last week, I talked about hosting your static website with Azure Static Web Apps. Today, I will extend this example using a free Cosmos DB for the website data and Azure Functions to retrieve them. This approach will give you free website hosting and global distribution of your website.
You can find the demo code of the Azure Static Web App here and the code for the Azure Functions here.

Azure Cosmos DB

Cosmos DB is a high-end NoSQL database that offers incredible speed and global distribution. Cosmos DB is way too comprehensive to talk about all the features here. I am using it because it offers a free tier which should give you enough compute resources for a static website.

Create a Free Tier Cosmos DB

In the Azure Portal search for Azure Cosmos DB, select it and click on Create or select Azure Cosmos DB from the left panel and then click on Create Azure Cosmos DB account.

Create a new Cosmos DB
Create a new Cosmos DB

On the next page, select a resource group and make sure that the Free Tier Discount is applied. After filling out all information click on Review + create.

Set up the free tier of the Cosmos DB
Set up the free tier of the Cosmos DB

The deployment will take around ten minutes.

Add Data to the Cosmos Database

After the deployment is finished, navigate to the Data Explorer tab in your Cosmos DB account. Click on New Container and a new tab is opened on the right side. There enter a Database id, Container id, and Partition key and click OK.

Create a new database and container in the Azure Cosmos DB
Create a new database and container in the Azure Cosmos DB

Open the newly created database and the Products container and click on New Item. This opens an editor where you can add your products as JSON.

Add data to the container for your Free Website Hosting
Add data to the container

Again, Azure Cosmos DB is too big to go into any details in this post. For the free hosting of your website, it is only important to know that I added the data for the website into the database. The next step is to edit the Azure Function so it doesn’t return a static list but uses the Azure Cosmos DB instead.

Using an Azure Function to read Data from Cosmos DB

I am re-using the Azure Function from my last post. If you don’t have any yet, create a new Azure Function with an HTTP trigger. To connect to the Cosmos DB, I am installing the Microsoft.Azure.Cosmos NuGet package and create a private variable with which I will access the data.

private static Container _container;

Next, I create a method that will create a connection to the container in the database.

 private static async Task SetUpDatabaseConnection()
        {
            var cosmosClient = new CosmosClient("https://staticwebappdemocosmosdb.documents.azure.com:443",
                "qCEzM0xsroClwt54p7aICi3yBa0bWn4rAaiQNiIPp74LHcA7Wbm9D1iHszfaJ0icRcTwiW74KbMbn4WrMqnyfg==", new CosmosClientOptions());
            Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync("StaticWebAppDatabase");
            _container = await database.CreateContainerIfNotExistsAsync("Products", "/Name", 400);
        }

To connect to the Azure Cosmos DB container, you have to enter your URI and primary key. You can find them in the Keys tab of your Cosmos DB account.

Get the Uri and Primary Key of the Cosmos DB for your Free Website Hosting
Get the Uri and Primary Key of the Cosmos DB

In the next method, I am creating an iterator that will return all my products. I add these products to a list and return the list. You can filter the query by providing a filter statement in the GetItemQueryIterator method.

 private static async Task<List<Product>> GetAllProducts()
        {
            var feedIterator = _container.GetItemQueryIterator<Product>();
            var products = new List<Product>();

            while (feedIterator.HasMoreResults)
            {
                foreach (var item in await feedIterator.ReadNextAsync())
                {
                    {
                        products.Add(item);
                    }
                }
            }

            return products;
        }

In the Run method of the Azure Function, I am calling both methods and convert the list to a JSON object before returning it.

[FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {
            await SetUpDatabaseConnection();

            return new OkObjectResult(JsonConvert.SerializeObject(await GetAllProducts()));
        }

I keep the Product class as it is.

public class Product
    {
        public string Name { get; set; }

        public decimal Price { get; set; }

        public string Description { get; set; }
    }

Start the Azure Function, enter the URL displayed in the command line and you will see your previously entered data.

Test the Azure Function locally
Test the Azure Function locally

The last step is to deploy the Azure Function. In my last post, I already imported the publish profile. Since nothing has changed, I can right-click on my project, select Publish and then Publish again.

Publish the Azure Function for your Free Website Hosting
Publish the Azure Function

Testing the Free Website Hosting Implementation

Open the URL of your Azure Static Web App and the data from the Cosmos DB will be displayed.

The data from the database is displayed in the React app
The data from the database is displayed in the React app

Conclusion

Today, I showed how to use Azure Cosmos DB, Azure Functions and Azure Static Web Apps to achieve free website hosting and also a global distribution of the website. You can find the demo code of the Azure Static Web App here and the code for the Azure Functions here.

Published inCloud

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    RSS
    Follow by Email
    LinkedIn
    Share