How to Create Static Web Apps in Azure for Beginners

A recent project had me looking into solutions for web forms that could be provisioned separately from a primary website. I was looking for possible ways to limit exposure from web bots and DDoS attacks above and beyond traditional means. My investigation led me to Azure Static Web Apps.

As defined by Microsoft, an Azure Static Web App is a service that automatically builds and deploys full stack web applications to Azure from a code repository such as GitHub or Azure DevOps. Built from libraries and web frameworks such as Angular, React, Svelte, Vue or Blazor where server side rendering is not required, these applications include HTML, CSS, JavaScript and image assets that make up the application.

I am not familiar with any of these libraries or frameworks, rather the majority of my web development was done using PHP which is not supported. Fortunately Static Web Apps can be developed using just standard JavaScript and with some creativity and leveraging API endpoints, I figured it may serve my purpose well.

To my surprise, or more likely my limited understanding of the underlining technology and techniques, I found this to be a bit of a stretch and challenged me. I struggled initially with reacquainting myself with client side programming such as JavaScript, then getting my code to replicate and synchronize between my GitHib repository and computer and finally getting the Azure pipeline to deploy my branch without failing. Oh and I did not mention, I am now a die-hard fan of Linux, specifically Ubuntu, and have been using and familiarizing myself with this environment in parallel.

I visited a number of channels on YouTube, read articles and essentially hacked my way through to getting my first Static Web Apps published. I have a lot to learn but feel I am well on my way and looking forward to the journey.

I found there was a limited number of how-to articles for the newcomer. This blog post may be of interest and of use to anyone else starting out. This is a first in a series I am going to create to demonstrate the usefulness of a Static Web App. Let me know what you think in the comments and if you have any questions or recommendations, I’d appreciate hearing from you.

Creating and Deploying your first Static Web App

This is the first instalment of a Static Web App Series. In this instalment, I will demonstrate how to:

  • Create a Code Repository in GitHub

  • Clone a Git Code Repository

  • Create a HTTP Trigger Function

  • Install Supporting Node Modules

  • Parse MultiPart Form Data

  • Commit Changes to GitHub Code Repository

  • Create Static Web App in Microsoft Azure

Create a Code Repository in GitHub

Git is a DevOps tool used for source code management. It is a free and open-source version control system used to handle small to very large projects efficiently. Git is used to track changes in the source code, enabling multiple developers to work together on non-linear development. Git is used as a deployment source for Azure Static Web Apps.

To create a Code Repository:

  • From GitHub, login and create a new private code repository by clicking on the New button

    • Repository Name: demo

    • Description: My first demo repository

    • Private: yes

    • Add a README.md: yes

    • Add .gitignore: yes Visual Studio. This specifies files intentionally untracked by Git.

  • Click Create Repository when done

Clone a Git Code Repository

The process to clone a Git code repository will allow you to work on the project code files in your own DevOps environment such as Visual Studio Code.

To clone a code repository locally:

  • Launch Visual Studio Code

    • From the Getting Started page, click Clone Git Repository

    • From the Clone from GitHub pop-up, enter or select your Repository URL

    • Select a target folder on your local computer to clone the repository to

      • i.e. home/projects

    • If applicable, choose Allow when prompted that the extension ‘GitHub’ wants to sign in to GitHub

    • Choose Open when prompted to open the cloned repository

Create a HTTP Trigger Function

With the code repository cloned successfully, from Visual Studio Code

  • create a new folder named api at the root of your project

  • press SHIFT+ALT+A to open the Azure workspace pane

  • from the local workspace, click the lightning bolt icon to create a HTTP Function

  • browse to the api folder you created above

  • select JavaScript as the language

  • select HTTP trigger as the template

  • enter contact as the function name

  • select Anonymous as the Authorization Level

The function project has been created successfully.

Install Supporting Node Modules

Three supporting Node modules will be installed:

  • MDB Bootstrap: MDB Bootstrap is a free, open source front-end CSS framework and toolkit for the creation of websites and web apps.

  • Node-Fetch: A light-weight module that brings Fetch API to node.js.

  • @anzp/azure-function-multipart: A module to parse multipart/form-data on Azure Functions.

Install MDB Bootstrap

  • From the project api folder, install MDB Bootstrap by issuing the following command

    • .../demo/api$ npm i mdb-ui-kit

    • From .../demo/api/node_modules/mdb-ui-kit, copy all the files excluding package.json and README.md to the project root .../demo

    • From the root of your project .../demo, copy index.html as error.html and success.html

    • From Visual Studio Code open index.html and make the following changes:

      • remove content between <-- Start your project here --> and <-- End your project here -->

      • add the following code:

<div class="container mt-5" style="width: 720px;">
<h2>Contact Us</h2>

<form>
<!-- Name input -->
<div class="form-outline mb-4">
<input type="text" id="fldName" name="fldName" class="form-control" />
<label class="form-label" for="fldName">Name</label>
</div>

<!-- Email input -->
<div class="form-outline mb-4">
<input type="email" id="fldEmailAddr" name="fldEmailAddr" class="form-control" />
<label class="form-label" for="fldEmailAddr">Email address</label>
</div>

<!-- Message input -->
<div class="form-outline mb-4">
<textarea class="form-control" id="fldMessage" name="fldMessage" rows="4"></textarea>
<label class="form-label" for="fldMessage">Message</label>
</div>

<!-- Checkbox -->
<div class="form-check d-flex justify-content-right mb-4">
<input class="form-check-input me-2" type="checkbox" value="" id="fldCC" name="fldCC" checked />
<label class="form-check-label" for="fldCC">
Send me a copy of this message
</label>
</div>

<!-- Submit button -->
<button type="submit" class="btn btn-primary mb-4">Send</button>
</form>
</div>

Install Node-Fetch and Azure-Function-MultiPart

  • From the project api folder, install Node Fetch v2. This is required to fetch a post response that will be featured in the next instalment.

    .../demo/api$ npm i node-fetch@2

  • From the project api folder, install azure-function-multipart. This is required to retrieve and parse the post response form fields submitted. If files are also transmitted, this module will handle them as well.

    .../demo/api$ npm i @anzp/azure-function-multipart

Parse MultiPart Form Data

  • From Visual Studio, open index.html at the project root. Amend <form> to include the following:

    • id: contact

    • action: /api/contact

    • method: post

    • enctype: application/x-www-form-urlencoded

<form id=”contact” action=”api/contact” method=”post” enctype=”application/x-www-form-urlencoded”>
  • From a Terminal window, navigate to the project root folder and issue the following command to start the Azure Static Web Apps Emulator:

    .../demo/api$swa start –api-location api

  • From your browser, navigate to http://localhost:4280 and test submitting the form. You should receive a message similar to the following in the browser:

This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.

  • From Visual Studio Code, amend the contact api index.js and include the following:

const parseMultipartFormData = require("@anzp/azure-function-multipart")
  .default;

const fetch = require("node-fetch");

module.exports = async function (context, req) {
    context.log("HTTP trigger 'contact' function processed a request.");

    const { fields, files } = await parseMultipartFormData(req);

    const responseMessage = fields;

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}
  • The above code will parse the POST response and store the field name/value pairs in the variable fields and output its content to the browser.

  • Test the site via emulator:

    http://localhost:4280

  • From Visual Studio Code, amend the contact api index.js, replacing context.res = {... } with:

var fldCC = false;

for (var i = 0; i < fields.length; i++) {
   switch (fields[i].name) {
      case "fldName":
         var fldName = fields[i].value;
         break;
      case "fldEmailAddr":
         var fldEmailAddr = fields[i].value;
         break;
      case "fldMessage":
         var fldMessage = fields[i].value;
         break;
      case "fldCC":
         var fldCC = true;
         break;
   }
}

console.log("fldName: " + fldName);
console.log("fldEmailAddr: " + fldEmailAddr);
console.log("fldMessage: " + fldMessage);
console.log("fldCC: " + fldCC);
  • The above code will iterate over each response name/value pair and store the value into its own variable and output its value to the console.

  • NOTE: as fldCC is a checkbox, its existence in the POST response will only occur when the checkbox is checked. However, there is no associated value. When it exists, we’ll assign a TRUE value, otherwise it will be assigned a FALSE value.

  • Save the contact api index.js file and test the site via emulator:

    http://localhost:4280

  • From Visual Studio Code, amend the contact api index.js, replacing the console.log line items with:

// Redirect a page
context.res = { status: 302, headers: { "location": "/success.html" } }
  • amend the success.html, remove content between <-- Start your project here --> and <-- End your project here --> and add the following:

    <div class="container">
      <div class="d-flex justify-content-center align-items-center" style="height: 100vh">
        <h2>Thank you for your submission, it has been received successfully.</h2>
      </div>
    </div>

Commit Changes to GitHub Code Repository

When complete and all tests completed successfully, commit and sync changes back to the Git Code Repository

  • From GitHub, view your existing demo repository. Note the Code only contains the gitignore and README.md files.

  • From Visual Studio Code, access the Source Control CTRL+SHIFT+ G to view pending changes

  • Click on the Commit button

  • When prompted "Would you like to stage all your changes and commit them directly?”, click Yes

  • Under COMMIT_EDITMSG, enter Initial Commit and click the Accept and Commit checkmark.

  • When prompted "Do you want to save the changes you made to COMMIT_EDITMSG”, click Save.

  • Click Sync Changes

  • When prompted "This action will pull and push commits from and to "origin/main”, click OK.

  • From GitHub, view your existing demo repository. Note all the files have been synchronized successfully.

Create Static Web App in Microsoft Azure

  • From your Azure Portal, access Static Web Apps

  • Click Create to create a new Static Web App

  • Under Project Details, select an existing Resource Group or enter a new Resource Group to be created

  • Under Static Web App Details, enter the Name demo

  • Under Deployment Details, from Organization choose your organization name

  • from Repository, choose demo

  • From Branch, choose main

  • Under Build Details, from Build Presets choose Custom

  • Leave App Location default to /

  • From API location, enter api

  • Leave Output Location empty

  • Click Review and Create

  • Click Create

NOTE: The deployment has begun and will take a few minutes to complete. You can monitor the deployment progress from your GitHub repo under Actions.

Once completed successfully, click on the Go to resource button.

From your GitHub demo repository, access the Action tab to view the deployment workflow progress. Once complete, from the Azure SWA Overview Page, click the URL to verify and test your new form.

Next Instalment

We will incorporate Google reCaptcha

Comments

Popular Posts