https://opengraph.githubassets.com/70092b9337715852f5e8fc859bcc65456f92e594efce0331913610382476bb4d/hschimpf/laravel-appsync-events
Broadcast Laravel events over AWS AppSync Event APIs — managed, serverless WebSocket fan-out — with a matching Laravel Echo 2 connector on the client. The package publishes events with SigV4-signed HTTP calls, authorizes connections and subscriptions through an AppSync Lambda authorizer that verifies HMAC tokens issued by your app, and ships the Echo connector as @hds-solutions/laravel-echo-appsync.
Warning
This package is in beta. The API may change between releases — pin an exact version in composer.json/package.json and check the changelog before upgrading. Found a bug or rough edge? Report it on GitHub.
AWS AppSync Event APIs give you a managed WebSocket endpoint: AWS holds the sockets, routes published events to channel subscribers, and scales the fan-out for you. This package plugs that into Laravel’s broadcasting layer — ShouldBroadcast events, routes/channels.php authorization, Broadcast::channel() — so you get realtime delivery without running Reverb, Pusher, or any WebSocket server of your own.
Use it when you want Laravel-native broadcasting but can’t (or don’t want to) operate a WebSocket fleet. AppSync Events is billed per published event and per connection time — check the AWS pricing page for current numbers.
The community package 7amoood/laravel-appsync-broadcaster solves the same problem with a different shape: Cognito OAuth for auth, a Redis-backed worker, and a Pawl WebSocket client that keeps a persistent publish connection; it ships no Echo connector. This package instead:
- publishes over HTTP with SigV4/IAM — a stateless
POST /event, no persistent publisher socket, no worker; - authorizes connections/subscriptions with a Lambda authorizer that verifies HMAC tokens your app issues (no Cognito, no Redis);
- ships an Echo 2 connector so the frontend stays
echo.private('orders.1').listen(...).
flowchart LR
subgraph Laravel
E["Event (ShouldBroadcast)"] --> B["AppSyncBroadcaster (SigV4)"]
R["/broadcasting/auth"] --> TS["TokenSigner (HMAC secret)"]
end
subgraph AWS
B -- "POST /event (IAM)" --> A["AppSync Event API"]
A -- "EVENT_CONNECT / EVENT_SUBSCRIBE" --> L["Lambda authorizer"]
L -. "verifies" .- TS
A -- "WebSocket" --> C["Echo connector"]
end
C -. "{socket_id, channel_name}" .-> R
R -. "{auth: subscribeToken}" .-> C
TS -. "clientConfig: connectToken" .-> C
Loading
- A
ShouldBroadcastevent fires;AppSyncBroadcasterSigV4-signs aPOST /eventto the Event API’s HTTP endpoint with IAM credentials. - AppSync delivers the event to every client subscribed to the mapped channel path (
/private/orders/1forprivate-orders.1). - The browser connects with a connect token (from
AppSyncEvents::clientConfig()) and asks your app for a per-channel subscribe token viaPOST /broadcasting/auth— the standard Echo channel-auth flow. - AppSync calls your Lambda authorizer for
EVENT_CONNECTandEVENT_SUBSCRIBE;AppSyncAuthorizerverifies the token’s HMAC signature, purpose and channel. EVENT_PUBLISHis always denied — clients can never publish; publishing is a server-side, IAM-only operation.
| Component | Version |
|---|---|
| PHP | ^8.2 |
| Laravel / Illuminate | ^11.0 | ^12.0 | ^13.0 |
| laravel-echo (peer) | ^2.0 |
Node.js (build & test the js/ package) |
>= 22 — the published package runs in browsers |
| AWS | An AppSync Event API (not a GraphQL API) — see AWS setup |
composer require hds-solutions/laravel-appsync-events php artisan appsync-events:install # publishes config, adds .env placeholders php artisan appsync-events:secret # generates APPSYNC_CHANNEL_SIGNING_SECRET npm install laravel-echo @hds-solutions/laravel-echo-appsync
Then set the environment values (the install command adds the placeholders to .env.example):
BROADCAST_CONNECTION=appsync APPSYNC_HTTP_ENDPOINT=https://<id>.appsync-api.<region>.amazonaws.com/event APPSYNC_REALTIME_ENDPOINT=wss://<id>.appsync-realtime-api.<region>.amazonaws.com/event/realtime APPSYNC_CHANNEL_SIGNING_SECRET=<64 hex chars from appsync-events:secret>
appsync-events:secret --show prints a secret without touching .env; --force overwrites an existing one. The same secret must be deployed to the Lambda authorizer — it is never sent to AWS or to clients.
1. Authorize the channel — routes/channels.php:
use App\Models\User; use Illuminate\Support\Facades\Broadcast; Broadcast::channel('orders.{id}', function (User $user, int $id) { return $user->can('view-order', $id); });
2. Broadcast an event:
use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class OrderShipped implements ShouldBroadcast { public function __construct(public readonly int $orderId) {} public function broadcastOn(): array { return [new PrivateChannel('orders.'.$this->orderId)]; } }
3. Listen in the frontend:
import Echo from 'laravel-echo'; import { appSyncEchoOptions } from '@hds-solutions/laravel-echo-appsync'; const echo = new Echo(appSyncEchoOptions({ wsEndpoint: 'wss://<id>.appsync-realtime-api.<region>.amazonaws.com/event/realtime', connectToken: () => fetchConnectToken(), // re-evaluated on every (re)connect })); echo.private('orders.1').listen('.OrderShipped', (e: unknown) => { console.log(e); });
The Laravel channel name private-orders.1 (Echo adds private-) maps to the AppSync channel path /private/orders/1 — so a private channel namespace must exist on the Event API.
Before the driver works, AWS needs:
- an Event API with auth providers
AWS_LAMBDA+AWS_IAM(plusAPI_KEYonly if you use public channels), connection modeAWS_LAMBDA, default publish modeAWS_IAM, default subscribe modeAWS_LAMBDA; - the
publicandprivatechannel namespaces (or your configured names) — AppSync namespaces are the authorization boundary, so theprivatenamespace subscribes via your Lambda authorizer whilepublicmay also allowAPI_KEY; - a Lambda authorizer holding the same
APPSYNC_CHANNEL_SIGNING_SECRET, with alambda:InvokeFunctionresource policy forappsync.amazonaws.comscoped to the API ARN; - an IAM policy granting your app’s role
appsync:EventPublishonarn:aws:appsync:<region>:<account>:apis/<api-id>/channelNamespace/<namespace>.
Full walkthrough plus CloudFormation, Serverless Framework, Terraform and CDK examples: docs/aws-setup.md.
AppSync Events offers five authorization types; this package uses three of them:
| Type | Used for | Supported |
|---|---|---|
AWS_IAM |
Your app publishing events (SigV4 POST /event) |
Yes — required |
AWS_LAMBDA |
Clients connecting and subscribing to private channels, with Laravel’s Broadcast::channel() callbacks deciding access |
Yes — required for private channels |
API_KEY |
Anonymous, read-only public channels | Yes — optional |
OPENID_CONNECT |
Clients authenticating with an OIDC provider | No |
AMAZON_COGNITO_USER_POOLS |
Clients authenticating with Cognito | No |
The package is PHP-strict: your Laravel users and routes/channels.php stay the source of truth, so Cognito and OIDC client authentication are out of scope. AppSync lets you set the authorization mode per namespace, so public channels (API_KEY) and private channels (AWS_LAMBDA) can live side by side on the same Event API.
Your Laravel app is not tied to a particular host. The broadcaster signs publish requests with the AWS SDK’s default credential chain (environment variables, web identity, ECS task role, EC2 instance profile), so wherever your app runs with an IAM role, it should need no keys in config — the role only needs appsync:EventPublish. /broadcasting/auth needs no AWS access.
Note
The platform notes below come from the platform documentation and the SDK’s credential chain; they have not been tested on a real Laravel Vapor or ECS deployment. Please verify them in your environment.
- Laravel Vapor — per Vapor’s docs, your app’s Lambda runs under the
laravel-vapor-rolerole and reserves theAWS_*credential and region variables. You will likely need to addappsync:EventPublishto that role; Vapor manages it itself, so see Laravel’s Customize Default Role post before editing it. Don’t setAWS_*keys yourself;APPSYNC_REGIONcan override the region. - Docker / ECS — grant the permission to the task role instead of configuring keys.
The authorizer below is the one piece AppSync invokes directly, so it must run on Lambda. As far as we know Vapor only deploys your Laravel app’s own functions, so plan to deploy the authorizer with another tool (Serverless Framework with Bref, CloudFormation, Terraform or CDK — see docs/aws-setup.md); it only needs the same APPSYNC_CHANNEL_SIGNING_SECRET.
AppSyncAuthorizer::authorize(array $event): array (HDSSolutions\Laravel\AppSyncEvents\Lambda) verifies the authorizer event and returns the AppSync contract {isAuthorized, ttlOverride, handlerContext?}:
EVENT_CONNECT→ verified, unexpired token withpurpose: connect.EVENT_SUBSCRIBE→ verified, unexpiredpurpose: subscribetoken whosechannelclaim equalsrequestContext.channel.EVENT_PUBLISH(and anything else) → always denied.
The class is framework-agnostic — constructor-injected secret, no container access — so it runs under any PHP Lambda runtime.
<?php use HDSSolutions\Laravel\AppSyncEvents\Lambda\AppSyncAuthorizer; return function (array $event): array { return (new AppSyncAuthorizer( $_ENV['APPSYNC_CHANNEL_SIGNING_SECRET'] ?? '', (int) ($_ENV['APPSYNC_AUTHORIZER_CACHE_TTL'] ?? 300), $_ENV['APPSYNC_CHANNEL_PREVIOUS_SIGNING_SECRETS'] ?? '', ))->authorize($event); };
Bref is one way to run PHP on Lambda — it is not a dependency of this package. With Bref 3, an event handler implements Bref\Event\Handler (see Bref function handlers):
<?php namespace App\Lambda; use Bref\Context\Context; use Bref\Event\Handler; use HDSSolutions\Laravel\AppSyncEvents\Lambda\AppSyncAuthorizer; final class AppsyncEventsAuthorizer implements Handler { public function handle($event, Context $context): array { // If the function boots your Laravel app (e.g. bref/laravel-bridge), // resolve from the container instead: app(AppSyncAuthorizer::class) return (new AppSyncAuthorizer( $_ENV['APPSYNC_CHANNEL_SIGNING_SECRET'] ?? '', previousSecrets: $_ENV['APPSYNC_CHANNEL_PREVIOUS_SIGNING_SECRETS'] ?? '', ))->authorize($event); } }
functions: authorizer: handler: App\Lambda\AppsyncEventsAuthorizer runtime: php-82 environment: APPSYNC_CHANNEL_SIGNING_SECRET: ${ssm:/my-app/appsync-signing-secret} # The authorizer must never broadcast itself — see warning below. BROADCAST_CONNECTION: log APPSYNC_HTTP_ENDPOINT: '' APPSYNC_REALTIME_ENDPOINT: ''
Warning — no self-invocation. The authorizer Lambda must never broadcast: if it boots your application, force
BROADCAST_CONNECTION=log(ornull) and leave the AppSync endpoint env vars empty. A function that publishes to the API it authorizes can invoke itself recursively.
config/appsync-events.php (publish with php artisan vendor:publish --tag=appsync-events-config):
| Key | Env var | Default | Description |
|---|---|---|---|
http_endpoint |
APPSYNC_HTTP_ENDPOINT |
— | Event API HTTP endpoint the broadcaster POSTs to. Required. |
realtime_endpoint |
APPSYNC_REALTIME_ENDPOINT |
— | WebSocket endpoint handed to the JS connector. Required for clientConfig(). |
signing_secret |
APPSYNC_CHANNEL_SIGNING_SECRET |
— | HMAC secret shared with the Lambda authorizer. Required. |
previous_signing_secrets |
APPSYNC_CHANNEL_PREVIOUS_SIGNING_SECRETS |
— | Comma-separated previous secrets still accepted for verification during rotation; never used for signing. Optional. |
region |
APPSYNC_REGION → AWS_DEFAULT_REGION |
us-east-1 |
SigV4 region fallback when it can’t be parsed from http_endpoint. |
namespaces.public |
APPSYNC_PUBLIC_NAMESPACE |
public |
AppSync namespace public channel names map onto; must exist on the Event API. |
namespaces.private |
APPSYNC_PRIVATE_NAMESPACE |
private |
AppSync namespace private- channel names map onto; must exist on the Event API. |
tokens.connect_ttl |
— | 43200 |
Connect token lifetime, seconds (12 h). |
tokens.subscribe_ttl |
— | 3600 |
Subscribe token lifetime, seconds (1 h). |
authorizer.cache_ttl |
— | 300 |
ttlOverride the authorizer returns for authorized calls. |
http.timeout |
— | 2.0 |
Publish request timeout, seconds. |
http.connect_timeout |
— | 1.0 |
Publish connect timeout, seconds. |
uid_resolver |
— | null |
Invokable class-string to derive the uid token claim; null = getAuthIdentifier(). |
client.auth_endpoint |
— | /broadcasting/auth |
Where the connector requests channel authorization. |
client.inactivity_timeout |
APPSYNC_INACTIVITY_TIMEOUT |
10 |
Seconds; shipped in clientConfig() for your client code to consume (see Vue composable). |
routes.auth.enabled |
— | true |
Registers /broadcasting/auth via Broadcast::routes() (never shadows your own route). |
routes.auth.middleware |
— | ['web'] |
Middleware on the auth endpoint. |
routes.client_config.enabled |
— | false |
Opt-in JSON endpoint serving the connector config. |
routes.client_config.uri |
— | broadcasting/appsync |
URI of the client-config endpoint. |
routes.client_config.middleware |
— | ['web', 'auth'] |
Middleware on the client-config endpoint. |
The appsync broadcasting connection merges over the package config, so config/broadcasting.php may override http_endpoint, signing_secret, previous_signing_secrets, region, namespaces and http.* per connection. A connection that sets its own signing_secret must also set its own previous_signing_secrets — the package-level previous list is never carried onto a different primary secret:
'connections' => [ 'appsync' => [ 'driver' => 'appsync', // 'http_endpoint' => env('APPSYNC_HTTP_ENDPOINT'), // optional override ], ],
| Method | Returns |
|---|---|
AppSyncEvents::clientConfig(?Authenticatable $user = null) |
Connector options {wsEndpoint, httpHost, connectToken, authEndpoint, publicNamespace, privateNamespace, inactivityTimeout} — null for guests. The connectToken is a static string minted once. |
AppSyncEvents::uid($user) |
The uid claim for tokens: runtime closure → uid_resolver class → getAuthIdentifier(). |
AppSyncEvents::resolveUidUsing(Closure) |
Set the uid strategy at runtime (config is not a place for closures). |
AppSyncEvents::signer() |
The TokenSigner bound to signing_secret (connectToken(), subscribeToken()). |
AppSyncEvents::httpHost($endpoint) |
The host[:port] authority the handshake authorizes. |
Share the client config as a prop — App/Http/Middleware/HandleInertiaRequests.php:
public function share(Request $request): array { return [ ...parent::share($request), 'appSync' => AppSyncEvents::clientConfig($request->user()), ]; }
const echo = new Echo(appSyncEchoOptions(props.appSync));
props.appSync is already the exact AppSyncConnectorOptions shape — spread or pass directly. Its connectToken is a static string; if your sessions outlive tokens.connect_ttl, wrap it in a re-fetching function (see the SPA variant below).
Enable the client-config route and protect it with your API middleware:
'routes' => [ 'client_config' => [ 'enabled' => true, 'middleware' => ['auth:sanctum'], ], ],
const config = await fetch('/broadcasting/appsync', { credentials: 'include' }) .then((r) => r.json()); const echo = new Echo(appSyncEchoOptions({ ...config, credentials: 'include', // cookies on the channel-auth POST too connectToken: () => fetch('/broadcasting/appsync', { credentials: 'include' }) .then((r) => r.json()) .then((c) => c.connectToken), // fresh token on every (re)connect }));
Cross-origin apps need Access-Control-Allow-Credentials on both endpoints — configure Laravel’s config/cors.php accordingly.
For web-guarded auth endpoints, send the CSRF token on the channel-auth POST:
appSyncEchoOptions({ // ... auth: { headers: { 'X-CSRF-TOKEN': csrfToken }, }, })
Or use bearerToken for Sanctum token auth instead.
clientConfig().inactivityTimeout is a hint your code consumes — the connector itself doesn’t time out idle tabs. This composable disconnects a hidden tab after inactivityTimeout seconds and reconnects on return:
import Echo from 'laravel-echo'; import { appSyncEchoOptions } from '@hds-solutions/laravel-echo-appsync'; import type { AppSyncConnectorOptions } from '@hds-solutions/laravel-echo-appsync'; import { onBeforeUnmount, onMounted, readonly, ref } from 'vue'; export function useAppSyncEcho(options: AppSyncConnectorOptions, inactivityTimeout = 10) { const echo = new Echo(appSyncEchoOptions(options)); const connected = ref(false); let timer: ReturnType<typeof setTimeout> | undefined; const connect = () => { clearTimeout(timer); echo.connector.connect(); connected.value = true; }; const disconnect = () => { clearTimeout(timer); echo.disconnect(); connected.value = false; }; const onVisibilityChange = () => { if (document.visibilityState === 'visible') connect(); else timer = setTimeout(disconnect, inactivityTimeout * 1000); }; onMounted(() => { document.addEventListener('visibilitychange', onVisibilityChange); connect(); }); onBeforeUnmount(() => { document.removeEventListener('visibilitychange', onVisibilityChange); disconnect(); }); return { echo, connected: readonly(connected), connect, disconnect }; }
For anonymous, read-only channels, add API_KEY to the Event API’s connection and subscribe auth modes and pass the key to the connector — no connect token or auth endpoint round-trip:
new Echo(appSyncEchoOptions({ wsEndpoint: 'wss://<id>.appsync-realtime-api.<region>.amazonaws.com/event/realtime', publicApiKey: 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx', }));
broadcast(new OrderShipped($order))->toOthers() is supported: the sender’s socket id (the X-Socket-ID header Echo attaches to the request that triggered the broadcast) is lifted out of the event data into a socket field on the published event envelope, and the Echo connector drops any event whose envelope socket matches its own socketId().
This is client-side filtering — AppSync has no server-side sender exclusion, so other connectors or raw subscribers still receive the event.
Laravel channel names map to AppSync channel paths /{namespace}/{segment}[/{segment}…] — the mapping is identical in PHP (ChannelPath) and TS (toAppSyncChannel), verified against a shared fixture:
| Laravel channel name | AppSync channel path |
|---|---|
orders |
/public/orders |
orders.1 |
/public/orders/1 |
orders.1.items |
/public/orders/1/items |
orders.1-items |
/public/orders/1-items |
private-orders.1 |
/private/orders/1 |
private-private.abc |
/private/private/abc |
private-orders.1.items |
/private/orders/1/items |
private-orders.550e8400-e29b-41d4-a716-446655440000 |
/private/orders/550e8400-e29b-41d4-a716-446655440000 |
private-solo |
/private/solo |
privateer.x |
/public/privateer/x |
Rules:
- The
private-prefix selects the private namespace (namespaces.private, defaultprivate); everything else maps under the public namespace (namespaces.public, defaultpublic). Prefixes are exact —privateer.xis public. private-encrypted-names are rejected (InvalidArgumentException/InvalidChannelNameError) — payload encryption is not implemented by this package; useprivate-.presence-names are rejected (InvalidArgumentException/InvalidChannelNameError) — presence channels are out of scope.- Each dot-part of the remaining name becomes a path segment (at most 4 — AppSync paths are capped at 5 segments total including the namespace).
-stays literal inside segments, soorders.1.itemsandorders.1-itemsare different channels (subscribe tokens are scoped to the path — keep that in mind when picking names).- Namespace names are configurable (
namespaces.public/namespaces.private) but are the AppSync authorization boundary — they must match the namespaces created on the Event API, and each namespace can carry its own auth mode (e.g.API_KEY+ Lambda forpublic, Lambda authorizer forprivate). - Subscribing or publishing to a missing namespace fails (subscribe_error / 404
BroadcastException). - Each segment is 1–50 chars, alphanumeric at both ends with
[A-Za-z0-9-]inside — underscores are not allowed in AppSync channel paths. Invalid names throwInvalidArgumentException(PHP) /InvalidChannelNameError(JS) instead of hitting the API.
-
Token wire format —
base64url(json(claims)) + '.' + hex(hmac_sha256(payload, secret)). Claims:purpose(connect/subscribe),uid,exp(unix), andchannel(the AppSync path) on subscribe tokens. The secret is shared only between your app and the authorizer — never sent to AWS or clients. -
TTLs —
tokens.connect_ttl(default 12 h) andtokens.subscribe_ttl(1 h).authorizer.cache_ttlis thettlOverridereturned on authorized calls — how long AppSync may cache the decision. -
Publish is never client-authorized —
EVENT_PUBLISHis denied unconditionally; publishing requires IAMappsync:EventPublish. -
Secret hygiene — keep
APPSYNC_CHANNEL_SIGNING_SECRETout of VCS (use SSM/Secrets Manager for the Lambda side). Rotate without downtime:- Generate a new secret —
php artisan appsync-events:secret --showprints 64 hex chars without touching.env(oropenssl rand -hex 32). - Deploy the authorizer first with
APPSYNC_CHANNEL_SIGNING_SECRET=<new>andAPPSYNC_CHANNEL_PREVIOUS_SIGNING_SECRETS=<old>— it now verifies both. - Deploy the Laravel app with the new
APPSYNC_CHANNEL_SIGNING_SECRET— it signs new tokens immediately; clients receive them on their next auth/clientConfigcall. - Once the longest token TTL has elapsed — connect tokens default to 12 h (
tokens.connect_ttl), subscribe tokens to 1 h (tokens.subscribe_ttl) — removeAPPSYNC_CHANNEL_PREVIOUS_SIGNING_SECRETSfrom the authorizer.
Clients holding tokens signed with the old secret simply reconnect and re-authorize with fresh tokens; already-authorized sockets are unaffected.
- Generate a new secret —
-
Least privilege — scope
appsync:EventPublishto the namespaces you use, and the authorizer’sSourceArnto the API. -
Testing — the AWS emulator used by the test suite does not verify SigV4 signatures, does not invoke Lambda authorizers, and does not validate token contents; those paths are covered by unit tests. Do not use the emulator for security testing.
Keep BROADCAST_CONNECTION=reverb (or log) locally and appsync in production — broadcasting is driver-agnostic, so nothing else changes. For AppSync-specific behavior, the repo runs against the AWS emulator: tests/emulator/start.sh, then composer test:emulator / npm --prefix js run test:emulator.
composer test # Pest (unit + feature) composer lint # Pint composer analyse # PHPStan npm --prefix js test # Vitest
Emulator tests, fixture conventions and the PR checklist live in CONTRIBUTING.md; security reports go through SECURITY.md.
- No presence channels —
echo.join()/presenceChannel()throws, and channel names starting withpresence-are rejected (InvalidArgumentException/InvalidChannelNameError); presence metadata has no AppSync Events equivalent. - No client events / whispers — clients cannot publish by design.
- One Echo connector instance per socket — the connector multiplexes channels over a single AppSync WebSocket; concurrent reconnects reuse the latest connect generation only.
- Emulator caveats — see tests/emulator/README.md.
Both packages follow SemVer and release in lockstep (0.x while the API surface stabilizes). MIT — see LICENSE. Built by Hermann D. Schimpf.
Laravel News Links




















