# Azion IaC

import DocButton from '~/components/webkit/DocButton.vue';
import Tabs from '~/components/tabs/Tabs'
import Apiv4Rollout from '~/includes/snippets/apiv4Rollout/en/snippet.mdx'

<Apiv4Rollout />

The `azion.config.js` file is an IaC configuration file created during the application's build process, based on the chosen preset, and serves as the source of truth for the configuration. Each preset provides a set of default settings, which can be replaced by the user. If the file is deleted, the default configuration will be recreated the next time the build process is triggered.

The configurations set by this file include: 

<Tabs client:visible>
    <Fragment slot="tab.apiv3" default>API v3</Fragment>
    <Fragment slot="tab.apiv4">API v4</Fragment>

<Fragment slot="panel.apiv3">

- Build Configurations
- Origins
- Cache Settings
- Rules Engine
- Network List
- Purge Settings
- Firewall Settings
- WAF Settings

</Fragment>
<Fragment slot="panel.apiv4">

- Build Configurations
- Workloads
- Connectors
- Applications
- Cache Settings
- Rules Engine
- Network List
- Purge Settings
- Firewall Settings
- WAF Settings
- Custom Pages
- KV Store

</Fragment>



</Tabs>

:::note
The default properties and values generated in the project's initial build are tested and work properly. In case this file is altered, we no longer guarantee it works properly, so use it wisely.
:::

---

## API Reference

### `defineConfig`

Configures and validates the options for the Application.

**Parameters**:

- `config: AzionConfig` - Configuration object for Applications.

---

## Types


<Tabs client:visible>
    <Fragment slot="tab.apiv3" default>API v3</Fragment>
    <Fragment slot="tab.apiv4">API v4</Fragment>

<Fragment slot="panel.apiv3">

### `AzionConfig`

**Properties**:

- `build?: AzionBuild` - The build configuration.
- `domain?: AzionDomain` - The domain object.
- `origin?: AzionOrigin[]` - List of origins.
- `cache?: AzionCache[]` - List of cache settings.
- `rules?: AzionRules[]` - List of application rules.
- `purge?: AzionPurge[]` - List of URLs or CacheKeys to purge.
- `networkLists?: AzionNetworkList[]` - List of network lists.
- `waf?: AzionWaf[]` - List of WAF configurations.


### `AzionBuild`

Type definition for the build configuration.

**Properties**:

- `builder?: 'esbuild' | 'webpack'` - The builder to use.
- `preset?: string` - The preset to use.
- `entry?: string` - The entry file.
- `polyfills?: boolean` - Whether to use Polyfills.
- `worker?: boolean` - Whether to build a worker.
- `custom?: Record<string, any>` - Custom build configuration.
- `memoryFS?: { injectionDirs: string[], removePathPrefix: string }` - Memory file system configuration.


### `AzionDomain`

Type definition for the domain configuration.

**Properties**:

- `name: string` - The domain name.
- `cnameAccessOnly?: boolean` - Whether to restrict access only to CNAMEs.
- `cnames?: string[]` - List of CNAMEs for the domain.
- `id?: number` - Domain ID.
- `edgeApplicationId?: number` - Application ID.
- `edgeFirewallId?: number` - Firewall ID.
- `digitalCertificateId?: string | number | null` - Digital certificate ID.
- `active?: boolean` - Whether the domain is active.
- `mtls?: MTLSConfig` - Configuration for mTLS.
  - `verification: 'enforce' | 'permissive'` - mTLS verification mode.
  - `trustedCaCertificateId: number` - Trusted CA certificate ID.
  - `crlList?: number[]` - List of Certificate Revocation Lists (CRLs).

### `AzionOrigin`

Type definition for the origin configuration.

**Properties**:

- `id?: number` - Origin ID.
- `key?: string` - Origin key.
- `name: string` - Origin name.
- `type: string` - Type of the origin. For example: 'single_origin', 'load_balancer'.
- `bucket?: string | null` - Bucket name for storage origins.
- `prefix?: string | null` - Prefix for storage origins.
- `addresses?: (string | { address: string; weight?: number })[]` - Array of addresses for the origin.
- `hostHeader?: string` - Custom host header.
- `protocolPolicy?: 'http' | 'https' | 'preserve'` - Protocol policy for the origin.
- `redirection?: boolean` - Whether to enable redirection.
- `method?: 'ip_hash' | 'least_connections' | 'round_robin'` - Load balancing method.
- `path?: string` - Path for the origin.
- `connectionTimeout?: number` - Connection timeout in seconds.
- `timeoutBetweenBytes?: number` - Timeout between bytes in seconds.
- `hmac?: { region: string; accessKey: string; secretKey: string }` - HMAC configuration for the origin.

### `AzionCache`

Type definition for the cache configuration.

**Properties**:

- `name: string` - Name of the cache configuration.
- `stale?: boolean` - Whether to allow stale content.
- `queryStringSort?: boolean` - Whether to sort query string parameters.
- `methods?: CacheMethods` - HTTP methods to cache.
  - `post?: boolean` - Whether to cache POST requests.
  - `options?: boolean` - Whether to cache OPTIONS requests.
- `browser?: BrowserCacheConfig` - Browser cache settings.
  - `maxAgeSeconds: number | string` - Maximum age for browser cache in seconds.
- `edge?: EdgeCacheConfig` - Cache settings.
  - `maxAgeSeconds: number | string` - Maximum age for cache in seconds.
- `cacheByCookie?: CacheByCookieConfig` - Cache by cookie settings.
  - `option: 'ignore' | 'varies' | 'whitelist' | 'blacklist'` - Cache by cookie option.
  - `list?: string[]` - List of cookies to use for caching.
- `cacheByQueryString?: CacheByQueryStringConfig` - Cache by query string settings.
  - `option: 'ignore' | 'varies' | 'whitelist' | 'blacklist'` - Cache by query string option.
  - `list?: string[]` - List of query string parameters to use for caching.

### `AzionRequestRule`

Type definition for the request rule configuration.

**Properties**:

- `name: string` - Name of the request rule.
- `description?: string` - Description of the request rule.
- `active?: boolean` - Whether the rule is active.
- `match: string` - Match criteria for the rule.
- `variable?: string` - Variable to be used in the match.
- `behavior?: RequestBehavior` - Behavior to apply when the rule matches.
  - `setOrigin?: { name: string; type: string }` - Set a new origin.
  - `rewrite?: string` - Rewrite the request.
  - `setHeaders?: string[]` - Set headers.
  - `bypassCache?: boolean | null` - Bypass cache.
  - `httpToHttps?: boolean | null` - Force HTTPS.
  - `redirectTo301?: string | null` - Redirect with 301 status.
  - `redirectTo302?: string | null` - Redirect with 302 status.
  - `forwardCookies?: boolean | null` - Forward cookies.
  - `setCookie?: string | null` - Set a cookie.
  - `deliver?: boolean | null` - Deliver the content.
  - `capture?: { match: string; captured: string; subject: string }` - Capture configuration.
  - `runFunction?: { path: string; name?: string | null }` - Run a serverless function.
  - `setCache?: string | { name: string; browser_cache_settings_maximum_ttl?: number | null; cdn_cache_settings_maximum_ttl?: number | null }` - Cache configuration.

### `AzionResponseRule`

Type definition for the response rule configuration.

**Properties**:

- `name: string` - Name of the response rule.
- `description?: string` - Description of the response rule.
- `active?: boolean` - Whether the rule is active.
- `match: string` - Match criteria for the rule.
- `variable?: string` - Variable to be used in the match.
- `behavior?: ResponseBehavior` - Behavior to apply when the rule matches.
  - `setCookie?: string | null` - Set a cookie.
  - `setHeaders?: string[]` - Set headers.
  - `deliver?: boolean | null` - Deliver the content.
  - `capture?: { match: string; captured: string; subject: string }` - Capture configuration.
  - `enableGZIP?: boolean | null` - Enable GZIP compression.
  - `filterCookie?: string | null` - Filter a cookie.
  - `filterHeader?: string | null` - Filter a header.
  - `runFunction?: { path: string; name?: string | null }` - Run a serverless function.
  - `redirectTo301?: string | null` - Redirect with 301 status.
  - `redirectTo302?: string | null` - Redirect with 302 status.

### `AzionRules`

Type definition for the rule set.

**Properties**:

- `request: AzionRequestRule[]` - Rule set for the Request phase.
- `response?: AzionResponseRule[]` - Rule set for the Response phase.

### `AzionPurge`

Type definition for the purge configuration.

**Properties**:

- `type: 'url' | 'cachekey' | 'wildcard'` - The type of purge to be performed.
- `urls: string[]` - List of URLs to be purged.
- `method?: 'delete'` - HTTP method for the purge request.
- `layer?: 'edge_caching' | 'l2_caching'` - Cache layer to be purged.

### `AzionNetworkList`

Type definition for the network list configuration.

**Properties**:

- `id: number` - Network list ID.
- `listType: 'ip_cidr' | 'asn' | 'countries'` - Network list type.
- `listContent: string[] | number[]` - List of IP CIDRs, ASNs, or countries.

### `AzionFirewall`

Type definition for the Firewall configuration.

**Properties**:

- `name: string` - Name of the firewall.
- `domains?: string[]` - List of domains associated with the firewall.
- `active?: boolean` - Whether the firewall is active.
- `edgeFunctions?: boolean` - Whether Functions are enabled.
- `networkProtection?: boolean` - Whether Network Protection is enabled.
- `waf?: boolean` - Whether WAF is enabled.
- `variable?: RuleVariable` - Variable to be used in matches.
- `rules?: AzionFirewallRule[]` - List of firewall rules.
- `debugRules?: boolean` - Whether debug mode is enabled for rules.

### `AzionFirewallRule`

Type definition for firewall rules.

**Properties**:

- `name: string` - Name of the rule.
- `description?: string` - Description of the rule.
- `active?: boolean` - Whether the rule is active.
- `match?: string` - Match criteria for the rule.
- `variable?: RuleVariable` - Variable to be used in the match.
- `criteria?: AzionFirewallCriteria[]` - Array of criteria for complex conditions.
- `behavior: AzionFirewallBehavior` - Behavior to be applied when the rule matches.

### `AzionFirewallBehavior`

Type definition for firewall rule behaviors.

**Properties**:

- `runFunction?: { path: string }` - Run a function.
- `setWafRuleset?: { wafMode: FirewallWafMode; wafId: string }` - Set WAF rule set.
- `setRateLimit?: ` - Set rate limit configuration.
    - `type: FirewallRateLimitType` - Rate limit type (second, minute, hour).
    - `limitBy: FirewallRateLimitBy` - Rate limit by (client_ip, global, token).
    - `averageRateLimit: string` - Average rate limit.
    - `maximumBurstSize: string` - Maximum burst size.
- `deny?: boolean` - Deny the request.
- `drop?: boolean` - Drop the request.
- `setCustomResponse?: ` - Set custom response.
  - `statusCode: number | string` - HTTP status code (200-499).
  - `contentType: string` - Response content type.
  - `contentBody: string` - Response content body.

### `AzionFirewallCriteria`

Type definition for firewall rule criteria.

**Properties**:

- `variable: RuleVariable` - Variable to be evaluated.
- `conditional: RuleConditional` - Conditional type.
- `operator: RuleOperatorWithValue | RuleOperatorWithoutValue` - Comparison operator.
- `inputValue?: string` - Input value for comparison (required for operators with value).

### `AzionWaf`

Type definition for the Web Application Firewall (WAF) configuration.

**Properties**:

- `id?: number` - WAF ID.
- `name: string` - WAF name.
- `active: boolean` - Whether the WAF is active.
- `mode: WafMode` - WAF mode (learning, blocking, counting).
- `sqlInjection?: object` - SQL Injection settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `remoteFileInclusion?: object` - Remote File Inclusion settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `directoryTraversal?: object` - Directory Traversal settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `crossSiteScripting?: object` - Cross-Site Scripting settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `evadingTricks?: object` - Evading Tricks settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `fileUpload?: object` - File Upload settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `unwantedAccess?: object` - Unwanted Access settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `identifiedAttack?: object` - Identified Attack settings.
  - `sensitivity: string` - Sensitivity level (low, medium, high).
- `bypassAdresses?: string[]` - List of IP addresses to bypass the WAF.

</Fragment>

<Fragment slot="panel.apiv4">

### `AzionConfig`

**Properties**:

- `build?: AzionBuild` - The build configuration.
- `workloads?: AzionWorkload[]` - List of workloads.
- `connectors?: AzionConnector[]` - List of connectors.
- `applications?: AzionApplication[]` - List of applications.
- `functions?: AzionFunction[]` - List of functions.
- `storage?: AzionBucket[]` - List of storage configurations.
- `firewall?: AzionFirewall[]` - List of firewall configurations.
- `networkList?: AzionNetworkList[]` - List of network lists.
- `purge?: AzionPurge[]` - List of URLs or CacheKeys to purge.
- `waf?: AzionWaf[]` - List of WAF configurations.
- `customPages?: AzionCustomPage[]` - List of custom pages.
- `kv?: AzionKV[]` - List of KV Store configurations.


### `AzionBuild`

Type definition for the build configuration.

**Properties**:

- `bundler?: 'esbuild' | 'webpack'` - The bundler to use.
- `preset?: string | AzionBuildPreset` - The preset to use (string or custom preset object).
- `entry?: string | string[] | Record<string, string>` - The entry file.
- `polyfills?: boolean` - Whether to use Polyfills.
- `worker?: boolean` - Whether to build a worker.
- `extend?: (context: WebpackConfig | ESBuildConfig) => WebpackConfig | ESBuildConfig` - Function to extend the bundler configuration.
- `memoryFS?: { injectionDirs: string[], removePathPrefix: string }` - Memory file system configuration.






### `AzionBuildPreset`

Type definition for custom build preset.

**Properties**:

- `config: AzionConfig` - Preset configuration.
- `handler?: AzionRuntimeModule` - Custom handler.
- `prebuild?: (config: BuildConfiguration, ctx: BuildContext) => Promise<void | AzionPrebuildResult>` - Function executed before build.
- `postbuild?: (config: BuildConfiguration, ctx: BuildContext) => Promise<void>` - Function executed after build.
- `metadata: PresetMetadata` - Preset metadata.

### `AzionWorkload`

Type definition for workload configuration.

**Properties**:

- `name: string` - Workload name.
- `active?: boolean` - Whether the workload is active.
- `infrastructure?: 1 | 2` - Infrastructure type (1 = Standard, 2 = High Performance).
- `tls?: AzionWorkloadTLS` - TLS configuration.
  - `certificate?: number | null` - Certificate ID.
  - `ciphers?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8` - Cipher configuration.
  - `minimumVersion?: '' | 'tls_1_0' | 'tls_1_1' | 'tls_1_2' | 'tls_1_3'` - Minimum TLS version.
- `protocols?: AzionWorkloadProtocols` - Protocol configuration.
  - `http: { versions: ('http1' | 'http2' | 'http3')[], httpPorts: number[], httpsPorts: number[], quicPorts?: number[] | null }` - HTTP configuration.
- `mtls?: AzionWorkloadMTLS` - mTLS configuration.
  - `enabled: boolean` - Whether mTLS is enabled.
  - `config: { verification: 'enforce' | 'permissive', certificate?: number | null, crl?: number[] | null }` - mTLS configuration.
- `domains?: string[]` - List of associated domains.
- `workloadDomainAllowAccess?: boolean` - Whether to allow access via workload domain.
- `deployments?: AzionWorkloadDeployment[]` - List of deployments.
  - `name: string` - Deployment name.
  - `current?: boolean` - Whether it's the current deployment.
  - `active?: boolean` - Whether it's active.
  - `strategy: AzionWorkloadDeploymentStrategy` - Deployment strategy.

### `AzionConnector`

Type definition for connectors (union of types).

**Available types**:
- `AzionConnectorHttp` - HTTP connector.
- `AzionConnectorStorage` - Object Storage connector.
- `AzionConnectorLiveIngest` - Live Ingest connector.

### `AzionConnectorHttp`

Type definition for HTTP connector.

**Properties**:

- `name: string` - Connector name.
- `active?: boolean` - Whether the connector is active.
- `type: 'http'` - Connector type.
- `attributes: ConnectorHttpAttributes` - Connector attributes.
  - `addresses: ConnectorAddress[]` - List of addresses.
    - `address: string` - IP address or CNAME.
    - `active?: boolean` - Whether the address is active.
    - `httpPort?: number` - HTTP port.
    - `httpsPort?: number` - HTTPS port.
  - `connectionOptions: ConnectorConnectionOptions` - Connection options.
    - `dnsResolution?: 'both' | 'force_ipv4'` - DNS resolution policy.
    - `transportPolicy?: 'preserve' | 'force_https' | 'force_http'` - Transport policy.
    - `httpVersionPolicy?: 'http1_1'` - HTTP version policy.
    - `host?: string` - Custom host.
    - `pathPrefix?: string` - Path prefix.
    - `followingRedirect?: boolean` - Follow redirects.
  - `modules?: ConnectorModules` - Connector modules.
    - `loadBalancer: { enabled: boolean, config: LoadBalancerConfig | null }` - Load balancer configuration.
    - `originShield: { enabled: boolean, config: OriginShieldConfig | null }` - Origin shield configuration.

### `AzionConnectorStorage`

Type definition for Object Storage connector.

**Properties**:

- `name: string` - Connector name.
- `active?: boolean` - Whether the connector is active.
- `type: 'storage'` - Connector type.
- `attributes: ConnectorStorageAttributes` - Connector attributes.
  - `bucket: string` - Bucket name.
  - `prefix?: string` - Prefix for objects.

### `AzionApplication`

Type definition for application configuration.

**Properties**:

- `name: string` - Application name.
- `active?: boolean` - Whether the application is active.
- `edgeCacheEnabled?: boolean` - Whether cache is enabled.
- `functionsEnabled?: boolean` - Whether Functions are enabled.
- `applicationAcceleratorEnabled?: boolean` - Whether Application Accelerator is enabled.
- `imageProcessorEnabled?: boolean` - Whether Image Processor is enabled.
- `debug?: boolean` - Whether debug mode is enabled.
- `cache?: AzionCache[]` - List of cache configurations.
- `rules?: AzionRules` - Rules configuration.
- `deviceGroups?: AzionDeviceGroup[]` - List of device groups.
- `functionsInstances?: AzionFunctionInstance[]` - List of function instances.

### `AzionCache`

Type definition for cache configuration.

**Properties**:

- `name: string` - Name of the cache configuration.
- `stale?: boolean` - Whether to allow stale content.
- `queryStringSort?: boolean` - Whether to sort query string parameters.
- `tieredCache?: { enabled: boolean, topology?: 'nearest-region' | 'br-east-1' | 'us-east-1' }` - Tiered Cache configuration.
- `methods?: { post?: boolean, options?: boolean }` - HTTP methods to cache.
- `browser?: { maxAgeSeconds: number | string }` - Browser cache settings.
- `edge?: { maxAgeSeconds: number | string }` - Cache settings.
- `cacheByCookie?: { option: 'ignore' | 'all' | 'allowlist' | 'denylist', list?: string[] }` - Cache by cookie settings.
- `cacheByQueryString?: { option: 'ignore' | 'all' | 'allowlist' | 'denylist', list?: string[] }` - Cache by query string settings.

### `AzionRules`

Type definition for the rule set.

**Properties**:

- `request?: AzionRequestRule[]` - Rule set for the Request phase.
- `response?: AzionResponseRule[]` - Rule set for the Response phase.

### `AzionRequestRule`

Type definition for the request rule configuration.

**Properties**:

- `name: string` - Name of the request rule.
- `description?: string` - Description of the request rule.
- `active?: boolean` - Whether the rule is active.
- `match?: string` - Match criteria for the rule (legacy format).
- `variable?: RuleVariable` - Variable to be used in the match (legacy format).
- `criteria?: AzionRuleCriteria[]` - Array of criteria for complex conditions (new format).
- `behavior?: object` - Behavior to apply when the rule matches.
  - `rewrite?: string` - Rewrite the request.
  - `bypassCache?: boolean | null` - Bypass cache.
  - `httpToHttps?: boolean | null` - Force HTTPS.
  - `redirectTo301?: string | null` - Redirect with 301 status.
  - `redirectTo302?: string | null` - Redirect with 302 status.
  - `forwardCookies?: boolean | null` - Forward cookies.
  - `setCookie?: string | null` - Set a cookie.
  - `deliver?: boolean | null` - Deliver the content.
  - `deny?: boolean | null` - Deny the request.
  - `noContent?: boolean | null` - Return no content.
  - `enableGZIP?: boolean | null` - Enable GZIP compression.
  - `filterCookie?: string | null` - Filter a cookie.
  - `filterHeader?: string | null` - Filter a header.
  - `optimizeImages?: boolean | null` - Optimize images.
  - `capture?: { match: string, captured: string, subject: string }` - Capture configuration.
  - `runFunction?: string | number` - Run a function (name or ID).
  - `setCache?: string | number | { name: string | number, browser_cache_settings_maximum_ttl?: number | null, cdn_cache_settings_maximum_ttl?: number | null }` - Cache configuration.
  - `finishRequestPhase?: boolean` - Finish request phase.
  - `setConnector?: string | number` - Set connector (name or ID).
  - `addRequestHeader?: string[]` - Add headers to request.
  - `addRequestCookie?: string` - Add cookie to request.
  - `filterRequestCookie?: string` - Filter request cookie.

### `AzionResponseRule`

Type definition for the response rule configuration.

**Properties**:

- `name: string` - Name of the response rule.
- `description?: string` - Description of the response rule.
- `active?: boolean` - Whether the rule is active.
- `match?: string` - Match criteria for the rule (legacy format).
- `variable?: RuleVariable` - Variable to be used in the match (legacy format).
- `criteria?: AzionRuleCriteria[]` - Array of criteria for complex conditions (new format).
- `behavior?: object` - Behavior to apply when the rule matches.
  - `setHeaders?: string[]` - Set headers.
  - `deliver?: boolean | null` - Deliver the content.
  - `capture?: { match: string, captured: string, subject: string }` - Capture configuration.
  - `enableGZIP?: boolean | null` - Enable GZIP compression.
  - `filterHeader?: string | null` - Filter a header.
  - `runFunction?: string | number` - Run a function (name or ID).
  - `redirectTo301?: string | null` - Redirect with 301 status.
  - `redirectTo302?: string | null` - Redirect with 302 status.
  - `addResponseHeader?: string[]` - Add headers to response.
  - `filterResponseCookie?: string` - Filter response cookie.

### `AzionRuleCriteria`

Type definition for rule criteria.

**Properties**:

- `variable: RuleVariable` - Variable to be evaluated.
- `conditional: 'if' | 'and' | 'or'` - Conditional type.
- `operator: RuleOperatorWithValue | RuleOperatorWithoutValue` - Comparison operator.
- `argument?: string` - Input value for comparison (required for operators with value).

### `AzionPurge`

Type definition for purge configuration.

**Properties**:

- `type: 'url' | 'cachekey' | 'wildcard'` - The type of purge to be performed.
- `items: string[]` - List of items to be purged.
- `layer?: 'cache' | 'tiered_cache'` - Cache layer to be purged.

### `AzionNetworkList`

Type definition for network list configuration.

**Properties**:

- `name: string` - Network list name.
- `type: 'ip_cidr' | 'asn' | 'countries'` - Network list type.
- `items: string[]` - List of IP CIDRs, ASNs, or countries.
- `active?: boolean` - Whether the network list is active.

### `AzionFirewall`

Type definition for Firewall configuration.

**Properties**:

- `name: string` - Name of the firewall.
- `active?: boolean` - Whether the firewall is active.
- `functions?: boolean` - Whether Functions are enabled.
- `networkProtection?: boolean` - Whether Network Protection is enabled.
- `waf?: boolean` - Whether WAF is enabled.
- `rules?: AzionFirewallRule[]` - List of firewall rules.
- `debugRules?: boolean` - Whether debug mode is enabled for rules.
- `functionsInstances?: AzionFirewallFunctionsInstance[]` - List of firewall function instances.

### `AzionFirewallRule`

Type definition for firewall rules.

**Properties**:

- `name: string` - Name of the rule.
- `description?: string` - Description of the rule.
- `active?: boolean` - Whether the rule is active.
- `match?: string` - Match criteria for the rule (legacy format).
- `variable?: RuleVariable` - Variable to be used in the match (legacy format).
- `criteria?: AzionFirewallCriteria[]` - Array of criteria for complex conditions (new format).
- `behaviors: AzionFirewallBehavior` - Array of behaviors to be applied when the rule matches.

### `AzionFirewallBehavior`

Type definition for firewall rule behaviors (array of behaviors).

**Available behavior types**:

- `{ runFunction: string | number }` - Run a function (name or ID).
- `{ setWafRuleset: { wafMode: 'learning' | 'blocking', wafId: string | number } }` - Set WAF rule set.
- `{ setRateLimit: { type: 'second' | 'minute', limitBy: 'clientIp' | 'global', averageRateLimit: string, maximumBurstSize: string } }` - Set rate limit configuration.
- `{ deny: true }` - Deny the request.
- `{ drop: true }` - Drop the request.
- `{ setCustomResponse: { statusCode: number | string, contentType: string, contentBody: string } }` - Set custom response.

### `AzionFirewallCriteria`

Type definition for firewall rule criteria.

**Properties**:

- `variable: RuleVariable` - Variable to be evaluated.
- `conditional: 'if' | 'and' | 'or'` - Conditional type.
- `operator: RuleOperatorWithValue | RuleOperatorWithoutValue` - Comparison operator.
- `argument?: string | number` - Input value for comparison (required for operators with value).

### `AzionWaf`

Type definition for Web Application Firewall (WAF) configuration.

**Properties**:

- `name: string` - WAF name.
- `productVersion?: string` - Product version.
- `engineSettings: WafEngineSettings` - WAF engine settings.
  - `engineVersion: '2021-Q3'` - Engine version.
  - `type: 'score'` - Engine type.
  - `attributes: WafEngineAttributes` - Engine attributes.
    - `rulesets: 1[]` - Rule sets.
    - `thresholds: WafThreshold[]` - Threat thresholds.
      - `threat: 'cross_site_scripting' | 'directory_traversal' | 'evading_tricks' | 'file_upload' | 'identified_attack' | 'remote_file_inclusion' | 'sql_injection' | 'unwanted_access'` - Threat type.
      - `sensitivity: 'lowest' | 'low' | 'medium' | 'high' | 'highest'` - Sensitivity level.

### `AzionFunction`

Type definition for Function configuration.

**Properties**:

- `name: string` - Function name.
- `path: string` - Function file path.
- `runtime?: 'azion_js'` - Runtime environment.
- `defaultArgs?: Record<string, unknown>` - Default arguments to pass to the function.
- `executionEnvironment?: 'application' | 'firewall'` - Execution environment.
- `active?: boolean` - Whether the function is active.
- `bindings?: AzionFunctionBindings` - Function bindings.
  - `storage?: AzionStorageBinding` - Storage binding.
    - `bucket: string` - Bucket name or ID.
    - `prefix?: string` - Storage prefix.

### `AzionFunctionInstance`

Type definition for Function instance within an Application.

**Properties**:

- `name: string` - Instance name.
- `ref: string | number` - Reference to Function name or ID.
- `args?: Record<string, unknown>` - Instance-specific arguments.
- `active?: boolean` - Whether the instance is active.

### `AzionCustomPage`

Type definition for custom pages.

**Properties**:

- `name: string` - Custom page name.
- `active?: boolean` - Whether it's active.
- `pages: AzionCustomPageEntry[]` - Array of error page configurations.
  - `code: 'default' | '400' | '401' | '403' | '404' | '405' | '406' | '408' | '409' | '410' | '411' | '414' | '415' | '416' | '426' | '429' | '431' | '500' | '501' | '502' | '503' | '504' | '505'` - Error code.
  - `page: AzionCustomPageConnector` - Page configuration.
    - `type?: 'page_connector'` - Page type.
    - `attributes: AzionCustomPageConnectorAttributes` - Page attributes.
      - `connector: string | number` - Connector name or ID.
      - `ttl?: number` - Time to live in seconds.
      - `uri?: string | null` - URI path.
      - `customStatusCode?: number | null` - Custom status code.

### `AzionKV`

Type definition for KV Store.

**Properties**:

- `name: string` - KV Store name.

### `AzionBucket`

Type definition for Storage configuration.

**Properties**:

- `name: string` - Storage name.
- `workloadsAccess?: 'read_only' | 'read_write' | 'restricted'` - Access type.
- `dir: string` - Storage directory.
- `prefix: string` - Storage prefix.


</Fragment>

</Tabs>
---

## Example

<Tabs client:visible>
    <Fragment slot="tab.apiv3" default>API v3</Fragment>
    <Fragment slot="tab.apiv4">API v4</Fragment>

<Fragment slot="panel.apiv3">

Here's an example of an implementation of the `azion.config.js` file:

```typescript

export default {
  build: {
    entry: './src/index.js',
    preset: 'angular',
  },
  domain: {
    name: 'my_domain',
    cnameAccessOnly: false, // Optional, defaults to false
    cnames: ['www.example.com'], // Optional
    edgeApplicationId: 12345, // Optional
    edgeFirewallId: 12345, // Optional
    digitalCertificateId: 'lets_encrypt', // 'lets_encrypt' or null
    mtls: {
      verification: 'enforce', // 'enforce' or 'permissive'
      trustedCaCertificateId: 12345,
      crlList: [111, 222],
    }, // Optional
  },
  origin: [
    {
      id: 123, // Optional. ID of your origin. Obtain this value via GET request. Cannot be changed via API.
      key: 'myorigin', // Optional. Key of your origin. Obtain this value via GET request. Cannot be changed via API.
      name: 'myneworigin', // Required
      type: 'single_origin', // Required. Options: single_origin, load_balancer, object_storage, live_ingest. Defaults to single_origin if not provided.
      path: '', // Optional. Default '' if not provided
      addresses: [
        // Required for single_origin, load_balancer, live_ingest. Optional for object_storage.
        // or addresses: ['http.bin.org']
        {
          address: 'http.bin.org',
          weight: 1, // Optional. Assign a number from 1 to 10 to determine how much traffic a server can handle.
        },
      ],
      protocolPolicy: 'preserve', // Optional. Options: preserve, https, http. Defaults to preserve if not provided.
      hostHeader: '${host}', // Defaults to '${host}' if not provided
      connectionTimeout: 60, // Optional. Default 60 if not provided
      timeoutBetweenBytes: 120, // Optional. Default 120 if not provided
      redirection: false, // Optional. Default false if not provided
      hmac: {
        region: 'us-east-1', // Required for hmac
        accessKey: 'myaccesskey', // Required for hmac
        secretKey: 'secretKey', // Required for hmac
      }, // Optional
    },
    {
      id: 456, // Optional. ID of your origin. Obtain this value via GET request. Cannot be changed via API.
      key: 'myorigin', // Optional. Key of your origin. Obtain this value via GET request. Cannot be changed via API.
      name: 'myneworigin', // Required
      type: 'object_storage', // Required. Options: single_origin, load_balancer, object_storage, live_ingest. Defaults to single_origin if not provided.
      bucket: 'blue-courage', // Required for object_storage.
      prefix: '0101010101001', // Optional. Default '' if not provided.
    },
  ],
  cache: [
    {
      name: 'mycache',
      stale: false,
      queryStringSort: false,
      methods: {
        post: false,
        options: false,
      },
      browser: {
        maxAgeSeconds: 1000 * 5, // 5000 seconds
      },
      edge: {
        maxAgeSeconds: 1000,
      },
      cacheByQueryString: {
        option: 'blacklist', // Options: ['blacklist', 'whitelist', 'varies', 'ignore']
        list: ['order', 'user'],
      },
      cacheByCookie: {
        option: 'whitelist', // Options: ['blacklist', 'whitelist', 'varies', 'ignore']
        list: ['session', 'user'],
      },
    },
  ],
  rules: {
    request: [
      {
        name: 'rewriteRuleExample',
        description: 'Rewrites URLs, sets cookies and headers, and forwards cookies.',
        active: true,
        variable: 'uri', // Optional, defaults to 'uri' if not provided.
        match: '^/rewrite$',
        behavior: {
          setCache: 'mycache1',
          rewrite: `/new/%{captured[1]}`, // Rewrites /original/image.jpg to /new/image.jpg.
          setCookie: 'user=12345; Path=/; Secure',
          setHeaders: 'Cache-Control: no-cache',
          forwardCookies: true,
        },
      },
      {
        name: 'gzipCompressionRuleExample',
        description: 'Enables GZIP compression for specified paths.',
        active: true,
        variable: 'uri', // Optional, defaults to 'uri' if not provided.
        match: '^/compress',
        behavior: {
          enableGZIP: true,
        },
      },
      {
        name: 'forceHttpsRuleExample',
        description: 'Redirects HTTP requests to HTTPS for secure areas.',
        active: true,
        variable: 'uri', // Optional, defaults to 'uri' if not provided.
        match: '^/secure-area',
        behavior: {
          httpToHttps: true,
        },
      },
    ],
    response: [
      {
        name: 'apiDataResponseRuleExample',
        description: 'Manages headers, cookies, and GZIP compression for API responses.',
        active: true,
        variable: 'uri', // Optional, defaults to 'uri' if not provided.
        match: '^/api/data',
        behavior: {
          setHeaders: 'Content-Type: application/json',
          setCookie: 'session=abcdef; Path=/; HttpOnly',
          filterHeader: 'Server',
          filterCookie: 'tracking',
          enableGZIP: true,
        },
      },
      {
        name: 'computeResultFunctionRuleExample',
        description: 'Executes a function and captures the full URI path for computational results.',
        active: true,
        variable: 'uri', // Optional, defaults to 'uri' if not provided.
        match: '^/compute-result',
        behavior: {
          runFunction: {
            path: '.edge/computeResult.js',
          },
          // Captures the full URI path and stores it in the variable 'full_path_arr'.
          capture: {
            match: '^(.*)$', // The regular expression '^(.*)$' captures the full URI path.
            captured: 'full_path_arr', // The result of the capture is stored in the variable 'full_path_arr'.
            subject: 'uri', // The capture is based on the value of the 'uri' variable.
          },
          // Permanently redirects to the first element captured in 'full_path_arr'.
          redirectTo301: '%{full_path_arr[0]}', // Uses the first element of the 'full_path_arr' array as part of the new URL.
        },
      },
    ],
  },
  purge: [
    {
      type: 'url',
      urls: ['http://www.example.com/image.jpg'],
    },
    {
      type: 'cachekey',
      urls: ['https://example.com/test1', 'https://example.com/test2'],
      method: 'delete',
    },
    {
      type: 'wildcard',
      urls: ['http://www.example.com/*'],
    },
  ],
};

```
</Fragment>

<Fragment slot="panel.apiv4">

Here's an example of an implementation of the `azion.config.js` file using the new V4 structure:

```typescript
import { defineConfig } from 'azion';

export default defineConfig({
  build: {
    bundler: 'esbuild',
    entry: './src/index.js',
    preset: 'react',
    polyfills: true,
    memoryFS: {
      injectionDirs: ['./src/inject'],
      removePathPrefix: './src',
    },
  },
  workloads: [
    {
      name: 'my-production-workload',
      active: true,
      infrastructure: 1,
      domains: ['example.com'],
      workloadDomainAllowAccess: false,
      protocols: {
        http: {
          versions: ['http1', 'http2'],
          httpPorts: [80],
          httpsPorts: [443],
        },
      },
      tls: {
        certificate: 12345,
        minimumVersion: 'tls_1_2',
      },
    },
  ],
  connectors: [
    {
      name: 'My Origin',
      type: 'http',
      active: true,
      attributes: {
        addresses: [
          {
            address: 'origin.example.com',
            httpPort: 80,
            httpsPort: 443,
          },
        ],
        connectionOptions: {
          transportPolicy: 'https',
          dnsResolution: 'both',
        },
        modules: {
          loadBalancer: {
            enabled: true,
            config: {
              method: 'round_robin',
              connectionTimeout: 60,
            },
          },
          originShield: {
            enabled: false,
            config: null,
          },
        },
      },
    },
    {
      name: 'My Storage',
      type: 'storage',
      active: true,
      attributes: {
        bucket: 'my-bucket',
        prefix: 'assets/',
      },
    },
  ],
  applications: [
    {
      name: 'My App',
      active: true,
      edgeCacheEnabled: true,
      functionsEnabled: true,
      cache: [
        {
          name: 'Default Cache',
          stale: false,
          queryStringSort: false,
          tieredCache: {
            enabled: true,
            topology: 'nearest-region',
          },
          methods: {
            post: false,
            options: false,
          },
          browser: {
            maxAgeSeconds: 3600,
          },
          edge: {
            maxAgeSeconds: 7200,
          },
          cacheByQueryString: {
            option: 'allowlist',
            list: ['order', 'user'],
          },
          cacheByCookie: {
            option: 'allowlist',
            list: ['session', 'user'],
          },
        },
      ],
      rules: {
        request: [
          {
            name: 'Rewrite Rule',
            description: 'Rewrites URLs to the new format',
            active: true,
            criteria: [
              {
                variable: 'uri',
                conditional: 'if',
                operator: 'matches',
                argument: '^/old/(.*)$',
              },
            ],
            behavior: {
              rewrite: '/new/$1',
            },
          },
          {
            name: 'Force HTTPS',
            description: 'Forces redirection to HTTPS',
            active: true,
            criteria: [
              {
                variable: 'scheme',
                conditional: 'if',
                operator: 'is_equal',
                argument: 'http',
              },
            ],
            behavior: {
              httpToHttps: true,
            },
          },
        ],
        response: [
          {
            name: 'Add Security Headers',
            description: 'Adds security headers',
            active: true,
            criteria: [
              {
                variable: 'status',
                conditional: 'if',
                operator: 'is_equal',
                argument: '200',
              },
            ],
            behavior: {
              addResponseHeader: [
                'X-Content-Type-Options: nosniff',
                'X-Frame-Options: DENY',
              ],
            },
          },
        ],
      },
      functionsInstances: [
        {
          name: 'my-function-instance',
          ref: 'my-function',
          args: {
            environment: 'production',
          },
        },
      ],
    },
  ],
  functions: [
    {
      name: 'my-function',
      path: './functions/my-function.js',
      runtime: 'azion_js',
      executionEnvironment: 'application',
      active: true,
    },
  ],
  firewall: {
    name: 'My Firewall',
    active: true,
    functions: true,
    networkProtection: true,
    waf: true,
    rules: [
      {
        name: 'Block Suspicious IPs',
        active: true,
        criteria: [
          {
            variable: 'remote_addr',
            conditional: 'if',
            operator: 'is_in_list',
            argument: 'blocked_ips',
          },
        ],
        behaviors: [
          { deny: true },
        ],
      },
      {
        name: 'Rate Limit API',
        active: true,
        criteria: [
          {
            variable: 'uri',
            conditional: 'if',
            operator: 'starts_with',
            argument: '/api/',
          },
        ],
        behaviors: [
          {
            setRateLimit: {
              type: 'second',
              limitBy: 'clientIp',
              averageRateLimit: '100',
              maximumBurstSize: '200',
            },
          },
        ],
      },
    ],
  },
  waf: [
    {
      name: 'My WAF',
      engineSettings: {
        engineVersion: '2021-Q3',
        type: 'score',
        attributes: {
          rulesets: [1],
          thresholds: [
            {
              threat: 'sql_injection',
              sensitivity: 'high',
            },
            {
              threat: 'cross_site_scripting',
              sensitivity: 'high',
            },
            {
              threat: 'remote_file_inclusion',
              sensitivity: 'medium',
            },
          ],
        },
      },
    },
  ],
  networkList: [
    {
      name: 'Blocked IPs',
      type: 'ip_cidr',
      items: ['192.168.1.1', '10.0.0.0/8'],
      active: true,
    },
    {
      name: 'Blocked Countries',
      type: 'countries',
      items: ['XX', 'YY'],
      active: true,
    },
  ],
  purge: [
    {
      type: 'url',
      items: ['https://example.com/path/to/purge'],
      layer: 'cache',
    },
    {
      type: 'wildcard',
      items: ['https://example.com/images/*'],
      layer: 'tiered_cache',
    },
  ],
  customPages: [
    {
      name: 'Error Pages',
      active: true,
      pages: [
        {
          code: '404',
          page: {
            type: 'page_connector',
            attributes: {
              connector: 'My Origin',
              uri: '/errors/404.html',
              ttl: 3600,
            },
          },
        },
        {
          code: '500',
          page: {
            type: 'page_connector',
            attributes: {
              connector: 'My Origin',
              uri: '/errors/500.html',
              ttl: 3600,
            },
          },
        },
      ],
    },
  ],
  kv: [
    {
      name: 'my-kv-store',
    },
  ],
  storage: [
    {
      name: 'my-storage',
      workloadsAccess: 'read_only',
      dir: './storage',
      prefix: 'data/',
    },
  ],
});
```

---

## Rule Variables

The following variables can be used in Application and Firewall rules:

### Common Variables (Request and Response)

- `args` - Request arguments
- `device_group` - Device group
- `domain` - Domain
- `geoip_city` - City (GeoIP)
- `geoip_city_continent_code` - Continent code (GeoIP)
- `geoip_city_country_code` - Country code (GeoIP)
- `geoip_city_country_name` - Country name (GeoIP)
- `geoip_continent_code` - Continent code
- `geoip_country_code` - Country code
- `geoip_country_name` - Country name
- `geoip_region` - Region (GeoIP)
- `geoip_region_name` - Region name (GeoIP)
- `host` - Request host
- `remote_addr` - Remote IP address
- `remote_port` - Remote port
- `remote_user` - Remote user
- `request` - Complete request
- `request_body` - Request body
- `request_method` - HTTP method
- `request_uri` - Request URI
- `scheme` - Scheme (http/https)
- `uri` - URI
- `network` - Network

### Request-Specific Variables

- `server_addr` - Server address
- `server_port` - Server port
- `ssl_client_fingerprint` - SSL certificate fingerprint
- `ssl_client_escaped_cert` - Escaped SSL certificate
- `ssl_client_s_dn` - SSL certificate subject DN
- `ssl_client_s_dn_parsed` - Parsed subject DN
- `ssl_client_cert` - Client SSL certificate
- `ssl_client_i_dn` - SSL certificate issuer DN
- `ssl_client_serial` - SSL certificate serial number
- `ssl_client_v_end` - SSL certificate validity end date
- `ssl_client_v_remain` - SSL certificate remaining days
- `ssl_client_v_start` - SSL certificate validity start date
- `ssl_client_verify` - SSL verification status

### Response-Specific Variables

- `sent_http_name` - Sent HTTP name
- `status` - HTTP status code
- `tcpinfo_rtt` - TCP round-trip time
- `upstream_addr` - Upstream address
- `upstream_status` - Upstream status

### Dynamic Variables

You can also use dynamic variables with the prefixes:

- `arg_{name}` - Specific arguments
- `cookie_{name}` - Specific cookies
- `http_{name}` - Specific HTTP headers
- `sent_http_{name}` - Sent HTTP headers
- `upstream_cookie_{name}` - Upstream cookies
- `upstream_http_{name}` - Upstream HTTP headers

---

## Comparison Operators

### Operators with Value

- `is_equal` - Is equal to
- `is_not_equal` - Is not equal to
- `starts_with` - Starts with
- `does_not_start_with` - Does not start with
- `matches` - Matches (regex)
- `does_not_match` - Does not match (regex)
- `is_in_list` - Is in list
- `is_not_in_list` - Is not in list

### Operators without Value

- `exists` - Exists
- `does_not_exist` - Does not exist

---

## Migration from V3 to V4

If you're migrating from a previous version, here are the main changes:

### Updated Nomenclature

- `Edge Application` → `Application`
- `Edge Functions` → `Functions`
- `Edge Firewall` → `Firewall`
- `Edge SQL` → `SQL Database`
- `Edge Cache` → `Cache`
- `Edge Storage` → `Object Storage`
- `Network Layer Protection` → `Network Shield`
- `Edge KV` → `KV Store`
- `Edge Connectors` → `Connectors`
- `Origin` → `Connector` (new, more flexible concept)

### Configuration Structure

The structure changed from a flat configuration to a hierarchical structure:

**V3 (previous):**
```javascript
{
  origin: [...],
  cache: [...],
  rules: {...}
}
```

**V4 (current):**
```javascript
{
  workloads: [...],
  connectors: [...],
  applications: [{
    name: 'My App',
    cache: [...],
    rules: {...}
  }]
}
```

### Origins to Connectors

The `origin` concept evolved to `connectors`, offering more flexibility:

**V3 (previous):**
```javascript
origin: [{
  name: 'my-origin',
  type: 'single_origin',
  addresses: ['origin.example.com']
}]
```

**V4 (current):**
```javascript
connectors: [{
  name: 'My Origin',
  type: 'http',
  attributes: {
    addresses: [{ address: 'origin.example.com' }],
    connectionOptions: { transportPolicy: 'https' }
  }
}]
```

### Rules with Criteria

Rules now support a more powerful criteria structure:

**V3 (previous):**
```javascript
rules: {
  request: [{
    name: 'My Rule',
    match: '^/api/',
    behavior: { ... }
  }]
}
```

**V4 (current):**
```javascript
applications: [{
  rules: {
    request: [{
      name: 'My Rule',
      criteria: [{
        variable: 'uri',
        conditional: 'if',
        operator: 'starts_with',
        argument: '/api/'
      }],
      behavior: { ... }
    }]
  }
}]
```

### Firewall Behaviors

Firewall behaviors are now an array, allowing multiple actions:

**V3 (previous):**
```javascript
behavior: {
  deny: true
}
```

**V4 (current):**
```javascript
behaviors: [
  { deny: true }
]
```

### WAF with Thresholds

WAF now uses a more granular thresholds structure:

**V3 (previous):**
```javascript
waf: [{
  name: 'My WAF',
  mode: 'blocking',
  sqlInjection: { sensitivity: 'high' }
}]
```

**V4 (current):**
```javascript
waf: [{
  name: 'My WAF',
  engineSettings: {
    engineVersion: '2021-Q3',
    type: 'score',
    attributes: {
      rulesets: [1],
      thresholds: [
        { threat: 'sql_injection', sensitivity: 'high' }
      ]
    }
  }
}]
```

---

## Additional Notes

### Configuration Validation

`defineConfig` automatically validates your configuration and provides clear errors if there are issues. Use TypeScript to get autocomplete and type checking during development.

### References by Name or ID

Many properties accept both names and IDs, allowing you to use more readable references:

```javascript
// By name (validated during build)
runFunction: 'my-function'

// By ID (used directly)
runFunction: 12345
```

### Custom Presets

You can create custom presets to reuse configurations:

```typescript
import { defineConfig } from 'azion';
import type { AzionBuildPreset } from 'azion/config';

const myCustomPreset: AzionBuildPreset = {
  config: {
    build: {
      bundler: 'esbuild',
      polyfills: true,
    },
  },
  metadata: {
    name: 'my-custom-preset',
    registry: 'my-registry',
  },
  prebuild: async (config, ctx) => {
    console.log('Running prebuild...');
    // Custom prebuild logic
  },
};

export default defineConfig({
  build: {
    preset: myCustomPreset,
  },
});
```

### CLI Integration

The `azion.config.js` file is automatically detected by the Azion CLI. You can:

- Use `azion build` to build your project with the defined configurations
- Use `azion deploy` to deploy your application
- Use `azion dev` for local development with hot reload


</Fragment>
</Tabs>

---

## Related Resources

- [Functions](/en/documentation/products/build/applications/functions/) - Serverless compute on Azion Platform
- [Applications](/en/documentation/products/build/applications/) - Configure and manage your applications
- [Firewall](/en/documentation/products/secure/firewall/) - Protect your applications
- [WAF](/en/documentation/products/secure/firewall/web-application-firewall/) - Web Application Firewall
- [Cache](/en/documentation/products/build/applications/cache/) - Configure cache policies
- [Object Storage](/en/documentation/products/store/object-storage/) - Object storage