newOS for Developers

Skills/Account/session-token

Session Token

Exchange Firebase ID token for Newgraph JWT

beginner1 endpointcore

When to Use

  • • After Firebase phone authentication completes
  • • After OAuth provider login (Twitter, Instagram)
  • • When refreshing an expired Newgraph JWT
  • • Implementing "remember me" functionality

Prerequisites

  • • Valid Firebase ID token (from phone auth or OAuth)
  • newgraphClient initialized

API Endpoint

EndpointMethodAuthDescription
/auth/generateSessionTokenPOSTFirebase TokenExchange for Newgraph JWT

Request & Response Types

// Request Body
interface GenerateSessionTokenRequest {
  referer: string;      // "newgra.ph"
  appOwner: string;     // "newcoinos"
  redirectUrl: string;  // App redirect URL
  scopes: string[];     // Optional permission scopes
  r?: string;           // Optional invitor ID
}

// Response
interface SessionTokenResponse {
  jwt: string;  // Newgraph JWT (valid 7 days)
}

Step-by-Step Implementation

1

Set Firebase Token on Client

// After Firebase auth completes
const firebaseUser = await signInWithPhoneNumber(auth, phone, verifier);
const firebaseToken = await firebaseUser.user.getIdToken();

// Set on Newgraph client temporarily
newgraphClient.updateToken(firebaseToken);
2

Exchange for Session Token

import { newgraphClient, stage } from "newgraph-signals";
import { ContentType } from "@newstackdev/iosdk-newgraph-client-js";

const sessionRes = await newgraphClient.api.request({
  baseUrl: `https://api${stage === "eu-prod" ? "" : `-${stage.split(/-/)[1]}`}.newgra.ph/v1/auth`,
  path: "/generateSessionToken",
  method: "POST",
  body: {
    referer: "newgra.ph",
    appOwner: "newcoinos",
    redirectUrl: window.location.origin + "/start",
    scopes: [],
  },
  secure: true,
  type: ContentType.Json,
  format: "json",
});

const newgraphJwt = sessionRes.data.jwt;
3

Store & Apply Token

// Store in localStorage for persistence
localStorage.setItem("newsafe-auth-token", newgraphJwt);

// Apply with newsafe prefix (CRITICAL!)
newgraphClient.updateToken(`newsafe ${newgraphJwt}`);

// Now you can make authenticated API calls
const currentUser = await newgraphClient.api.user.currentList();
console.log("Logged in as:", currentUser.data.username);
⚠️ Important: The token format must be newsafe {jwt} with a space. Missing this prefix will cause 401 errors.

Complete Example

// auth.ts - Full session token flow
import { newgraphClient, stage } from "newgraph-signals";
import { ContentType } from "@newstackdev/iosdk-newgraph-client-js";

const JWT_LOCALSTORAGE = "newsafe-auth-token";

export const signIn = async (firebaseToken: string, opts?: { invitorId: string }) => {
  // Step 1: Set Firebase token
  newgraphClient.updateToken(firebaseToken);

  // Step 2: Exchange for session token
  const sessionRes = await newgraphClient.api.request({
    baseUrl: `https://api${stage === "eu-prod" ? "" : `-${stage.split(/-/)[1]}`}.newgra.ph/v1/auth`,
    path: "/generateSessionToken",
    method: "POST",
    body: {
      referer: "newgra.ph",
      appOwner: "newcoinos",
      redirectUrl: "https://os.newcoin.org/start",
      scopes: [],
      r: opts?.invitorId,
    },
    secure: true,
    type: ContentType.Json,
    format: "json",
  });

  const jwt = sessionRes.data.jwt;

  // Step 3: Store and apply
  localStorage.setItem(JWT_LOCALSTORAGE, jwt);
  newgraphClient.updateToken(`newsafe ${jwt}`);

  // Step 4: Load current user
  const currentUser = await newgraphClient.api.user.currentList();
  
  return { jwt, user: currentUser.data };
};

Edge Cases

Token Expiry (7 days)

The JWT expires after 7 days. Implement refresh logic before expiry using the same/generateSessionToken endpoint.

URL Token Extraction

Tokens can arrive via URL params: ?newsafe_jwt=... or?token=.... Check these on app load.

401 Unauthorized

If you get 401 errors, check: (1) token has newsafe prefix, (2) token hasn't expired, (3) Firebase token was valid during exchange.

🧪 Quick Test

Sign in to Test

Use the sidebar to sign in with your phone number