Emergent Software

Building a Serverless Full-Stack Application Using Azure Static Web Apps and Azure Functions

by Mike Allen

In This Blog

Azure's serverless platform provides developers with a powerful set of tools for building modern web applications without managing underlying infrastructure. At the core of this ecosystem are two key services: Azure Static Web Apps and Azure Functions. These services work together seamlessly to enable the development of full-stack applications that automatically scale based on demand while minimizing operational overhead.

Understanding Azure's Serverless Ecosystem

Azure Static Web Apps serves as the foundation for hosting your frontend application, supporting popular frameworks like React, Angular, Vue.js and Blazor WASM. Meanwhile, Azure Functions provides the serverless computing capability for your backend logic, allowing you to write focused pieces of code that respond to various triggers and events.

Development Process

Setting Up Your Development Environment

The development environment setup process has been streamlined to help teams get started quickly. A local accounting firm's development team recently transitioned their client portal to Azure's serverless architecture, beginning with a straightforward environment setup process. They found that Visual Studio Code with Azure Extensions provided an intuitive development experience, while Azure Functions Core Tools and the Static Web Apps CLI enabled efficient local testing and deployment.

Their development team, consisting of three .NET developers, established a consistent environment across their team by following a standardized setup process. Using Visual Studio Code as their primary integrated development environment (IDE), they leveraged Azure Extensions to streamline their workflow. Here's the approach they used to initialize their project:

 ```bash 

    npm create vite@latest my-app -- --template react-ts 

    func init api --typescript 

    swa init 

    ``` 

Building the Frontend Application

When building the frontend of your serverless application, structure your code to efficiently interact with backend Functions. A typical React component making authenticated API calls to an Azure Function might look like this:

```typescript 

const OrderList: React.FC = () => { 

  const [orders, setOrders] = useState<Order[]>([]); 

  const [loading, setLoading] = useState(true); 



  useEffect(() => { 

    const fetchOrders = async () => { 

      try { 

        const response = await fetch('/api/orders', { 

          headers: { 

            'x-functions-key': process.env.REACT_APP_FUNCTION_KEY 

          } 

        }); 

        const result = await response.json(); 

        setOrders(result); 

      } catch (error) { 

        console.error('Error fetching orders:', error); 

      } finally { 

        setLoading(false); 

      } 

    }; 

    fetchOrders(); 

  }, []); 



  if (loading) return <div>Loading orders...</div>; 



  return ( 

    <div className="order-list"> 

      {orders.map(order => ( 

        <div key={order.id} className="order-item"> 

          <h3>Order #{order.id}</h3> 

          <p>Customer: {order.customerName}</p> 

          <p>Total: ${order.totalAmount.toFixed(2)}</p> 

          <p>Status: {order.status}</p> 

        </div> 

      ))} 

    </div> 

  ); 

}; 

``` 

Implementing Serverless Backend Functions

Azure Functions excel at handling business-critical operations while maintaining code modularity and scalability. A property management company serving multiple residential communities demonstrates this capability well. They transformed their maintenance request system using Azure Functions to handle work order processing, resident notifications, and contractor scheduling. Their backend implementation showcases how Azure Functions can interface seamlessly with SQL Server databases while maintaining enterprise-grade security and performance. The following example demonstrates a typical order processing function they implemented:

```typescript 

import { AzureFunction, Context, HttpRequest } from "@azure/functions"; 

using Microsoft.Data.SqlClient; 

using System.Data; 



public static class OrderFunction 

{ 

    [FunctionName("CreateOrder")] 

    public static async Task<IActionResult> Run( 

        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req, 

        ILogger log) 

    { 

        try { 

            string connectionString = Environment.GetEnvironmentVariable("SqlConnectionString"); 

            var order = await JsonSerializer.DeserializeAsync<Order>(req.Body); 



            using (SqlConnection conn = new SqlConnection(connectionString)) 

            { 

                await conn.OpenAsync(); 

                using (SqlCommand cmd = new SqlCommand("sp_CreateOrder", conn)) 

                { 

                    cmd.CommandType = CommandType.StoredProcedure; 

                    cmd.Parameters.AddWithValue("@CustomerId", order.CustomerId); 

                    cmd.Parameters.AddWithValue("@OrderDate", order.OrderDate); 

                    cmd.Parameters.AddWithValue("@TotalAmount", order.TotalAmount); 



                    var newOrderId = await cmd.ExecuteScalarAsync(); 

                    return new OkObjectResult(new { OrderId = newOrderId }); 

                } 

            } 

        } 

        catch (Exception ex) 

        { 

            log.LogError(ex, "Error creating order"); 

            return new StatusCodeResult(500); 

        } 

    } 

} 



export default httpTrigger; 

``` 

Securing API Communication

Security is paramount in serverless applications. Azure Static Web Apps provides built-in authentication and authorization capabilities. Configure role-based access control (RBAC) using route definitions in your staticwebapp.config.json:

```json 

{ 

  "routes": [ 

    { 

      "route": "/api/admin/*", 

      "allowedRoles": ["administrator"] 

    }, 

    { 

      "route": "/api/data/*", 

      "allowedRoles": ["authenticated"] 

    } 

  ] 

} 

``` 

Automating Deployment with GitHub Actions

Azure Static Web Apps automatically creates a GitHub Actions workflow when you connect your repository. This workflow handles the build and deployment process for both your frontend and backend code. Here's an example workflow configuration:

```yaml 

name: Azure Static Web Apps CI/CD 

on: 

  push: 

    branches: 

      - main 

  pull_request: 

    types: [opened, synchronize, reopened, closed] 

    branches: 

      - main 



jobs: 

  build_and_deploy_job: 

    runs-on: ubuntu-latest 

    name: Build and Deploy Job 

    steps: 

      - uses: actions/checkout@v2 

      - name: Build And Deploy 

        id: builddeploy 

        uses: Azure/static-web-apps-deploy@v1 

        with: 

          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }} 

          repo_token: ${{ secrets.GITHUB_TOKEN }} 

          action: "upload" 

          app_location: "/"  

          api_location: "api" 

          output_location: "dist" 

``` 

Optimizing Costs in Production

One of the key benefits of serverless architecture is its consumption-based pricing model, which can significantly reduce operational costs for small and medium-sized businesses. By implementing proper caching strategies through Azure CDN and configuring appropriate Function timeouts and memory allocations, businesses can optimize their resource usage. The Azure Functions consumption plan ensures you only pay for actual usage, making it particularly attractive for applications with variable traffic patterns.

A medical supplies distributor rebuilt their ordering portal using Azure Static Web Apps and Functions, taking advantage of the built-in CDN services and SSL support. The serverless architecture allowed them to handle their busiest ordering periods efficiently without maintaining excess capacity during quieter times. This predictable scaling model helped them manage technology resources effectively while growing their business.

Real-world benefits can be substantial. Here at Emergent Software, our team worked with a regional insurance broker and transformed their client portal from traditional VMs to this serverless architecture, significantly reducing their infrastructure management overhead. They improved their application's ability to handle monthly policy renewal periods smoothly, while maintaining their existing database integration. The automated scaling capabilities of Azure Static Web Apps and Functions allowed them to focus on business growth rather than infrastructure management.

Read more about their experience here.

Conclusion

By following these practices and leveraging Azure's serverless platform, you can build scalable, cost-effective full-stack applications that are easy to maintain and deploy. The combination of Azure Static Web Apps and Azure Functions provides a robust foundation for modern web development, enabling teams to focus on building features rather than managing infrastructure.

Contact us today to discover how our services can help your business succeed. Our expert team provides tailored solutions to optimize your technology infrastructure, enhance productivity, and drive growth.

Frequently Asked Questions

Is Azure Static Web Apps serverless?

Yes, Azure Static Web Apps is a fully serverless hosting service that automatically manages scaling, infrastructure, and deployments. It integrates seamlessly with CI/CD workflows, allowing developers to quickly build and host modern web applications without worrying about server management. This makes it ideal for static sites and single-page applications with dynamic backend functionality.

Are Azure function apps serverless?

Yes, Azure Functions is a serverless compute service that automatically scales to meet demand and charges only for the resources used. It is designed for event-driven workloads, enabling developers to focus on writing business logic without managing servers. Its flexibility makes it ideal for tasks such as API development, data processing, and integration workflows.

What is the difference between Azure Functions and Azure function app?

Azure Functions are individual code snippets that execute specific tasks or business logic, while an Azure function app serves as a container to group and manage multiple related functions. The function app provides shared configurations, such as authentication, scaling settings, and environment variables, to streamline management of the functions it hosts. This separation allows for better organization and scalability of your applications.

About Emergent Software

Emergent Software offers a full set of software-based services from custom software development to ongoing system maintenance & support serving clients from all industries in the Twin Cities metro, greater Minnesota and throughout the country.

Learn more about our team.

Let's Talk About Your Project

Contact Us