Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 57 ยท Real-World Projects

Project: Static Web App with a Serverless API

Build a static front end with an Azure Functions API: Static Web Apps, GitHub deployment, routes and auth rules, a custom domain, and a local stand-in.

In this project you will design and ship a small but complete web application: a static front end (HTML, CSS and JavaScript) that talks to a serverless API, with sign-in, access rules, a custom domain and automatic deployment from GitHub. It is the cheapest way to run a real product on Azure, because there is no server to patch and a free tier exists for small sites.

The service that ties it together is Azure Static Web Apps (SWA). It hosts your files on a global content network, runs an API built from Azure Functions next to them, provides built-in authentication, and sets up a GitHub Actions workflow that deploys every push. The real service needs an Azure account and a GitHub repository, so all Azure commands and configuration below are read-only. The runnable parts are Node.js stand-ins that reproduce the routing, sign-in and API logic locally, so you can test the behavior of your configuration without Azure. Earlier lessons give the background: Azure Functions, Microsoft Entra ID and CI/CD with GitHub Actions and Azure DevOps.

What we are building

A small "task list" app. Visitors can read a public page, but only signed-in users can see and edit their own tasks, and only an administrator can call an admin endpoint.

flowchart LR
    B["Browser"] --> E["Static Web Apps edge<br/>(static files + routing rules)"]
    E -->|"/ and /app/*"| F["Static files<br/>from the build"]
    E -->|"/api/*"| A["Functions API<br/>(managed or linked)"]
    E -->|"/.auth/*"| AU["Built-in authentication"]
    G["GitHub repo"] -->|"push triggers workflow"| W["GitHub Actions build"]
    W -->|"deploys"| E

One public address serves the files, the API and the sign-in endpoints, so the browser never needs cross-origin requests.

Because the API lives under the same address (/api/...), you avoid CORS configuration: the front end simply calls fetch("/api/todos").

Project layout

TEXT
my-swa/
  index.html            (public home page)
  app/index.html        (signed-in task list)
  src/main.js
  staticwebapp.config.json
  api/
    package.json
    host.json
    src/functions/todos.js
  .github/workflows/azure-static-web-apps.yml

The settings that matter are three folders: app_location (where the front-end source is), api_location (the Functions project) and output_location (the build output, empty for plain files).

The API: an Azure Functions project

In the Node.js programming model, a function registers itself with the app object from the @azure/functions package. The code below is read-only: it needs the Functions runtime to run.

JavaScript
const { app } = require("@azure/functions");

const tasks = new Map(); // demo only: real apps use a database (see the next projects)

function currentUser(request) {
  const header = request.headers.get("x-ms-client-principal");
  if (!header) return null;
  return JSON.parse(Buffer.from(header, "base64").toString("utf8"));
}

app.http("todos", {
  methods: ["GET", "POST"],
  authLevel: "anonymous",
  route: "todos",
  handler: async (request, context) => {
    const user = currentUser(request);
    if (!user) return { status: 401, jsonBody: { error: "sign in first" } };

    const mine = tasks.get(user.userId) ?? [];
    if (request.method === "GET") return { jsonBody: mine };

    const body = await request.json();
    mine.push({ id: mine.length + 1, title: String(body.title ?? "").slice(0, 100) });
    tasks.set(user.userId, mine);
    context.log(`task added for ${user.userDetails}`);
    return { status: 201, jsonBody: mine };
  },
});

Notes on this code:

  • authLevel: "anonymous" is right here because Static Web Apps does the authentication before the request reaches your function. You do not use function keys behind SWA.
  • When a user is signed in, SWA adds the x-ms-client-principal header: a Base64-encoded JSON object with identityProvider, userId, userDetails (the display name or email) and userRoles. Your code decodes it. Treat it as trusted only because the request came through SWA; never expose the function app so that callers can reach it directly with a forged header.
  • With the managed functions option, the API is deployed together with the site and is limited to HTTP triggers. If you need timers, queues or private networking, link your own Function App instead (the "bring your own functions" option), which needs a paid SWA plan.
  • The in-memory Map loses its data whenever an instance restarts or a second instance appears. It is only there to keep the example short; Project: Containerized API with a Database and Azure Cosmos DB show real storage.

Routing and access rules: staticwebapp.config.json

One JSON file at the root of the app (or in the build output) controls routing, authorization, fallback pages and headers:

JSON
{
  "routes": [
    { "route": "/api/admin/*", "allowedRoles": ["administrator"] },
    { "route": "/api/todos*", "allowedRoles": ["authenticated"] },
    { "route": "/app/*", "allowedRoles": ["authenticated"] },
    { "route": "/login", "redirect": "/.auth/login/github" },
    { "route": "/logout", "redirect": "/.auth/logout" }
  ],
  "navigationFallback": {
    "rewrite": "/index.html",
    "exclude": ["/api/*", "/images/*.{png,jpg,gif}", "/*.{css,js}"]
  },
  "responseOverrides": {
    "401": { "statusCode": 302, "redirect": "/login" }
  },
  "globalHeaders": {
    "X-Content-Type-Options": "nosniff"
  }
}

How the rules work:

  • Routes are evaluated in order, and the first match wins, so put specific rules before general ones.
  • Every visitor has the built-in role anonymous; signed-in users also have authenticated. Any other role (such as administrator) is a custom role that you assign by sending invitations from the portal, or by an API function that returns roles. An anonymous visitor who requests a protected route gets 401; a signed-in user who lacks the role gets 403.
  • navigationFallback makes single-page apps work: an unknown path such as /app/settings returns /index.html so the client-side router can take over. The exclude list keeps API calls and static assets from being rewritten.
  • responseOverrides turns the 401 into a redirect to the login page, so a visitor is sent to sign in instead of seeing an error.
  • The built-in sign-in endpoints live under /.auth/: /.auth/login/github, /.auth/login/aad for Microsoft Entra ID, /.auth/logout, and /.auth/me, which returns the current user as JSON. Pre-configured providers such as GitHub and Entra ID work without any setup on the Free plan; custom providers need the Standard plan.

Running the logic locally: a stand-in

You cannot run Static Web Apps on this site, but you can run its rules. The program below starts three tiny pieces on the local loopback address of the sandbox: a "function app" with plain handlers, a "gateway" that applies a routes file like the one above (first match wins, 401 vs 403, a /.auth/me endpoint, the x-ms-client-principal header, a navigation fallback), and a "front end" that makes fetch calls exactly as browser code would. It is a stand-in: the real SWA edge, token handling and cookies are far more elaborate, and sign-in here is faked with a user name.

Node.js A local stand-in for Static Web Apps routing, auth and API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output against the config. The anonymous visitor reaches the public page, but the /app/ path and the API return 401. Alice gets 403 on the admin route because she is authenticated but lacks the administrator role. A path that matches no file, such as /docs/anything, falls back to /index.html so a single-page app can handle it, while an unknown /api/... path is not rewritten because of the exclude rule. You can edit the config object and watch the status codes change: that is the cheapest way to design access rules before deploying.

Testing the front-end calls

A front end should never trust itself: the check that matters is on the server side, so your function must reject bad input even when the page's JavaScript is correct. The second stand-in is the function logic alone, called the way a browser would, including mistakes a real user (or an attacker) can make.

Node.js Call the function logic with good and bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Every branch returns a clear status code and a short message. That discipline (validate, never trust the client, return 4xx for caller mistakes) matters more than any framework.

Creating the resource and the deployment

With a GitHub repository ready, one command creates the Static Web App and commits a workflow file to your repository (read-only here):

Terminal
az group create --name rg-swa --location westeurope

az staticwebapp create \
  --name swa-tasks-demo \
  --resource-group rg-swa \
  --source https://github.com/<your-account>/my-swa \
  --branch main \
  --app-location "/" \
  --api-location "api" \
  --output-location "" \
  --login-with-github

The generated workflow builds on every push to main, deploys to production, and for every pull request also creates a temporary preview environment with its own URL, which Azure deletes when the pull request closes. The key part of the workflow looks like this:

YAML
- 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: ""

The deployment token is stored as a GitHub secret. It can publish to this one site, so keep it out of the repository and rotate it if it leaks. Environment settings for the API (connection details, feature flags) are set on the Static Web App itself and reach your functions as environment variables, as in App Service and Web Apps.

Custom domain and HTTPS

Every site gets a default *.azurestaticapps.net address. To use your own domain:

  1. For a subdomain such as www.example.com, create a CNAME record at your DNS provider pointing to the default address (see DNS and Traffic Manager).
  2. For a root (apex) domain such as example.com, which cannot have a CNAME, either host the zone in Azure DNS and use an alias record, or validate with a TXT record where your DNS provider supports it.
  3. Register the name with the service. Azure validates ownership and issues and renews a free TLS certificate for you.
Terminal
az staticwebapp hostname set --name swa-tasks-demo --resource-group rg-swa \
  --hostname www.example.com

DNS changes can take time to propagate, so wait for the validation to complete before you retry. HTTPS is enforced; there is no certificate to buy or renew by hand.

Project checklist

  • Public pages work for anonymous visitors, and protected routes return 401 or 403 as designed.
  • The API validates input, reads the user from x-ms-client-principal, and stores data in a real database, not memory.
  • staticwebapp.config.json has a navigation fallback with an exclude list, and security headers.
  • Secrets are in app settings or Key Vault, never in the repository (see Key Vault).
  • A pull request opens a preview environment, and merging to main updates production.
  • Cost: on the Free plan the site costs nothing for small traffic; set a budget alert anyway (see Pricing, Cost Management and Budgets).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can the front end call fetch('/api/todos') without any CORS configuration?

    Static Web Apps routes /api/* to the Functions backend behind the same host name, so the browser sees one origin and does not send cross-origin requests.
  2. 2. A signed-in user without the administrator role requests a route that requires it. What status code does Static Web Apps return?

    401 is for visitors who are not authenticated at all. An authenticated user who lacks the required role gets 403.
  3. 3. How does a function learn who the signed-in user is?

    SWA authenticates the user and passes a Base64-encoded principal to the API. This is safe only because requests come through SWA.
  4. 4. What does navigationFallback do for a single-page app?

    Without the fallback, refreshing on /app/settings would return 404 from the file host. With it, index.html is served and the router renders the right view.
  5. 5. Why is an in-memory Map a bad place to keep tasks in a real function app?

    Functions instances come and go and may run in parallel, so state must live in a database or storage service.

Summary

  • Azure Static Web Apps hosts static files, a Functions API and built-in sign-in under one address, and deploys from GitHub with preview environments for pull requests.
  • staticwebapp.config.json holds ordered route rules, role requirements (401 for anonymous, 403 for missing roles), navigation fallback and headers.
  • Functions behind SWA receive the signed-in user in the x-ms-client-principal header and should use authLevel: "anonymous".
  • Always validate input on the server and keep data in a real store.
  • A custom domain needs a DNS record and validation; the TLS certificate is free and renewed automatically.
  • The local stand-ins reproduce the rules' behavior, not the real edge network, so verify the final result in a deployed preview.

Next: Project: Event-Driven Image Processing.