### Re-deploying an Existing Next.js Azure App Source: https://github.com/zpg6/opennextjs-azure/blob/main/examples/basic-app/README.md Instructions for initializing and deploying your own Next.js application to Azure Functions. This involves scaffolding the project, customizing `azure.config.json`, building, and then deploying. It assumes you have `npx` and `opennextjs-azure` installed. ```bash # In an empty directory npx opennextjs-azure@latest init --scaffold # Edit azure.config.json with your app name and region # Deploy npx opennextjs-azure build npx opennextjs-azure deploy ``` -------------------------------- ### Local Development and Build Commands for Next.js App Source: https://github.com/zpg6/opennextjs-azure/blob/main/examples/basic-app/README.md Commands for managing the local development environment and building the Next.js application for production. These are standard pnpm commands for Next.js projects. They require pnpm to be installed and the project to be set up. ```bash pnpm dev # Start dev server at http://localhost:3000 pnpm build # Build for production ``` -------------------------------- ### Scaffold, Build, and Deploy Next.js App to Azure Source: https://github.com/zpg6/opennextjs-azure/blob/main/examples/basic-app/README.md This snippet shows the essential commands to initialize, build, and deploy a Next.js application to Azure Functions using the opennextjs-azure CLI. It automates infrastructure provisioning through Bicep templates. No external dependencies are explicitly mentioned for these commands. ```bash npx opennextjs-azure@latest init --scaffold npx opennextjs-azure build npx opennextjs-azure deploy ``` -------------------------------- ### Initialize New Next.js Project for Azure Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Scaffolds a new Next.js application pre-configured for Azure Functions deployment. It installs necessary dependencies, sets up `next.config.ts`, `open-next.config.ts`, Bicep infrastructure templates, and Azure configuration files. Customization options from `create-next-app` can be passed through. ```bash # Create new Next.js 15 app with Azure configuration npx opennextjs-azure@latest init --scaffold # Customize the scaffold with create-next-app options npx opennextjs-azure init --scaffold \ --no-typescript \ --no-tailwind \ --no-eslint \ --no-src-dir \ --no-app-router \ --import-alias "@/*" \ --package-manager npm ``` -------------------------------- ### Configure Azure Adapters with defineAzureConfig Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Programmatically creates OpenNext configuration with Azure-specific adapters using the `defineAzureConfig` function. This simplifies the setup by providing sensible defaults for Azure Functions compatibility, including wrappers, converters, and storage adapters. All parameters are optional. ```typescript // open-next.config.ts import { defineAzureConfig } from "opennextjs-azure"; export default defineAzureConfig({ // Use default Azure adapters (recommended) incrementalCache: "azure-blob", tagCache: "azure-table", queue: "azure-queue", imageLoader: "azure-blob", // Enable image optimization caching enableImageOptimizationCache: true, // Route preloading behavior routePreloadingBehavior: "none", // Application Insights monitoring applicationInsights: true, // Deployment configuration deployment: { target: "functions", region: "eastus", resourceGroup: "my-resources", }, // Custom build settings buildCommand: "npm run build", buildOutputPath: ".", appPath: ".", }); ``` -------------------------------- ### Package.json Scripts for Azure Deployment Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Provides npm scripts for integrating Azure deployment into the development workflow. Includes commands for initialization, building, deploying (including production), tailing logs, and health checks. ```json { "name": "my-nextjs-app", "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "azure:init": "opennextjs-azure init", "azure:build": "opennextjs-azure build", "azure:deploy": "opennextjs-azure deploy", "azure:deploy:prod": "opennextjs-azure deploy --environment prod", "azure:tail": "opennextjs-azure tail", "azure:health": "opennextjs-azure health", "deploy": "npm run azure:build && npm run azure:deploy" }, "dependencies": { "next": "^15.0.0", "react": "^18.3.0", "react-dom": "^18.3.0" }, "devDependencies": { "opennextjs-azure": "^0.1.3", "esbuild": "^0.19.0" } } ``` -------------------------------- ### Package.json Scripts for Azure Deployment Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Provides npm scripts to integrate Azure deployment into your development workflow, including build, deploy, and log tailing. ```APIDOC ## Package.json Scripts ### Description Integrates Azure deployment into your development workflow using npm scripts. ### Method These are npm scripts defined in the `package.json` file. ### Endpoint N/A ### Parameters None ### Request Example ```json { "name": "my-nextjs-app", "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "azure:init": "opennextjs-azure init", "azure:build": "opennextjs-azure build", "azure:deploy": "opennextjs-azure deploy", "azure:deploy:prod": "opennextjs-azure deploy --environment prod", "azure:tail": "opennextjs-azure tail", "azure:health": "opennextjs-azure health", "deploy": "npm run azure:build && npm run azure:deploy" }, "dependencies": { "next": "^15.0.0", "react": "^18.3.0", "react-dom": "^18.3.0" }, "devDependencies": { "opennextjs-azure": "^0.1.3", "esbuild": "^0.19.0" } } ``` ### Usage - `npm run deploy`: Builds and deploys the application to Azure. - `npm run azure:deploy:prod`: Deploys the application to the production environment. - `npm run azure:tail`: Views live logs after deployment. ``` -------------------------------- ### Initialize Existing Next.js Project for Azure Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Adds Azure deployment infrastructure to an existing Next.js project. This command generates `infrastructure/main.bicep` for Azure resource definitions and `azure.config.json` for deployment configuration, while also updating `.gitignore`. It can also scaffold a new project if the directory is empty. ```bash # Add Azure infrastructure to current directory npx opennextjs-azure init # The command creates: # - infrastructure/main.bicep (Azure resource definitions) # - azure.config.json (deployment configuration) # - Updates .gitignore with Azure-specific entries ``` -------------------------------- ### Build Next.js Application for Azure Deployment Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Compiles the Next.js application for deployment on Azure Functions. It generates the `.open-next/` directory containing server code, Azure Functions metadata, production dependencies, and optimized binaries for Sharp. Supports custom OpenNext configurations. ```bash # Build with default config npx opennextjs-azure build # Build with custom OpenNext config npx opennextjs-azure build -c ./custom-open-next.config.ts ``` -------------------------------- ### Initialize New OpenNextJS Azure Project Source: https://github.com/zpg6/opennextjs-azure/blob/main/README.md Scaffolds a new Next.js project with Azure-specific configurations using a single command. It wraps `create-next-app` and supports various customization options like disabling TypeScript, Tailwind CSS, ESLint, or specifying the package manager. ```bash npx opennextjs-azure@latest init --scaffold ``` ```bash # Customize the scaffold opennextjs-azure init --scaffold \ [--no-typescript] \ [--no-tailwind] \ [--no-eslint] \ [--no-src-dir] \ [--no-app-router] \ [--import-alias ] \ [--package-manager npm|yarn|pnpm|bun] ``` -------------------------------- ### Runtime Configuration Resolver Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Retrieves Azure configuration settings from environment variables at runtime. This is essential for storage adapters to connect to Azure services. ```APIDOC ## Runtime Configuration Resolver ### Description Retrieves Azure configuration from environment variables at runtime. This function is used by storage adapters to establish connections with Azure services. ### Method This describes the usage of the `getAzureConfig` function. ### Endpoint N/A (This is a client-side/server-side SDK usage, not a direct HTTP endpoint). ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```typescript import { getAzureConfig } from "opennextjs-azure/config/index.js"; const config = getAzureConfig(); ``` ### Response #### Success Response (200) Returns an object containing the Azure configuration. #### Response Example ```json { "deployment": { "target": "functions", "region": "eastus" }, "storage": { "connectionString": "DefaultEndpointsProtocol=https;...", "accountName": "mystorageaccount", "accountKey": "abc123...", "containerName": "nextjs-cache", "tableName": "nextjstags", "queueName": "nextjsrevalidation" } } ``` ### Environment Variables - `AZURE_DEPLOYMENT_TARGET`: Specifies the deployment target (e.g., "functions"). - `AZURE_REGION`: The Azure region for deployment. - `AZURE_STORAGE_CONNECTION_STRING`: The connection string for Azure Storage. - `AZURE_STORAGE_ACCOUNT_NAME`: The name of the Azure Storage account. - `AZURE_STORAGE_ACCOUNT_KEY`: The key for the Azure Storage account. - `AZURE_STORAGE_CONTAINER_NAME`: The name of the storage container. - `AZURE_TABLE_NAME`: The name of the Azure Table. - `AZURE_QUEUE_NAME`: The name of the Azure Queue. ``` -------------------------------- ### Azure Deployment Configuration File Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Stores default deployment settings for OpenNextJS on Azure in the `azure.config.json` file. This file is automatically created by `opennextjs-azure init` and can be overridden by command-line options. ```json { "appName": "my-nextjs-app", "resourceGroup": "my-resources", "location": "eastus", "environment": "prod", "applicationInsights": true } ``` -------------------------------- ### View Live Logs for Azure Functions Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Opens the Azure Portal to stream live logs for a deployed Azure Function. This command allows for interactive selection of the application or specification of app name and resource group for direct log streaming. ```bash # Interactive selection npx opennextjs-azure tail # Specify app details npx opennextjs-azure tail \ --app-name my-nextjs-app \ --resource-group my-resources ``` -------------------------------- ### Azure Runtime Configuration Resolver Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Retrieves Azure configuration settings from environment variables at runtime. It supports various Azure services like Storage and provides sensible defaults for optional configuration values, ensuring flexibility and ease of use. ```typescript import { getAzureConfig } from "opennextjs-azure/config/index.js"; // Environment variables: // AZURE_DEPLOYMENT_TARGET=functions // AZURE_REGION=eastus // AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;... // AZURE_STORAGE_ACCOUNT_NAME=mystorageaccount // AZURE_STORAGE_ACCOUNT_KEY=abc123... // AZURE_STORAGE_CONTAINER_NAME=nextjs-cache // AZURE_TABLE_NAME=nextjstags // AZURE_QUEUE_NAME=nextjsrevalidation const config = getAzureConfig(); // Returns: // { // deployment: { // target: "functions", // region: "eastus" // }, // storage: { // connectionString: "DefaultEndpointsProtocol=https;...", // accountName: "mystorageaccount", // accountKey: "abc123...", // containerName: "nextjs-cache", // tableName: "nextjstags", // queueName: "nextjsrevalidation" // } // } // Used by storage adapters to connect to Azure services at runtime // Falls back to defaults if environment variables are not set: // - containerName: "nextjs-cache" // - tableName: "nextjstags" // - queueName: "nextjsrevalidation" // - target: "functions" // - region: "eastus" ``` -------------------------------- ### Scaffold New Next.js Project for Azure Source: https://github.com/zpg6/opennextjs-azure/blob/main/README.md Initializes a new Next.js project with Azure deployment configurations, including dependencies, Next.js configuration, OpenNext configuration, Bicep infrastructure templates, and Azure configuration files. ```bash npx opennextjs-azure@latest init --scaffold ``` -------------------------------- ### Deploy Next.js Application to Azure Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Deploys the built Next.js application to Azure, including automatic provisioning of necessary infrastructure like Storage Accounts and Function Apps. Supports interactive and fully specified deployments, skipping infrastructure updates, and different environment configurations (dev, staging, prod) affecting resource tiers. ```bash # Interactive deployment (prompts for resource group and environment) npx opennextjs-azure deploy # Fully specified deployment npx opennextjs-azure deploy \ --app-name my-nextjs-app \ --resource-group my-resources \ --location eastus \ --environment prod # Skip infrastructure provisioning (for updates) npx opennextjs-azure deploy --skip-infrastructure # Environment options: # --environment dev → Y1 Consumption (pay-per-execution, auto-scale) # --environment staging → EP1 Premium (always-ready, faster cold starts) # --environment prod → EP1 Premium (production-grade, GRS storage) ``` -------------------------------- ### Configure Next.js for Serverless Deployment Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Configures Next.js for serverless deployment compatibility, specifically for Azure Functions. The `output: "standalone"` setting is mandatory for this environment. Optional image optimization settings are also provided. ```typescript // next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { output: "standalone", // Required for Azure Functions // Optional: Configure image optimization images: { deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], formats: ["image/webp", "image/avif"], minimumCacheTTL: 60, }, }; export default nextConfig; ``` -------------------------------- ### OpenNextJS Azure CLI Commands Source: https://github.com/zpg6/opennextjs-azure/blob/main/README.md Provides a suite of commands for managing Next.js applications deployed on Azure. These include initializing infrastructure, building the Next.js app, deploying to Azure with environment-specific configurations, tailing logs, checking deployment health, and deleting resources. ```bash # Initialize Azure infrastructure in existing project opennextjs-azure init ``` ```bash # Build Next.js app for Azure opennextjs-azure build [-c ] ``` ```bash # Deploy to Azure opennextjs-azure deploy \ [--app-name ] \ [--resource-group ] \ [--location ] \ [--environment dev|staging|prod] \ [--skip-infrastructure] ``` ```bash # View live logs in Azure Portal opennextjs-azure tail \ [--app-name ] \ [--resource-group ] ``` ```bash # Check deployment health opennextjs-azure health \ [--app-name ] \ [--resource-group ] ``` ```bash # Delete resource group and all resources opennextjs-azure delete \ [--resource-group ] \ [--yes] \ [--no-wait] ``` -------------------------------- ### Add OpenNext.js Azure to Existing Project Source: https://github.com/zpg6/opennextjs-azure/blob/main/README.md Commands to integrate OpenNext.js Azure into an existing Next.js project, including initializing infrastructure, building the app, deploying, and viewing logs. ```bash # Initialize Azure infrastructure npx opennextjs-azure init # Build for Azure npx opennextjs-azure build # Deploy (provisions infrastructure + deploys app) npx opennextjs-azure deploy # View live logs in Azure Portal npx opennextjs-azure tail ``` -------------------------------- ### Azure Bicep Template for Next.js App Infrastructure Source: https://context7.com/zpg6/opennextjs-azure/llms.txt This Bicep template defines essential Azure resources for a Next.js application, including storage accounts for caching and assets, an App Service Plan, and a Function App with a Node.js runtime. It supports environment-specific configurations for SKUs and application settings. ```bicep // Auto-generated by opennextjs-azure init param appName string param location string = resourceGroup().location param environment string = 'dev' // Storage Account for ISR cache, assets, and queues resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = { name: '${appName}storage${uniqueString(resourceGroup().id)}' location: location sku: { name: environment == 'prod' ? 'Standard_GRS' : 'Standard_LRS' } kind: 'StorageV2' properties: { minimumTlsVersion: 'TLS_1_2' allowBlobPublicAccess: true supportsHttpsTrafficOnly: true } } // Blob containers: assets, nextjs-cache, optimized-images // Table: nextjstags // Queue: nextjsrevalidation // App Service Plan resource appServicePlan 'Microsoft.Web/serverfarms@2023-01-01' = { name: '${appName}-plan-${environment}' location: location sku: { name: environment == 'dev' ? 'Y1' : 'EP1' tier: environment == 'dev' ? 'Dynamic' : 'ElasticPremium' } kind: 'functionapp' } // Function App with Node.js 20 runtime resource functionApp 'Microsoft.Web/sites@2023-01-01' = { name: '${appName}-func-${environment}' location: location kind: 'functionapp' properties: { serverFarmId: appServicePlan.id siteConfig: { nodeVersion: '~20' appSettings: [ { name: 'AZURE_STORAGE_CONNECTION_STRING', value: '...' } { name: 'NEXT_BUILD_ID', value: '...' } { name: 'NODE_ENV', value: 'production' } ] } } } // Application Insights (optional) resource appInsights 'Microsoft.Insights/components@2020-02-02' = { name: '${appName}-insights-${environment}' location: location kind: 'web' properties: { Application_Type: 'web' } } ``` -------------------------------- ### Manually Configure OpenNextJS Azure Adapters Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Manually configure Azure adapters for OpenNextJS without using `defineAzureConfig`. This approach offers granular control over adapter imports and settings, allowing for custom adapter integration. It's useful for understanding the configuration structure or implementing specific customizations. ```typescript // open-next.config.ts export default { default: { override: { wrapper: () => import("opennextjs-azure/adapters/wrappers/azure-functions.js").then(m => m.default), converter: () => import("opennextjs-azure/adapters/converters/azure-http.js").then(m => m.default), incrementalCache: () => import("opennextjs-azure/overrides/incrementalCache/azure-blob.js").then(m => new m.default()), tagCache: () => import("opennextjs-azure/overrides/tagCache/azure-table.js").then(m => new m.default()), queue: () => import("opennextjs-azure/overrides/queue/azure-queue.js").then(m => new m.default()), proxyExternalRequest: "fetch", }, routePreloadingBehavior: "none", }, middleware: { external: false, }, imageOptimization: { loader: () => import("opennextjs-azure/overrides/imageLoader/azure-blob.js").then(m => m.default), override: { wrapper: () => import("opennextjs-azure/adapters/wrappers/azure-image-optimization.js").then(m => m.default), converter: () => import("opennextjs-azure/adapters/converters/azure-http.js").then(m => m.default), }, install: { packages: ["sharp@0.33.5"], }, }, buildOutputPath: ".", appPath: ".", }; ``` -------------------------------- ### Build and Deploy Next.js App on Azure Source: https://github.com/zpg6/opennextjs-azure/blob/main/README.md Commands to build the Next.js application for Azure deployment and then deploy the application along with its required infrastructure to Azure. ```bash npx opennextjs-azure build npx opennextjs-azure deploy ``` -------------------------------- ### Wrap OpenNext Handler for Azure Functions v3 Compatibility (TypeScript) Source: https://context7.com/zpg6/opennextjs-azure/llms.txt This snippet illustrates how the `opennextjs-azure` library wraps an OpenNext handler to ensure compatibility with the Azure Functions v3 runtime. It details features like static asset redirection to Blob Storage, streaming response handling via Node.js Writable streams, and specific management of HTTP status codes without bodies. It also covers environment-aware error handling. ```typescript import azureFunctionsWrapper from "opennextjs-azure/adapters/wrappers/azure-functions.js"; import type { InvocationContext, HttpRequest } from "@azure/functions"; // The wrapper provides streaming support and static asset redirection // Automatically used by OpenNext build - this example shows internal behavior // Static asset requests (/_next/static/*, favicon.ico, etc.) are redirected: // Request: GET /_next/static/chunks/main-abc123.js // Response: 301 Redirect to https://{storage}.blob.core.windows.net/assets/_next/static/chunks/main-abc123.js // Cache-Control: public, max-age=31536000, immutable // Streaming responses are handled via Node.js Writable streams: async function exampleHandler(context: InvocationContext, request: HttpRequest) { // Wrapper converts request → InternalEvent // Executes Next.js handler with streaming support // Collects streamed chunks // Sets context.res = { status, headers, body } } // HTTP status codes without body (101, 204, 205, 304) are handled specially: // Response: { status: 304, headers: {...} } // No body is sent even if handler produces output // Error handling with environment-specific details: // Production: { error: "Internal Server Error" } // Development: { error: "Internal Server Error", message: "...", stack: "..." } ``` -------------------------------- ### Azure Functions Wrapper API Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Wraps the OpenNext handler to ensure compatibility with the Azure Functions v3 runtime. It supports streaming responses, redirects static assets to Blob Storage, and handles special HTTP status codes. ```APIDOC ## API: Azure Functions Wrapper ### Description Wraps OpenNext handler for Azure Functions v3 runtime compatibility, providing streaming support and static asset redirection. ### Method N/A (This is an adapter, used internally during the build process) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import azureFunctionsWrapper from "opennextjs-azure/adapters/wrappers/azure-functions.js"; import type { InvocationContext, HttpRequest } from "@azure/functions"; // The wrapper is automatically used by OpenNext build process. // This example illustrates its internal behavior: async function handler(context: InvocationContext, request: HttpRequest) { // ... OpenNext handler logic ... // The wrapper converts the request to InternalEvent, executes the handler, // and collects the streamed response, setting context.res accordingly. } // Example of static asset redirection: // Request: GET /_next/static/chunks/main-abc123.js // Response: 301 Redirect to https://{storage}.blob.core.windows.net/assets/_next/static/chunks/main-abc123.js // Cache-Control: public, max-age=31536000, immutable ``` ### Response N/A (The wrapper modifies the Azure Functions `context.res` object) ### Error Handling Provides environment-specific error details: - Production: `{ error: "Internal Server Error" }` - Development: `{ error: "Internal Server Error", message: "...", stack: "..." }` Handles null-body status codes (101, 204, 205, 304) correctly by not sending a body. ``` -------------------------------- ### Next.js Features to Azure Service Mapping Source: https://github.com/zpg6/opennextjs-azure/blob/main/README.md Illustrates how various Next.js features are implemented using specific Azure services for a serverless architecture. ```markdown | Next.js Feature | Azure Implementation | | -------------------------------------- | --------------------------------------------------------------- | | Incremental Static Regeneration | Azure Blob Storage | | Image Optimization | Azure Blob Storage with automatic caching | | Streaming SSR | Azure Functions with Node.js streams | | `revalidateTag()` / `revalidatePath()` | Azure Table Storage + Queue Storage | | Fetch caching | Azure Blob Storage with build ID namespacing | | Monitoring & Logging | Azure Application Insights (optional, enabled by default) | | Infrastructure | Azure Bicep templates upsert infrastructure in a resource group | ``` -------------------------------- ### Check OpenNextJS Azure Deployment Health Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Verifies the running status of the Azure Function App, checks connectivity to the storage account, validates environment variables, and displays the deployment URL and configuration. This command is essential for ensuring a successful deployment. ```bash npx opennextjs-azure health \ --app-name my-nextjs-app \ --resource-group my-resources ``` -------------------------------- ### Check Deployment Health on Azure Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Verifies the deployment status and health of resources associated with the OpenNext.js Azure deployment. This command provides an interactive way to check the overall health of the deployed application and its infrastructure. ```bash # Interactive health check npx opennextjs-azure health ``` -------------------------------- ### Azure Queue Revalidation API Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Handles on-demand Incremental Static Regeneration (ISR) revalidation by sending messages to Azure Queue Storage. This allows Next.js pages to be re-rendered asynchronously when content changes. ```APIDOC ## Azure Queue Revalidation API ### Description Handles on-demand ISR revalidation via Azure Queue Storage. Messages are sent to the queue, which are then processed to trigger Next.js page re-renders. ### Method This describes the process of sending a message to the queue using the `AzureQueueRevalidation` class. ### Endpoint N/A (This is a client-side/server-side SDK usage, not a direct HTTP endpoint). ### Parameters #### Query Parameters None #### Request Body This section describes the structure of the message sent to the queue: - **host** (string) - Required - The host of the revalidation request. - **url** (string) - Required - The URL path to revalidate. - **lastModified** (number) - Optional - Timestamp of the last modification. - **eTag** (string) - Optional - The ETag of the content. - **deduplicationId** (string) - Optional - For message deduplication. - **groupId** (string) - Optional - For message grouping. ### Request Example ```json { "MessageBody": { "host": "example.com", "url": "/products/123", "lastModified": 1699564800000, "eTag": "abc123xyz" }, "MessageDeduplicationId": "dedup-123", "MessageGroupId": "group-products" } ``` ### Response #### Success Response (200) Indicates the message was successfully sent to the queue. #### Response Example N/A (The `send` method typically returns a promise that resolves on successful queue addition, without a specific JSON response body). ### Queue Message Format (Base64 Encoded) ```json { "host": "example.com", "url": "/products/123", "lastModified": 1699564800000, "eTag": "abc123xyz", "deduplicationId": "dedup-123", "groupId": "group-products" } ``` ### Usage Triggered by Next.js Revalidation APIs ```typescript import { revalidatePath } from "next/cache"; await revalidatePath("/products/123"); // Sends queue message ``` ``` -------------------------------- ### Azure HTTP Converter API Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Converts between Azure Functions HTTP request/response format and OpenNext internal event/result format. It handles header normalization, cookie parsing, query parameter extraction, request body buffering, and streaming response bodies. ```APIDOC ## API: Azure HTTP Converter ### Description Converts between Azure Functions HTTP format and OpenNext internal format, handling various aspects of HTTP communication. ### Method N/A (This is a utility module, not a direct API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example (Conversion from Azure to OpenNext) ```typescript import type { HttpRequest } from "@azure/functions"; import type { InternalEvent } from "@opennextjs/aws/types/open-next.js"; import azureHttpConverter from "opennextjs-azure/adapters/converters/azure-http.js"; const azureRequest: HttpRequest = { method: "GET", url: "https://example.com/api/products?category=electronics", headers: { "content-type": "application/json", "cookie": "session=abc123; theme=dark", "x-forwarded-for": "192.168.1.1", }, arrayBuffer: async () => new ArrayBuffer(0), }; const internalEvent: InternalEvent = await azureHttpConverter.convertFrom(azureRequest); // internalEvent will contain: { type: "core", method: "GET", rawPath: "/api/products", url: "...", headers: {...}, query: { category: "electronics" }, cookies: { session: "abc123", theme: "dark" }, remoteAddress: "192.168.1.1", body: undefined } ``` ### Request Example (Conversion from OpenNext to Azure) ```typescript import type { InternalResult } from "@opennextjs/aws/types/open-next.js"; import { ReadableStream } from "stream/web"; const internalResult: InternalResult = { statusCode: 200, headers: { "content-type": "text/html", "cache-control": "public, max-age=3600", "set-cookie": ["token=xyz789; HttpOnly", "theme=light; Path=/"], }, body: new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("Hello")); controller.close(); }, }), isBase64Encoded: false, }; const azureResponse = await azureHttpConverter.convertTo(internalResult); // azureResponse will contain: { status: 200, headers: { "content-type": "text/html", "cache-control": "public, max-age=3600", "set-cookie": "token=xyz789; HttpOnly, theme=light; Path=/" }, body: "Hello" } ``` ### Response N/A (This is a utility module, methods return converted objects) ### Error Handling Handles missing headers, malformed cookies, and other common HTTP issues gracefully. Automatically detects client IP from `x-forwarded-for` or `x-real-ip` headers. ``` -------------------------------- ### Convert Azure HTTP Request/Response to OpenNext Internal Format (TypeScript) Source: https://context7.com/zpg6/opennextjs-azure/llms.txt This snippet demonstrates how to convert Azure Functions HttpRequest objects to OpenNext's InternalEvent format and vice versa, using the `opennextjs-azure` library. It handles request normalization, query parameters, cookies, and response body streaming. Dependencies include `@azure/functions` and `@opennextjs/aws/types/open-next.js`. ```typescript import type { HttpRequest } from "@azure/functions"; import type { InternalEvent, InternalResult } from "@opennextjs/aws/types/open-next.js"; import azureHttpConverter from "opennextjs-azure/adapters/converters/azure-http.js"; // Convert Azure HTTP request to OpenNext InternalEvent const azureRequest: HttpRequest = { method: "GET", url: "https://example.com/api/products?category=electronics", headers: { "content-type": "application/json", "cookie": "session=abc123; theme=dark", "x-forwarded-for": "192.168.1.1", }, arrayBuffer: async () => new ArrayBuffer(0), }; const internalEvent: InternalEvent = await azureHttpConverter.convertFrom(azureRequest); // Convert OpenNext InternalResult to Azure HTTP response const internalResult: InternalResult = { statusCode: 200, headers: { "content-type": "text/html", "cache-control": "public, max-age=3600", "set-cookie": ["token=xyz789; HttpOnly", "theme=light; Path=/"], }, body: new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("Hello")); controller.close(); }, }), isBase64Encoded: false, }; const azureResponse = await azureHttpConverter.convertTo(internalResult); ``` -------------------------------- ### Azure Blob Incremental Cache for Next.js Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Stores Next.js Incremental Static Regeneration (ISR) cache entries in Azure Blob Storage. It handles both page and fetch cache data, uses build ID namespacing for isolation, and follows AWS S3 key structure for compatibility. Configuration is done via environment variables. ```typescript import AzureBlobIncrementalCache from "opennextjs-azure/overrides/incrementalCache/azure-blob.js"; // Configure via environment variables: // AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=... // AZURE_STORAGE_CONTAINER_NAME=nextjs-cache // NEXT_BUILD_ID=abc123xyz const cache = new AzureBlobIncrementalCache(); // Store a rendered page in ISR cache await cache.set("/products/electronics", { kind: "PAGE", html: "...", pageData: { products: [...] }, headers: { "content-type": "text/html" }, status: 200, }, "cache"); // Blob storage path: nextjs-cache/abc123xyz/products/electronics.cache // Content: JSON stringified cache value // Retrieve cached page const result = await cache.get("/products/electronics", "cache"); // Returns: // { // value: { // kind: "PAGE", // html: "...", // pageData: { products: [...] }, // headers: { "content-type": "text/html" }, // status: 200 // }, // lastModified: 1699564800000 // } // Store fetch cache (data cache) await cache.set("api-call-key", { kind: "FETCH", data: { users: [...] }, revalidate: 3600, }, "fetch"); // Blob storage path: nextjs-cache/__fetch/abc123xyz/api-call-key.fetch // Delete cache entry await cache.delete("/products/electronics"); // Removes: nextjs-cache/abc123xyz/products/electronics.cache ``` -------------------------------- ### Azure Table Tag Cache for Next.js Revalidation Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Manages tag-to-path mappings for Next.js tag-based revalidation using Azure Table Storage. It supports many-to-many relationships, efficient querying by tag or path, and stores revalidation timestamps. Integrates with Next.js revalidation APIs. ```typescript import AzureTableTagCache from "opennextjs-azure/overrides/tagCache/azure-table.js"; // Configure via environment variables: // AZURE_STORAGE_CONNECTION_STRING=... // AZURE_TABLE_NAME=nextjstags // NEXT_BUILD_ID=abc123xyz const tagCache = new AzureTableTagCache(); // Write tag-to-path mappings await tagCache.writeTags([ { tag: "product", path: "/products/123", revalidatedAt: Date.now(), }, { tag: "product", path: "/products/456", revalidatedAt: Date.now(), }, { tag: "electronics", path: "/products/123", revalidatedAt: Date.now(), }, ]); // Table storage schema: // | PartitionKey | RowKey | revalidatedAt | // | abc123xyz/product | abc123xyz/products/123 | 1699564800000 | // | abc123xyz/product | abc123xyz/products/456 | 1699564800000 | // | abc123xyz/electronics | abc123xyz/products/123 | 1699564800000 | // Get all paths tagged with "product" const paths = await tagCache.getByTag("product"); // Returns: ["/products/123", "/products/456"] // Get all tags for a specific path const tags = await tagCache.getByPath("/products/123"); // Returns: ["product", "electronics"] // Check if path needs revalidation const lastModified = await tagCache.getLastModified("/products/123", 1699564700000); // Returns: -1 (if any tag was revalidated since timestamp) // Returns: 1699564700000 (if no revalidation needed) // Usage in Next.js: // import { revalidateTag } from "next/cache"; // await revalidateTag("product"); // Invalidates all paths tagged "product" ``` -------------------------------- ### Azure Table Tag Cache Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Stores tag-to-path mappings for tag-based revalidation in Azure Table Storage. Enables efficient querying for revalidation logic. ```APIDOC ## Azure Table Tag Cache Stores tag-to-path mappings for tag-based revalidation in Azure Table Storage. ### Description Stores tag-to-path mappings for tag-based revalidation in Azure Table Storage. Enables efficient querying for revalidation logic and integrates with Next.js revalidation APIs. ### Method Not applicable (Class-based implementation) ### Endpoint Not applicable (Class-based implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import AzureTableTagCache from "opennextjs-azure/overrides/tagCache/azure-table.js"; // Configure via environment variables: // AZURE_STORAGE_CONNECTION_STRING=... // AZURE_TABLE_NAME=nextjstags // NEXT_BUILD_ID=abc123xyz const tagCache = new AzureTableTagCache(); // Write tag-to-path mappings await tagCache.writeTags([ { tag: "product", path: "/products/123", revalidatedAt: Date.now(), }, { tag: "product", path: "/products/456", revalidatedAt: Date.now(), }, { tag: "electronics", path: "/products/123", revalidatedAt: Date.now(), }, ]); // Get all paths tagged with "product" const paths = await tagCache.getByTag("product"); // Get all tags for a specific path const tags = await tagCache.getByPath("/products/123"); // Check if path needs revalidation const lastModified = await tagCache.getLastModified("/products/123", 1699564700000); ``` ### Response #### Success Response (200) - `getByTag` and `getByPath` return an array of strings (paths or tags). - `getLastModified` returns a number representing the timestamp of the last revalidation or the provided timestamp if no revalidation is needed. #### Response Example ```json // Example for getByTag("product") [ "/products/123", "/products/456" ] // Example for getLastModified("/products/123", 1699564700000) -1 // or 1699564700000 ``` ``` -------------------------------- ### Azure Queue Revalidation with OpenNextJS Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Handles on-demand ISR revalidation using Azure Queue Storage. It sends revalidation messages containing host, URL, and cache metadata to Azure. The messages are base64 encoded and processed asynchronously by a background worker to trigger Next.js page re-renders. ```typescript import AzureQueueRevalidation from "opennextjs-azure/overrides/queue/azure-queue.js"; import type { QueueMessage } from "@opennextjs/aws/types/overrides.js"; // Configure via environment variables: // AZURE_STORAGE_CONNECTION_STRING=... // AZURE_QUEUE_NAME=nextjsrevalidation const queue = new AzureQueueRevalidation(); // Send revalidation message const message: QueueMessage = { MessageBody: { host: "example.com", url: "/products/123", lastModified: Date.now(), eTag: "abc123xyz", }, MessageDeduplicationId: "dedup-123", MessageGroupId: "group-products", }; await queue.send(message); // Queue message format (base64 encoded): // { // "host": "example.com", // "url": "/products/123", // "lastModified": 1699564800000, // "eTag": "abc123xyz", // "deduplicationId": "dedup-123", // "groupId": "group-products" // } // The queue message triggers revalidation: // 1. Message is added to Azure Queue Storage // 2. Background processor picks up message // 3. Next.js re-renders the specified URL // 4. Updated content is stored in incremental cache // 5. Subsequent requests serve fresh content // Usage triggered by Next.js revalidation APIs: // import { revalidatePath } from "next/cache"; // await revalidatePath("/products/123"); // Sends queue message ``` -------------------------------- ### Azure Blob Incremental Cache Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Stores Next.js ISR cache entries in Azure Blob Storage. Supports storing rendered pages and fetch cache data, with build ID namespacing for isolation. ```APIDOC ## Azure Blob Incremental Cache Stores Next.js ISR cache entries in Azure Blob Storage. ### Description Stores Next.js ISR cache entries in Azure Blob Storage. Supports storing rendered pages and fetch cache data, with build ID namespacing for isolation. ### Method Not applicable (Class-based implementation) ### Endpoint Not applicable (Class-based implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import AzureBlobIncrementalCache from "opennextjs-azure/overrides/incrementalCache/azure-blob.js"; // Configure via environment variables: // AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=... // AZURE_STORAGE_CONTAINER_NAME=nextjs-cache // NEXT_BUILD_ID=abc123xyz const cache = new AzureBlobIncrementalCache(); // Store a rendered page in ISR cache await cache.set("/products/electronics", { kind: "PAGE", html: "...", pageData: { products: [...] }, headers: { "content-type": "text/html" }, status: 200, }, "cache"); // Retrieve cached page const result = await cache.get("/products/electronics", "cache"); // Store fetch cache (data cache) await cache.set("api-call-key", { kind: "FETCH", data: { users: [...] }, revalidate: 3600, }, "fetch"); // Delete cache entry await cache.delete("/products/electronics"); ``` ### Response #### Success Response (200) For `get` requests, returns an object with `value` and `lastModified` properties. - **value** (object) - The cached data (PAGE or FETCH). - **lastModified** (number) - Timestamp of the last modification. #### Response Example ```json { "value": { "kind": "PAGE", "html": "...", "pageData": { "products": [...] }, "headers": { "content-type": "text/html" }, "status": 200 }, "lastModified": 1699564800000 } ``` ``` -------------------------------- ### OpenNext.js Azure Architecture Flow Source: https://github.com/zpg6/opennextjs-azure/blob/main/README.md Details the request flow from a client to the Next.js server within the Azure Functions environment, including interactions with various Azure services for caching and revalidation. ```markdown ``` Next.js Request ↓ Azure Functions HTTP Trigger ↓ Azure HTTP Converter (request → InternalEvent) ↓ Azure Functions Wrapper (handles streaming) ↓ Next.js Server (OpenNext) ↓ ISR Cache Check → Azure Blob Storage Tag Check → Azure Table Storage Revalidation → Azure Queue Storage ↓ Response Stream → Azure Functions Response ``` ``` -------------------------------- ### Delete OpenNextJS Azure Resources Source: https://context7.com/zpg6/opennextjs-azure/llms.txt Removes all Azure resources associated with your OpenNextJS deployment, including the Function App, Storage Account, App Service Plan, and Application Insights. This operation is irreversible. Options are available to skip confirmation prompts and perform asynchronous deletion. ```bash # Interactive deletion with confirmation npx opennextjs-azure delete ``` ```bash # Skip confirmation prompt npx opennextjs-azure delete \ --resource-group my-resources \ --yes ``` ```bash # Async deletion (don't wait for completion) npx opennextjs-azure delete \ --resource-group my-resources \ --yes \ --no-wait ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.