Skip to main content

Configuring Go API with Azure Container Apps

· 2 min read
Gretchun Kim
SharePoint Architect, Loop Logic Specialist

When deploying a Go API to Azure Container Apps (ACA) to serve as the backend for your Docusaurus site, there are some important configuration details to keep in mind.

CORS Configuration​

By default, ACA does not enable CORS (Cross-Origin Resource Sharing), which is essential for your Docusaurus frontend to communicate with the Go API backend hosted on ACA. To enable CORS, you need to modify your Go API code to include the appropriate headers. Here 's a simple example of how to set CORS headers in your Go API:

import (
"net/http"
)
func setCORSHeaders(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*") // Adjust as needed for security
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
}

Make sure to call setCORSHeaders in your API handlers to ensure that the headers are included in the responses.

Environment Variables​

When configuring your Docusaurus site to interact with the Go API on ACA, you need to set the correct base URL for the API. In development, you might use a local URL, but in production, you should point to the ACA endpoint. To manage this, you can use environment variables in Docusaurus. For example, you can set DOCUSAURUS_GO_API_BASE_URL in your .env.development.local file for local development and in your production environment settings for the ACA URL.

# .env.development.local
DOCUSAURUS_GO_API_BASE_URL=http://localhost:8080
# Production environment variable
DOCUSAURUS_GO_API_BASE_URL=https://your-container-app.azurecontainerapps.io

Fetching Data in Docusaurus​

When fetching data from the API in your Docusaurus components, make sure to use the environment variable to construct the API URL. Here’s an example of how to do this:


const apiUrl = process.env.DOCUSAURUS_GO_API_BASE_URL
? `${process.env.DOCUSAURUS_GO_API_BASE_URL}/api/your-endpoint`
: '/api/your-endpoint'; // Fallback for development
fetch(apiUrl)

.then(response => response.json())
.then(data => {
// Handle the data
});

By following these steps, you can successfully configure your Docusaurus site to work with an API hosted on Azure Container Apps, ensuring smooth communication between the frontend and backend.

Formal documentation from Docusaurus​

https://docusaurus.io/docs/deployment

How to handle your Backend API URL:​

Since a Docusaurus site is statically rendered, it cannot access server-side environment variables directly at runtime like a standard Node.js app. Instead, you should pass your backend URL using customFields in your docusaurus.config.js: