Skip to content

Running the Worker

AI Worker is middleware: it sits between Magento and your AI provider, sends the request and returns the result. You choose where that middleware runs. Local Node, a production Node service and Cloudflare all use the same worker.js from the AI Worker package.

The hosting choice determines who manages the infrastructure, how the worker reaches Magento and how long it can keep working. Your models, provider API keys and saved jobs remain configured in Magento. Your AI provider still runs the model and charges for its usage.

Choose Where to Run It

Where When to use it What you manage
Local Node or Docker Recommended for development, including a private local Magento installation. Start the worker alongside your development environment.
Your own Node service Production when your team wants to operate the worker itself. Hosting, HTTPS, process supervision, capacity and runtime updates.
Cloudflare Workers Recommended for production when you want a serverless service to manage the infrastructure. Deploy the script, configure secrets and monitor requests and updates.

Complete package installation and Magento configuration first. Each setup uses the same two worker secrets and Magento connection settings. Node's adapter and the shared script are included in the package; no npm install or application build is needed. Keep them from the same package version.

The included PHP fallback runs inside Magento and remains subject to the store's PHP capacity and server timeouts. It is a baseline or backup, not the recommended hosting choice for streaming or production.

Local Development

Complete package installation and Magento configuration first. The adapter requires Node 20 or later (--env-file requires 20.6 or later); the supplied Docker image uses Node 22. Use a supported Node release suitable for your environment.

Node Process

From the Magento project root, copy the example to a project-owned, ignored file:

cp vendor/hyva-themes/commerce-module-ai-worker/worker/runtimes/node/.env.example ai-worker.env
chmod 600 ai-worker.env

Add ai-worker.env to your project's .gitignore. Fill in the two matching worker secrets, ALLOWED_ORIGIN and MAGENTO_ALLOWED_ORIGIN from Worker Setup. Configure the listener:

HOST=127.0.0.1
PORT=8787
MAX_CONCURRENT_REQUESTS=8
TLS_CERT_FILE=/absolute/path/to/worker-certificate.pem
TLS_KEY_FILE=/absolute/path/to/worker-private-key.pem
NODE_EXTRA_CA_CERTS=/absolute/path/to/local-root-ca.pem

Use a certificate for the worker hostname that the browser and Magento PHP trust. NODE_EXTRA_CA_CERTS lets the worker trust Magento's certificate. If a local reverse proxy terminates HTTPS, omit the two TLS_* values and route that proxy to the Node listener.

Start the service:

node --env-file=/absolute/path/to/magento/ai-worker.env vendor/hyva-themes/commerce-module-ai-worker/worker/runtimes/node/server.mjs

Set External Worker URL to the corresponding HTTPS hostname and port. The browser and PHP must both resolve it to the worker. Ensure the worker resolves Magento's hostname to the local web proxy, not its own loopback address.

Docker

From the worker directory:

cd vendor/hyva-themes/commerce-module-ai-worker/worker
export AI_WORKER_ENV_FILE=/absolute/path/to/magento/ai-worker.env
docker compose -f runtimes/docker/docker-compose.yml up --build

The supplied service uses a non-root Node process. It exposes port 8787, but does not configure a public HTTPS hostname or your Magento network automatically. Add project-owned Compose overrides for the network, certificates and reverse proxy. Use HOST=0.0.0.0 inside the container so the published port can reach the listener. Mount the local CA and set NODE_EXTRA_CA_CERTS to its path inside the container.

Inside Compose, localhost is the container itself, so http://localhost:8787 reaches the worker from your browser but not from Magento's PHP. Give the worker a hostname that resolves the same way on the host and inside the containers, and serve it over HTTPS with a certificate both trust. Magento refuses a plain HTTP worker URL on save unless the host is localhost, 127.0.0.1 or [::1], and the worker applies the same rule to its callback URL. The runtime README in the package shows the recipe: a hostname in your development TLD with a certificate from the stack's CA. The Warden helper below does the same for that stack.

Keep AI_WORKER_ENV_FILE absolute; relative paths resolve against the Compose file. The image's build context must include both worker.js and the runtime adapter. Rebuild after worker updates.

The optional worker/runtimes/warden/start.sh helper automates certificates and networking for Warden. It is a convenience for that stack, not a requirement for Node or Docker. Follow the shipped runtime README if you use it.

After saving the worker URL, run Magento's Test Connection and confirm the external worker passes. Generate and save a small draft to check the complete flow.

Production

Choose a managed serverless deployment or run the Node service on infrastructure your team controls. Both perform the same middleware work outside Magento's PHP processes. Cloudflare is the ready-to-use serverless option supplied with this package; other serverless services need their own integration and testing.

Your Own Server (Node)

Deploy the package's worker/ directory on a separate service host with no Magento source, database credentials, Redis access or shared Magento filesystem mounts. It needs HTTPS access back to Magento and out to the configured AI providers. The admin browser and all Magento nodes need access to its HTTPS endpoint.

Runtime Configuration

Store secrets in a service-owned environment file or your platform's secret manager. Include the shared settings and:

NODE_ENV=production
HOST=127.0.0.1
PORT=8787
MAX_CONCURRENT_REQUESTS=8
SHUTDOWN_GRACE_MS=660000

This example assumes a reverse proxy on the same host and permits shutdown long enough for a ten-minute request plus callback delivery. Size both concurrency and shutdown grace for your workload and service manager. The runtime default shutdown grace is only 30 seconds.

Set HOST=0.0.0.0 for a container whose listener must be reached from another container. Restrict ingress through your network/proxy configuration. INSECURE_SKIP_TLS_VERIFY=1 is refused when NODE_ENV=production; install the correct CA trust instead.

Example systemd Service

The paths and user below are deployment choices, not files created by Magento. Copy worker/ to /opt/hyva-ai-worker, create a restricted service account and provision /etc/hyva-ai-worker.env for that account:

[Unit]
Description=Hyva AI Worker
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=hyva-ai-worker
Group=hyva-ai-worker
WorkingDirectory=/opt/hyva-ai-worker
EnvironmentFile=/etc/hyva-ai-worker.env
Environment=MALLOC_ARENA_MAX=2
ExecStart=/usr/bin/node /opt/hyva-ai-worker/runtimes/node/server.mjs
Restart=on-failure
RestartSec=5
TimeoutStopSec=680
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Adjust the Node executable path and service stop timeout for the host. MALLOC_ARENA_MAX belongs in the process environment before Node starts, rather than Node's --env-file, because glibc reads it at process startup.

HTTPS and Streaming Proxy

Terminate TLS at your proxy or configure the runtime's TLS_CERT_FILE and TLS_KEY_FILE. For a dedicated Nginx worker hostname, the relevant location can look like:

location / {
    proxy_pass http://127.0.0.1:8787;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header Connection "";
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 660s;
    proxy_send_timeout 660s;
}

This is only the location inside a server block where you already configured the hostname and TLS certificate. Validate it against your deployment and any load balancer in front. Nginx's read timeout measures gaps between reads, not total request duration; see the proxy module reference. Magento's own PHP/proxy configuration need not be raised to these worker-stream limits.

Start, Verify and Update

  1. Start the supervised service and inspect GET /v1/health on its HTTPS endpoint.
  2. Save that base URL as Magento's External Worker URL, then use Test Connection.
  3. Generate and save a small CMS draft. Verify an image separately if enabled.
  4. Keep Magento cron running. Automatic transport detection uses self-hosted /v1/dispatch for bulk jobs, so this deployment does not need the Cloudflare connection-holder consumer.
  5. For updates, deploy the runtime files, drain/restart the service with its configured grace period, then repeat the checks.

Multiple worker instances can share the same secrets behind a routable endpoint; durable job state stays in Magento. Do not assume a process per Magento node automatically creates an endpoint browsers can reach.

MAX_CONCURRENT_REQUESTS defaults to eight and conservatively counts active requests and background work; a streaming generation can occupy two entries. Saturation returns HTTP 503 with Retry-After while health checks remain available. Monitor memory, concurrency and provider quotas before increasing it.

Cloudflare Workers

Use your own Cloudflare account and separate workers and secrets for development, staging and production. Deploy the worker/worker.js from your installed hyva-themes/commerce-module-ai-worker package. No Pages project, database binding, KV or Durable Object is needed.

Choose either the dashboard steps or Wrangler. Both deploy the same file. Complete Prepare Magento first and have the two saved worker secrets available.

Download the Worker

In Magento, open Stores → Configuration → Hyvä AI → AI Worker and select Download worker.js. Open the downloaded file in a text editor to copy its contents. The download requires the Hyvä AI Worker Section admin permission.

This is the complete JavaScript file from your installed module, with no build step or extra files needed for Cloudflare's editor. It contains no store secrets or provider API keys. Configure the secrets and origin settings separately using the steps below. Download it again after updating the Magento package to keep the deployed worker aligned.

If you have filesystem access, the same file is at vendor/hyva-themes/commerce-module-ai-worker/worker/worker.js.

Dashboard Setup

1. Create the Worker
  1. Sign in to the Cloudflare dashboard and select the account that will own the worker.
  2. Open Workers & Pages, then Create application.
  3. Select the Hello World template. Give the worker a name, such as hyva-ai-worker-production, and choose Deploy.
  4. Open the deployed worker and select Edit code.
  5. Open the downloaded worker.js in a text editor. Copy the entire file.
  6. Replace all of the starter script in Cloudflare's code editor with that content, then select Deploy. Keep the script intact; secrets are entered in settings below.

Cloudflare documents the dashboard creation flow and the Hello World / Edit code workflow.

2. Add the Secrets
  1. Return to Workers & Pages and open your worker.
  2. Open Settings → Variables and Secrets → Add.
  3. Choose type Secret, enter TOKEN_SIGNING_SECRET as the name and paste Magento's Token Signing Secret as its value.
  4. Choose Add variable. Use type Secret again, name it KEY_ENCRYPTION_SECRET and paste Magento's separate Key Encryption Secret.
  5. Select Deploy to apply them.

Both values must match the saved Magento configuration. Keep provider API keys in Magento; they are not deployment secrets. See Cloudflare's secret settings.

3. Allow Your Store's Addresses

Return to Settings → Variables and Secrets → Add. Add these as Text variables, then select Deploy:

Variable name Value
ALLOWED_ORIGIN The origin you use to open Magento admin, for example https://admin.example.com. Include a port if used, but no path or trailing slash.
MAGENTO_ALLOWED_ORIGIN The HTTPS origin the worker uses to reach Magento, for example https://shop.example.com. Use the origin of Worker Callback Base URL if you configured that override.

The origins can be the same when admin and storefront share a host. They are Magento addresses, not the worker's address. See Cloudflare's variable settings.

In the worker's Settings, find Compatibility date and set it to the date in the package's worker/wrangler.toml (currently 2026-06-01). Save/deploy the change. Cloudflare otherwise sets new dashboard workers to the creation date; see compatibility date settings.

4. Connect Magento
  1. Copy the worker's deployed workers.dev address, such as https://hyva-ai-worker-production.your-account.workers.dev. Use the deployed address, not the editor's preview URL.
  2. In Magento, open Stores → Configuration → Hyvä AI → AI Worker.
  3. Paste the address into External Worker URL, without an endpoint such as /v1/stream.
  4. Review PHP Worker and Backup → Enable PHP Worker. Leave it on only if the store can spare PHP capacity during an external outage; turn it off for external-only operation.
  5. Save the configuration, then select Test Connection. Confirm the external worker passes, even if PHP backup also passes.
  6. Generate a small CMS draft and save it. Test images and background jobs separately if you use them.

For protected staging, configure Basic auth. For a private store, see Private Development and Staging. Retrieval and callbacks must reach Magento without a login page, redirect or interactive challenge.

A starter greeting means the Hyvä script is not deployed. Visiting /v1/health reports runtime health and version, but does not verify the Magento secrets or provider access on its own.

Wrangler Deployment

For repeatable deployments, copy the package's worker.js and wrangler.toml into a project-owned deployment directory. Set the worker name, update ALLOWED_ORIGIN and add MAGENTO_ALLOWED_ORIGIN under [vars] in wrangler.toml, using the values shown above. From that directory, run:

npx wrangler login
npx wrangler secret put TOKEN_SIGNING_SECRET
npx wrangler secret put KEY_ENCRYPTION_SECRET
npx wrangler deploy

Enter the matching Magento secrets at the prompts. Keep them out of wrangler.toml and source control. Follow Connect Magento using the deployed URL printed by Wrangler. Choose one managed deployment workflow so dashboard edits and CLI deployments do not overwrite each other's configuration.

Background Jobs

Keep Magento cron running. Cloudflare bulk jobs also need a supervised Magento consumer:

bin/magento queue:consumers:start hyvaAiWorkerJobChunk

The scheduler selects /v1/complete automatically; the consumer holds a connection while the worker generates. This uses a Magento CLI process, but does not hold a PHP-FPM web request or admin session lock. Do not force self-hosted dispatch for long Cloudflare jobs: work after the response has a limited grace period.

After deployment, restart consumers and inspect:

bin/magento hyva:ai-worker:scheduler:run --status

Limits and Cost

Check Workers limits and current pricing when choosing a plan. Network waiting does not count as CPU time, but parsing large responses and processing images does. Test realistic generations; a free plan is not a guarantee that your workload fits. Provider API usage is billed separately.

Cloudflare can continue an HTTP request while its client remains connected. After the response ends or the client disconnects, waitUntil extends execution for at most 30 seconds. Hyvä also enforces its own maximum request duration. Browser disconnect recovery cannot guarantee completion after the host's grace period. See Cloudflare's duration limits.

Worker Updates

Deploy worker.js from the installed module version and retain matching secrets and origin variables unless deliberately rotating them. The required runtime is 1.0.0. Repeat the connection, generation and background-job checks after an update.

Private Development and Staging

A hosted worker cannot resolve a private development hostname. If you need to test it against a private store, expose Magento through a trusted HTTPS tunnel and set Worker Callback Base URL to the tunnel base URL. Keep the tunnel running and update the setting if its address changes.

ALLOWED_ORIGIN remains the origin used to open admin in your browser. Set MAGENTO_ALLOWED_ORIGIN to the tunnel origin.

Use a tunnel without an interstitial page

If the tunnel presents an interactive warning, login page or redirect, the hosted worker's request retrieval fails. Pick a tunnel that passes requests straight through to Magento.

Run Magento's Test Connection, then generate and save a small draft. See troubleshooting for DNS, certificate and one-time-request errors.

Other Serverless Worker Services

Cloudflare is the only serverless platform with a ready-to-deploy worker supplied in this package. The services below offer a similar managed execution model, but they are candidates for an integration, not supported copy-and-paste alternatives. No adapters or deployment tests for them are included.

Service What an integration would need
Deno Deploy A Deno request handler and environment-variable mapping. Its serverless lifecycle can stop or evict instances, so background work and callback delivery need explicit handling. Use current Deno Deploy documentation; Deploy Classic is a different, retired platform.
Netlify Edge Functions A Netlify handler, route configuration, secrets and context.waitUntil integration. Its 50 ms CPU budget and 40-second response-header timeout need careful testing against token verification, stream parsing and image requests. It is not a general recommendation for this workload.
Supabase Edge Functions A function entry point, routing/authentication configuration that accepts Hyvä's signed tokens, environment variables and background-task handling. Its 150-second free / 400-second paid worker lifetime and 2-second CPU limit can prevent longer generations from finishing.

These are compatibility assessments from the platform documentation, not confirmation that Hyvä AI Worker has run successfully on those services. For a setup that works with the supplied script, follow the Cloudflare instructions above. Deno Deploy's current platform replaces Deploy Classic. Vercel is not listed as a new edge-worker setup because it deprecates Edge Functions for new projects.

Requirements for a Platform Adapter

The shared JavaScript needs fetch, Request/Response, streaming responses, Web Crypto and an adapter for fetch(request, env, ctx). Secrets must be supplied through env; the host must support outbound HTTPS to Magento and the provider, and expose trusted HTTPS to Magento and the admin browser.

Check maximum request duration, response buffering, disconnect behaviour and work after the response. An API-compatible host can still terminate a long generation. The current script distinguishes Cloudflare from self-hosted runtimes; another serverless host needs an adapter and transport review so it is not treated as an unrestricted self-hosted process. Report accurate health capabilities and use a connected holder where detached work cannot run for the required duration. Verify text streaming, images, callbacks and background jobs before production. The supplied Cloudflare and Node setups provide concrete reference implementations.