Skip to content

Every App SDK

The Every App SDK (@every-app/sdk) handles all the communication between your app and the Gateway. It’s responsible for:

  1. Session token management - Requesting and refreshing session tokens from the Gateway
  2. Route synchronization - Keeping your app’s URL in sync with the Gateway
  3. API Request authentication - Simplifying adding tokens to your API requests and verifying them on the backend
Terminal window
npm install @every-app/sdk

How Session Tokens Work

When your app loads inside the Gateway’s iframe using the SDK:

  1. Your app client requests a session token from the Gateway via postMessage
  2. The Gateway returns a signed JWT scoped to your app ID
  3. Your app client includes the token in all API requests to your backend
  4. Your backend verifies the token using the Gateway’s public key (JWKS)
  5. 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

PropTypeRequiredDescription
appIdstringYesMust match the App ID configured in the Gateway

What it does

  • Creates a SessionManager instance
  • 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

PropertyTypeDescription
userIdstringThe user’s unique ID (from JWT sub claim)
emailstringThe 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

  1. Gets the global SessionManager instance (set by EmbeddedAppProvider)
  2. Calls getToken() to get a valid token
  3. 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:

  1. Does nothing at module load time
  2. Creates the actual resource on first property access
  3. 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

  1. Extracts the Authorization: Bearer <token> header from the request
  2. Fetches the Gateway’s JWKS (JSON Web Key Set) to get the public key
  3. Verifies the JWT signature, issuer, and audience
  4. Returns the decoded payload if valid, null if invalid