Every App SDK
The Every App SDK (@every-app/sdk) handles all the communication between your app and the Gateway. It’s responsible for:
- Session token management - Requesting and refreshing session tokens from the Gateway
- Route synchronization - Keeping your app’s URL in sync with the Gateway
- API Request authentication - Simplifying adding tokens to your API requests and verifying them on the backend
npm install @every-app/sdkHow Session Tokens Work
When your app loads inside the Gateway’s iframe using the SDK:
- Your app client requests a session token from the Gateway via
postMessage - The Gateway returns a signed JWT scoped to your app ID
- Your app client includes the token in all API requests to your backend
- Your backend verifies the token using the Gateway’s public key (JWKS)
- Before the token expires, the SDK automatically requests a new one
┌──────────────┐ ┌──────────────┐ ┌──────────────┐│ Gateway │ │ App Client │ │ App Backend ││ (parent) │ │ (iframe) │ │ (Cloudflare) │└──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ │ 1. postMessage │ │ │ "request token" │ │ │◄───────────────────│ │ │ │ │ │ 2. postMessage │ │ │ JWT session token │ │ │───────────────────►│ │ │ │ │ │ │ 3. API request │ │ │ Authorization: │ │ │ Bearer <token> │ │ │───────────────────►│ │ │ │ │ │ │ 4. Verify JWT │ │ │ via Gateway │ ◄ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │ JWKS │ (fetch public key) │ │ │ │Client SDK
The client SDK is imported from @every-app/sdk/tanstack and provides React components and hooks for authentication.
EmbeddedAppProvider
The main React provider that wraps your app. It initializes the session manager and handles route synchronization.
import { EmbeddedAppProvider } from "@every-app/sdk/tanstack";
function App() { return ( <EmbeddedAppProvider appId="your-app-id"> <YourApp /> </EmbeddedAppProvider> );}Props
| Prop | Type | Required | Description |
|---|---|---|---|
appId | string | Yes | Must match the App ID configured in the Gateway |
What it does
- Creates a
SessionManagerinstance - Requests an initial session token from the Gateway
- Sets up route synchronization (your app’s routes sync with the Gateway’s URL bar)
- Makes the session manager globally available for the middleware
SessionManager
The class that handles all token management. You usually don’t interact with this directly - the provider and middleware handle it for you.
interface SessionManagerConfig { appId: string;}Key Methods
getToken(): Promise<string> - Returns a valid session token. If the current token is expired or expiring soon (within 10 seconds), it automatically requests a new one.
getTokenState() - Returns the current token state:
type TokenState = { status: "NO_TOKEN" | "VALID" | "EXPIRED" | "REFRESHING"; token: string | null;};getAppId(): string - Returns the configured app ID.
getParentOrigin(): string - Returns the Gateway URL (from VITE_GATEWAY_URL env var).
getUser(): { userId: string; email: string } | null - Extracts user information from the current JWT token. Returns null if no valid token is available.
const user = sessionManager.getUser();if (user) { console.log(`Logged in as ${user.email}`);}useCurrentUser
A React hook that returns the current authenticated user’s information.
import { useCurrentUser } from "@every-app/sdk/tanstack";
function UserProfile() { const user = useCurrentUser();
if (!user) { return <div>Not authenticated</div>; }
return ( <div> <p>User ID: {user.userId}</p> <p>Email: {user.email}</p> </div> );}Return Value
Returns { userId: string; email: string } | null
| Property | Type | Description |
|---|---|---|
userId | string | The user’s unique ID (from JWT sub claim) |
email | string | The user’s email address |
Returns null if the user is not authenticated or the session token is not yet available.
useSessionTokenClientMiddleware
A TanStack Start middleware that automatically adds the session token to all server function requests.
import { useSessionTokenClientMiddleware } from "@every-app/sdk/tanstack";
export const myServerFunction = createServerFn({ method: "GET" }) .middleware([useSessionTokenClientMiddleware]) .handler(async () => { // Your handler code });How it works
- Gets the global
SessionManagerinstance (set byEmbeddedAppProvider) - Calls
getToken()to get a valid token - Adds an
Authorization: Bearer <token>header to the request
lazyInitForWorkers
A utility that wraps resource creation to avoid Cloudflare Workers’ global scope restrictions.
import { lazyInitForWorkers } from "@every-app/sdk/cloudflare";import { createCollection, queryCollectionOptions } from "@tanstack/db";
export const todosCollection = lazyInitForWorkers(() => createCollection( queryCollectionOptions({ queryKey: ["todos"], queryFn: async () => fetchTodos(), // ... other options }), ),);Why it’s needed
Cloudflare Workers don’t allow certain async operations (like creating TanStack DB collections) to run in the global scope at module load time. This utility defers initialization until the resource is first accessed.
How it works
Returns a Proxy that:
- Does nothing at module load time
- Creates the actual resource on first property access
- Caches the instance for subsequent accesses (singleton pattern)
Server SDK
The server SDK is imported from @every-app/sdk/tanstack/server and provides authentication utilities.
authenticateRequest
Verifies the JWT session token from incoming requests. This is the main function you’ll use to authenticate users in your server functions.
import { authenticateRequest, getAuthConfig,} from "@every-app/sdk/tanstack/server";
export const myServerFunction = createServerFn({ method: "GET" }) .middleware([useSessionTokenClientMiddleware]) .handler(async () => { const session = await authenticateRequest(getAuthConfig());
if (!session) { throw new Error("Unauthorized"); }
const userId = session.sub; // ... your logic });Parameters
interface AuthConfig { issuer: string; // The Gateway URL (validates token issuer) audience: string; // Your app ID (validates token audience)}Return Value
Returns the decoded JWT payload or null if authentication fails:
interface SessionTokenPayload { sub: string; // User ID iss: string; // Issuer (Gateway URL) aud: string; // Audience (your app ID - use this for app identification) exp: number; // Expiration timestamp iat: number; // Issued at timestamp email?: string; // User email (for user provisioning)}How it works
- Extracts the
Authorization: Bearer <token>header from the request - Fetches the Gateway’s JWKS (JSON Web Key Set) to get the public key
- Verifies the JWT signature, issuer, and audience
- Returns the decoded payload if valid,
nullif invalid