Authentication
How to handle authentication in Motia for HTTP endpoints and real-time streams
Motia provides two authentication patterns: stream authentication configured via the iii engine's config.yaml, and HTTP endpoint authentication handled within your Step handlers.
Stream Authentication
Stream authentication operates at two levels: connection-level authentication when the WebSocket connects, and subscription-level authorization when a client joins a specific stream.
Connection-Level Authentication
Configure the auth_function on the Stream module in config.yaml. The value uses <module>.<function> format — stream.authenticate means the iii engine looks for a registered Step whose exported handler is named authenticate under the stream module namespace. This function runs on every new WebSocket connection before the upgrade completes.
Create a Step file that exports the handler referenced by auth_function. The handler receives a stream connection object (not an Express-like req) with the WebSocket handshake's headers, path, query_params, and addr. It should return a context object that gets attached to the connection and passed to all subsequent stream join/leave trigger handlers:
If the function throws or returns no result, the connection proceeds without an auth context. The returned context is attached to the connection and passed to stream join/leave trigger handlers.
Subscription-Level Authorization
When a client joins a specific stream, a stream trigger handler can reject the subscription by returning { unauthorized: true }. This allows per-stream, per-group access control using the auth context from the connection:
HTTP Endpoint Authentication
For HTTP endpoints, handle authentication directly in your Step handler using shared utility functions:
Then use it in your Step handlers:
Error Handling
Wrap your handler logic in try/catch blocks for error handling. This replaces the previous middleware-based coreMiddleware pattern:
Reusable Auth Wrappers
For a cleaner pattern across many Steps, create a wrapper function: