Hello Thanos: static web app with azure function
We are going to create a plain HTML+JS static web app with an Azure Function as backend API, and by "plain" I mean no framework like React, Angular, or Vue, but will use Bootstrap and JQuery.
It will be a simple app with 2 input fields and 1 button. You will enter your name and last name and the app will say "hello" to Thanos and let you know if Thanos snapped you or not (Because you should not talk to the mad titan without permission).
We are going to use ReCaptcha V3 to prevent abuse and a bootstrap form with client-side validation before sending the data back to the azure function.
#1 Create the app from Visual Studio Code
#2 Get your Recaptcha keys
#3 Add code
index.html
Here is the code for index.html
Once you added the code, replace SITE_KEY with your own key.
Salute.cs
If you have not added an HTTP function, you can do it from VS Code command palette (F1). The function should be in a folder called "/api", in the root of the repository and side by side with our "/src" folder that contains the index.html page.
I named the function "Salute", copy and paste the function code below.
We use the Flurl library to call Google Recaptcha API, so add the Flurl NuGet package with:
dotnet add package Flurl.Http
Now open the local.settings.json file and add your secret key in there.
This settings file will be used during local development, once deployed to Azure, you will need to add the key to the application settings of the function as shown below:
That's it! You can push your changes and test your application in azure.
#4 Run & Debug locally
Run the function locally with Control+F5 or F5 if debugging, and from a terminal within VS Code run:
swa start src --api api
This will start running the static web app and you will get an output similar to this:
#5 Add a custom domain
By default, Azure creates assign URLs for your app as subdomains of "azurestaticsites.net", which are not easy to remember. If you own a domain you can add a custom domain, open the tab for "Custom domains"
In order to validate the domain is yours, you can use CNAME validation, by going to your DNS administration and set a CNAME (like "thanos" in my case) to the value of the current app URL, minus the "https://" part.
After the domain is pointing to the app and ready, go back to the Recaptcha configuration and add your new domain. Here is a capture of https://thanos.lpaneque.com.
#6 Play with it
Now is your time to modify this and play a bit:
- My "snap" function was lazy. Experiment with different approaches.
- Try other ways to build the payload and call the API
- Avoid bootstrap!?!? :)
- Use Recaptcha V2 instead of V3
Here is the public repository for the code https://github.com/lpaneque/salute-thanos
Comments