Jamstack: Azure Serverless Functions App With React

Jamstack: Azure Serverless Function App With React

Matt McCandless Architecture, Azure, Development Technologies, Node.js, React Leave a Comment

A new trend of creating applications is emerging called Jamstack. No, this isn’t slapping together your favorite flavor of jelly (grape is the best) with peanut butter and two pieces of bread. The intent is an architecture that is faster, more secure, and easier to scale. It focuses on pre-rending and decoupling. This way, the solutions created are more reliable and resilient than before.

Pre-rendering comes by the way of using a static website via a CDN for high availability and security. No more serving your React app via web server like we’ve become accustomed to. It reduces cost and complexity by eliminating the regular maintenance and configuration of traditional servers.

Also, the idea of APIs and the ability to move them to things like Serverless functions creates more cost savings, elimination of traditional servers, and use of features only when they are requested. For more information, check out the Serverless website.

Making a lovely PB&J


Let’s consider bread to be the cloud provider of your choice. For today’s example, we will be using Azure. There are many flavors of bread: AWS, Azure, GCP, and others (all with their own tasty bits and options), but really, it’s just the bread.
The good stuff is what’s in the middle.

Peanut Butter

Here, we are going to look at the Serverless function apps in Azure as our peanut butter. Peanut butter can be complex. Whether it be creamy, crunchy, whipped, or natural – they all serve a purpose, so it can be complicated to choose what we want.
Personally, I think crunchy peanut butter gives the sandwich some texture and is the way to go. At any rate, our peanut butter Serverless function app will provide the more complex part of our code. We will set up our backend code to provide our endpoints – login, user listing, and updating the role.

So, how do we get this all working? We create a regular Node.js application. Time to code!

Coding the Peanut Butter

First, we will set up Serverless on our local machine. Using the link mentioned above, we can follow the steps to install Serverless on our local machine. This will allow us to create, edit, and run the code locally but in an “offline” mode. This way, we can debug things locally before we ever push anything up to Azure.

First, we need to install the serverless tools locally.

npm i -g serverless

Next, create a new function app.

servless create -t azure-nodejs -p <appName>

After it is done, change into that directory and run.

npm install

Once you have done this, let’s take a closer look at the serverless.yml file.

service: <serviceName>
# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
frameworkVersion: '3'
  name: azure
  region: Central US
  runtime: nodejs12
  resourceGroup: <resourceGroup>
  # os: windows  # windows is default, linux is available
  # prefix: "sample"  # prefix of generated resource name
  # subscriptionId:
  # stage: dev
  # type: premium  # premium azure functions
  environment: # these will be created as application settings
    VARIABLE_FOO: 'foo'

The service name is whatever you’d like to name it, but you will leave the rest the same. Name a resource group or use one that you already have defined. By default, Windows is the OS of choice.

Further down, let’s take a look at the function mapping. All it’s really doing is mapping where your function lives, the methods accepted, the authorization level to use it, and the type of event it is.

    handler: src/handlers/login.login
      - http: true
          - POST
        authLevel: anonymous # can also be `function` or `admin`

From here, you would write your code to authenticate your user. This article won’t get into specifics, as there are many ways in which you can do so. What we will focus is on how to handle logins from a Serverless setting.

Create your login handler like the example below, and import anything that you need to. The key is to return the response in the context.

const login = require("../login");
module.exports.login = async function (context, req) {
  context.log('JavaScript HTTP trigger function login request.');
  context.res.headers = { "Content-Type": "application/json" };
  context.res = await login(req, context.res);

In this example, the original login code that we used on a traditional implementation was left intact. In this approach, we can, if need be, revert to a traditional setup with minimal effort.

To test locally now, use the following command.

serverless offline

This will run the Serverless functions locally and list out the available endpoints and the URLs to call them.

Functions:        login: [POST] http://localhost:7071/api/login

Now your function is available to test via Postman or other tools.

Deploy the Peanut Butter

This is where things get sticky. Deploying to Azure isn’t extremely clear using the Serverless tools. This article assumes you have an Azure account already. Be sure that you have the proper permissions to the subscription and write permissions.

Avoid getting peanut butter in your hair. Make sure these are all in place before running any of this via the CLI tool. Instead of regurgitating the steps, I advise you to visit this link and follow the steps.

Once all of that is set up, then run the following command.

serverless deploy

If all goes well, it will zip up your app and deploy it to Azure. Then, you can pop over to Azure Function Apps and look at it there. Once it is running, you can use Postman to try your login or even use the test/run option available.

Jelly Time: Grape, of Course!

It’s jelly time, and in my opinion, there’s only one flavor worth using: grape. By grape, I mean a React-based web application. A lot of times, people forget that React builds a static output that can actually just be hosted on any web server. This allows us to take our application and host it via a CDN.

We won’t get into specifics of how to host in this article. Azure, AWS, and GCP all have different flavors of hosting a CDN where we can add our static files to be hosted. This allows for a scalable and highly available static website with minimal setup and configuration.

All you need to do is create your frontend application like you normally do with a login, lists, forms, etc. The only difference is that now you point your API calls to the Serverless calls that were listed above.

PBJ Perfection

Hopefully, you can see that this approach is fairly simple to carry out. You don’t need to change how you develop a whole lot. The key is how you are going to host and deploy your functions.

Your backend APIs aren’t eating up computing time and are much more shareable now. There are some studies that suggest that around 80% of computing time is idle. In a Serverless environment, you only use compute time when needed.

A CDN-hosted website is a prime way to create a highly scalable and available website application with little to no overhead. It is almost like stealing the jelly for your sandwich.

Hopefully, you enjoyed this tasty treat and are ready to start making your own Jamstack solutions! If you enjoyed this snack, make sure you check out the others on the Keyhole Dev Blog.

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments