Skip to main content

What is the BloxChat API?

BloxChat uses tRPC to provide a type-safe, end-to-end API for real-time chat communication. Built on top of tRPC’s modern RPC framework, the API offers both HTTP and WebSocket support for queries, mutations, and real-time subscriptions.
tRPC eliminates the need for traditional REST endpoints by providing direct, type-safe function calls between client and server.

API Structure

The BloxChat API is organized into two main routers:

Auth Router

Handles user authentication, verification flows, and JWT token management

Chat Router

Manages chat messages, subscriptions, and rate limiting

Router Definition

The API structure is defined in packages/api/src/root.ts:
packages/api/src/root.ts
import { authRouter } from "./routers/auth";
import { chatRouter } from "./routers/chat";
import { t } from "./trpc";

export const appRouter = t.router({
  chat: chatRouter,
  auth: authRouter,
});

export type AppRouter = typeof appRouter;

Connection Methods

BloxChat supports dual-protocol communication for maximum flexibility:

HTTP Adapter

Used for queries and mutations:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '@bloxchat/api';

const client = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url: 'http://localhost:3000',
      headers: () => ({
        authorization: `Bearer ${getToken()}`,
      }),
    }),
  ],
});

WebSocket Adapter

Required for real-time subscriptions:
import { createTRPCProxyClient, wsLink } from '@trpc/client';
import type { AppRouter } from '@bloxchat/api';

const client = createTRPCProxyClient<AppRouter>({
  links: [
    wsLink({
      client: new WebSocket('ws://localhost:3000'),
    }),
  ],
});

// Subscribe to chat messages
const subscription = client.chat.subscribe.subscribe(
  { channel: 'global' },
  {
    onData: (message) => {
      console.log('New message:', message);
    },
  }
);

Base URL

The default server configuration runs on:
HTTP: http://localhost:3000
WebSocket: ws://localhost:3000
In production, replace localhost:3000 with your deployed API endpoint.

WebSocket Subscriptions

BloxChat leverages tRPC’s subscription capabilities for real-time features:
  • Chat messages: Real-time message delivery via chat.subscribe
  • Automatic reconnection: Server broadcasts reconnect notifications on shutdown
  • Channel-based: Subscribe to specific channels for filtered message streams
Example Subscription
for await (const message of client.chat.subscribe.subscribe({ channel: 'global' })) {
  console.log(message.author.name, ':', message.content);
}

Rate Limiting

BloxChat implements comprehensive rate limiting at multiple levels:
  • Refresh tokens: 4 requests per hour per user
  • Game verification: 20 requests per minute per user
  • Check verification: 60 requests per minute per session
Rate limits are configurable per channel via getChatLimitsForChannel():
  • Message length limits
  • Message rate limits (requests per time window)
  • Configurable per channel for flexibility
Rate limit errors return HTTP 429 with a retryAfterMs field indicating when to retry.

Procedure Types

BloxChat defines three types of procedures:
Procedure TypeAuthenticationUse CaseExample
publicProcedureNonePublic endpointsauth.beginVerification
protectedProcedureJWT requiredAuthenticated actionschat.publish
gameVerificationProcedureVerification secretGame server callbacksauth.completeVerification
See the Authentication guide for details on JWT tokens and protected procedures.

Error Handling

tRPC uses standardized error codes. Common BloxChat errors:
// UNAUTHORIZED - Missing or invalid JWT
throw new TRPCError({ code: 'UNAUTHORIZED' });

// BAD_REQUEST - Invalid input or expired session
throw new TRPCError({ 
  code: 'BAD_REQUEST',
  message: 'Verification code expired' 
});

// TOO_MANY_REQUESTS - Rate limit exceeded
throw new TRPCError({ 
  code: 'TOO_MANY_REQUESTS',
  message: 'Rate limit hit. Try again in 30s.' 
});

Next Steps

Authentication

Learn how JWT authentication works in BloxChat

Begin Verification

Start the authentication flow

Publish Messages

Send messages to chat channels

tRPC Documentation

Deep dive into tRPC concepts

Build docs developers (and LLMs) love