When your PartyKit project is deployed, the server accepts HTTP requests and WebSocket connections from the Internet.
In order to prevent unauthorized requests being routed to your server, you can implement authentication in your onBeforeConnect and onBeforeRequest handlers.
Authenticating WebSocket connections
Every PartyKit server accepts WebSocket connections by default.
To ensure that only authorized users can connect to your server, you should pass a session token to the initial connection request. The most convenient way to do this is to pass the token as a query string parameter:
The query parameter can be an object of key-value pairs, or an (optionally) asynchronous
function that returns one.
You can then verify your user’s identity in a static onBeforeConnect method:
To ensure that only authorized users can make requests to your server, you should send a session token in the request.
The recommended way is to pass it as an Authorization header:
You can then verify your user’s identity in a static onBeforeRequest method:
Other authentication methods
The above examples use Clerk for brevity, but you can use any authentication provider.
If you’re rolling your own JWT authentication, or your identity provider doesn’t supply an SDK that’s compatible with PartyKit’s Cloudflare Workers runtime, you can verify and decode your JWTs with the cloudflare-worker-jwt package.
Alternatively, you can consider these authentication methods:
For client-to-server connections, you can pass any type of session token, and verify it against your session service. For an example with NextAuth.js, see the PartyKit Next.js example app.