How to deploy to Azure Static Web App with database connection in Svelte using GitHub workflow?

113 views Asked by At

I have created a Svelte skeleton web application and a Cosmos NoSQL database. I installed the swa CLI tool using npm install -g @azure/static-web-apps-cli command. Furthermore, I was following the Azure Cosmos DB Tutorials under the Database connection section in the Azure Static Web Apps (SWA) Documentation.

I created the sample data successfully on Azure CosmosDB according to the documentation. Then, I added the list API to test the deployment. This is the content of the src/routes/+page.svelte home page:

<script>
  async function list() {
    const query = `
      {
        people {
          items {
            id
            Name
          }
        }
      }`;

    const endpoint = '/data-api/graphql';
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query: query })
    });
    const result = await response.json();
    console.table(result.data.people.items);
  }
</script>

<h1>Static Web Apps with Database Connections</h1>
<blockquote>Open the console in the browser developer tools to see the API responses.</blockquote>
<div>
  <button id="list" on:click={list}>List</button>
</div>

Configuration setup

I set the database connection string environment variable:

export DATABASE_CONNECTION_STRING='<YOUR_CONNECTION_STRING>'

I initialized the SWA configuration with the swa init command and the configuration files under the /swa-db-connections folder are the following:

  • staticwebapp.database.config.json:
{
  "$schema": "https://github.com/Azure/data-api-builder/releases/download/v0.9.7/dab.draft.schema.json",
  "data-source": {
    "database-type": "cosmosdb_nosql",
    "connection-string": "@env('DATABASE_CONNECTION_STRING')",
    "options": {
      "database": "MyTestPersonDatabase",
      "schema": "staticwebapp.database.schema.gql"
    }
  },
  "runtime": {
    "graphql": {
      "enabled": true,
      "path": "/graphql",
      "allow-introspection": true
    },
    "host": {
      "cors": {
        "origins": ["http://localhost:4280"],
        "allow-credentials": false
      },
      "authentication": {
        "provider": "StaticWebApps"
      },
      "mode": "production"
    }
  },
  "entities": {
    "Person": {
      "source": "MyTestPersonContainer",
      "permissions": [
        {
          "actions": ["*"],
          "role": "anonymous"
        }
      ]
    }
  }
}
  • staticwebapp.database.schema.gql:
type Person @model {
  id: ID
  Name: String
}

This is the content of the /svelte.config.js file:

import adapter from '@sveltejs/adapter-auto';

export default {
  kit: {
    adapter: adapter()
  }
};

Page not Found Error

When I would like to emulate the Static Web App on the /src folder with the swa start ./src --data-api-location swa-db-connections command, I got the following output:

[dataApi] Information: Microsoft.DataApiBuilder 0.9.7+e560142426d1c080b9fd7b7fabff51a276f6bf61
[dataApi] Information: User provided config file: staticwebapp.database.config.json
[dataApi] Loading config file from staticwebapp.database.config.json.
[dataApi] Information: Loaded config file: staticwebapp.database.config.json
[dataApi] Information: Setting default minimum LogLevel: Error for Production mode.
[dataApi] Starting the runtime engine...
[swa] 
[swa] Using workflow file:
[swa]   C:\Users\z0190983\ws\personal\pomodoro-svelte\.github\workflows\azure-static-web-apps.yml
[swa] 
[swa] Serving static content:
[swa]   C:\Users\z0190983\ws\personal\pomodoro-svelte\src
[swa]
[swa] Azure Static Web Apps emulator started at http://localhost:4280. Press CTRL+C to exit.
[swa]
[swa]
[dataApi] Redirecting to https is disabled.
[dataApi] Loading config file from staticwebapp.database.config.json.
[dataApi] info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[63]
[dataApi]       User profile is available. Using 'C:\Users\z0190983\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
[dataApi] info: Microsoft.Hosting.Lifetime[14]
[dataApi]       Now listening on: http://localhost:5000
[dataApi] info: Microsoft.Hosting.Lifetime[14]
[dataApi]       Now listening on: https://localhost:5001
[dataApi] info: Microsoft.Hosting.Lifetime[0]
[dataApi]       Application started. Press Ctrl+C to shut down.
[dataApi] info: Microsoft.Hosting.Lifetime[0]
[dataApi]       Hosting environment: Production
[dataApi] info: Microsoft.Hosting.Lifetime[0]
[dataApi]       Content root path: C:\Users\z0190983\ws\personal\pomodoro-svelte\swa-db-connections
[swa] GET http://localhost:4280/404.html - 404

Somehow the Svelte web application could not be found and a 404: Not Found page was displayed:

enter image description here

Questions:

  • How to emulate the Svelte application using the swa CLI tool locally?
  • What is the minimal GitHub workflow file to deploy the web application automatically?
1

There are 1 answers

3
Péter Szilvási On BEST ANSWER

Emulating Static Web App locally

First, install the static site generator adapter in SvelteKit. Install it via npm install -D @sveltejs/adapter-static and then configure the svelte.config.js file for the production build:

import adapter from '@sveltejs/adapter-static';

export default {
  kit: {
    adapter: adapter({
      fallback: 'index.html'
    })
  }
};

The fallback name is important because the entry has to be either index.html or Index.html page. After that, you have to create a build using this command:

npm run build

Notice that, it creates a build folder which can be used to emulate the Static Web App locally with the swa CLI tool:

swa start ./build --data-api-location swa-db-connections

Go to the http://localhost:4280 URL, open the browser console with F12, and click on the List button. In the console, you'll see the items in the database container.

The minimal Deployment file

The steps to create a GitHub workflow. Here is a minimal azure-static-web-apps.yml file that uses the Azure/static-web-apps-deploy@v1 action:

name: Azure Static Web Apps CI/CD

on:
  push:
    branches: 'main'

jobs:
  build_and_deploy_job:
    runs-on: ubuntu-latest
    name: Build and Deploy Job
    steps:
      - uses: actions/checkout@v4
      - name: Build And Deploy
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_BRAVE_COAST_063A3A503 }}
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          action: 'upload'
          app_location: '/'
          output_location: 'build'

Replace the AZURE_STATIC_WEB_APPS_API_TOKEN_BRAVE_COAST_063A3A5033 API token secret with yours by navigating to your GitHub repository and Settings > Secrets and variables > Actions section. Lastly, check if the CosmosDB is connected to the Static Web App in the Azure portal:

enter image description here

If everything is working, you can visit and try out the web application by navigating to Overview > View your application > Visit your site button under the Static Web App resource.