SynqDocs
Getting started

Sign users in with @synqauth/js

Sign someone in, finish the callback, read who they are and sign them out with @synqauth/js, in a single-page app or on a server of your own.

At 0.x

@synqauth/js is on npm at 0.x, so a minor release can change its API. The changelog says what each release changed.

@synqauth/js is Synq's client for any JavaScript. It sends the person to your brand's hosted sign-in page, finishes the callback when they come back (the authorization code flow, with PKCE, state, the nonce and the iss check), keeps the session, and signs them out. This page does it twice: in a single-page app in the browser, then on a server of your own. Synq's own tests run every file on this page: the browser's and the server's against a stand-in for a brand's issuer, and the React ones against a stand-in for the client.

Which page to start from:

  • A Next.js app with the App Router: Sign users in to a Next.js app, with @synqauth/nextjs, which keeps every token on the app's server, and @synqauth/react's components.
  • A single-page app with no server of its own, such as a Vite or React app: in the browser, below. @synqauth/react isn't for this app: its hooks and components ask a route mount on your app's server, which @synqauth/nextjs serves, and never call Synq themselves.
  • A server of your own that isn't Next.js: on a server, below.

Before you start

First, sign up, verify your email and make an org. Its first brand signs people in at once, on the free Starter plan. Choose React when onboarding asks what you're building with, and it makes a development single-page app that sends people back to https://localhost:5173/callback, Vite's dev server on https (Developing on your laptop sets it up); Node makes a development web app on https://localhost:3000. Each app's page in the dashboard shows its client ID.

In the browser: a single-page app

1. Register the app

The app is a single-page app of your brand: public, with no secret. Its redirect URI is the page Synq sends people back to, such as https://app.example.com/callback, and the app's root, https://app.example.com/, is where they land after signing out.

In the dashboard, open the brand's Apps and make a New app: a Single-page app, with that redirect URI. Add the app's root under After signing out on the app's page.

Or make it with the management API, with the same $ORG, $BRAND, $SYNQ_API_KEY and $SYNQ_API as the Next.js page:

curl -X POST "$SYNQ_API/v1/orgs/$ORG/brands/$BRAND/apps" \
  -H "Authorization: Bearer $SYNQ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My app",
    "app_type": "spa",
    "first_party": true,
    "redirect_uris": ["https://app.example.com/callback"],
    "post_logout_redirect_uris": ["https://app.example.com/"]
  }'

2. Install and configure

npm install @synqauth/js

The code below is a Vite app's, which reads its settings from .env.local. Neither is a secret: a single-page app's code shows them to anyone.

VariableWhat it is
VITE_SYNQ_ISSUERThe brand's issuer, such as https://acme.auth.synq.build
VITE_SYNQ_CLIENT_IDThe app's client ID

One client for the page:

src/synq.ts
import { browserSessionStorage, createSynqClient } from '@synqauth/js'

// The page's one client. A single-page app has no secret: its issuer and
// client ID are fine in the browser's code.
export const synq = createSynqClient({
  issuer: import.meta.env.VITE_SYNQ_ISSUER,
  clientId: import.meta.env.VITE_SYNQ_CLIENT_ID,
  redirectUri: `${location.origin}/callback`,
  postLogoutRedirectUri: `${location.origin}/`,
  scope: 'openid profile email',
  // The tab keeps the session across reloads: its ID and access tokens, never a refresh token.
  storage: browserSessionStorage(),
})

Without storage, the session is kept in the page's memory, and a reload forgets it. browserSessionStorage() keeps it in the tab, and browserLocalStorage() in every tab of the app. Neither ever holds a refresh token, which any script on the page could read: a refresh token stays in the client's memory alone. A single-page app gets none unless you turn on Give it refresh tokens under the app's Advanced settings (spa_refresh_tokens).

3. Sign in, finish the callback, and read who's there

The page has a line that says who is signed in, and a button to sign in or out:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My app</title>
    <script type="module" src="/src/main.ts"></script>
  </head>
  <body>
    <p id="who">Loading…</p>
    <button id="sign-in" hidden>Sign in</button>
    <button id="sign-out" hidden>Sign out</button>
  </body>
</html>

Every page load starts by asking who is signed in. On /callback, handleCallback finishes the sign-in Synq sent the browser back with: it checks the state, the issuer, the PKCE verifier and the ID token, keeps the session, and answers it. Anywhere else, restoreSession() answers the session this tab kept. Once its access token runs out, with no refresh token to get another, it sends the browser to Synq to sign in again without showing anything (prompt=none), which comes back to /callback signed in while the person is still signed in at the brand. If they aren't, it comes back with login_required, and they're signed out here.

src/session.ts
import { type Session, isSynqError } from '@synqauth/js'

import { synq } from './synq.ts'

// What a sign-in that shows nothing (restoreSession's) comes back with when
// the person has to see Synq's page first: they're signed out here.
const ASK_FIRST = new Set([
  'login_required',
  'consent_required',
  'interaction_required',
  'account_selection_required',
])

/**
 * Who is signed in as the page loads. Back from Synq at /callback, it
 * finishes the sign-in. Anywhere else, it picks up the session this tab
 * kept, and once its access token runs out, signs in again without showing
 * anything.
 */
export async function loadSession(): Promise<Session | null> {
  if (location.pathname !== '/callback') return synq.restoreSession()
  try {
    return await synq.handleCallback(location.href)
  } catch (error) {
    if (isSynqError(error) && ASK_FIRST.has(error.code)) return null
    throw error
  } finally {
    // The code is spent: take it out of the address bar and the history.
    history.replaceState(null, '', '/')
  }
}

synq.signIn() sends the browser to the brand's hosted page. session.claims is who signed in, from their ID token: sub always, email with the email scope, and name with profile where they have one (tokens and claims).

src/main.ts
import { isSynqError } from '@synqauth/js'

import { loadSession } from './session.ts'
import { synq } from './synq.ts'

const who = document.querySelector<HTMLParagraphElement>('#who')!
const signInButton = document.querySelector<HTMLButtonElement>('#sign-in')!
const signOutButton = document.querySelector<HTMLButtonElement>('#sign-out')!

signInButton.addEventListener('click', () => void synq.signIn())
signOutButton.addEventListener('click', () => void signOut())

async function signOut() {
  // Ends the session here, then Synq's page asks whether to sign out of the brand too.
  const url = await synq.signOut()
  location.assign(url?.href ?? '/')
}

try {
  const claims = (await loadSession())?.claims
  who.textContent = claims
    ? `Signed in as ${claims.name ?? claims.email ?? claims.sub}`
    : 'Signed out'
  signInButton.hidden = Boolean(claims)
  signOutButton.hidden = !claims
} catch (error) {
  // Branch on the code, never the words: access_denied when they said no, say.
  who.textContent = `Sign-in failed: ${isSynqError(error) ? error.code : String(error)}`
  signInButton.hidden = false
}

signIn() takes the same options as authorizationUrl(): method opens the hosted page at one way in (passkey, email, wallet, google…), loginHint fills in their address, and prompt: 'create' opens it on sign-up. A sign-in's transaction is kept in localStorage, so one that finishes in another tab, as a magic link from an email does, still finishes there. A callback finishes once: the same address again is unknown_state.

Your host must serve index.html at /callback too. Vite's dev server does; a static host does with its fallback for single-page apps.

4. Sign out

synq.signOut() ends the session in the page and revokes its refresh token if it had one, then answers your brand's sign-out URL. A public app has no secret to end the brand's session with from the page, so the brand's page asks first, then sends the person back to the app's root. See signing out.

5. Call your API

Register your API with the brand (Register an API), and give the client its identifier as resource, with its scopes in scope. Then send await synq.getAccessToken() as Authorization: Bearer, and check it on your API with createAccessTokenVerifier from @synqauth/js/server, as the Next.js page shows. Without a refresh token, an access token that ran out can't be renewed: getAccessToken() throws no_refresh_token, and restoreSession() signs the person in again.

In React

Keep src/synq.ts and src/session.ts from above, and ask who is signed in before React renders. React may run an effect twice, and a callback finishes only once.

src/main.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'

import { App } from './App.tsx'
import { loadSession } from './session.ts'

// Who is signed in, before the first render: the callback is finished once,
// here, and never in an effect React may run twice.
const session = await loadSession().catch((error: unknown) => {
  // access_denied when they said no, say: they're signed out, and can try again.
  console.error('Sign-in failed', error)
  return null
})

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App session={session} />
  </StrictMode>,
)

synq.subscribe hears every sign-in, refresh and sign-out the client makes, and answers the function that stops it, which is the effect's cleanup:

src/App.tsx
import type { Session } from '@synqauth/js'
import { useEffect, useState } from 'react'

import { synq } from './synq.ts'

export function App({ session: first }: { session: Session | null }) {
  const [session, setSession] = useState(first)
  // Every sign-in, refresh and sign-out the client makes, from anywhere on the page.
  useEffect(() => synq.subscribe((event) => setSession(event.session)), [])

  if (!session) return <button onClick={() => void synq.signIn()}>Sign in</button>
  const claims = session.claims
  return (
    <>
      <p>Signed in as {claims?.name ?? claims?.email ?? claims?.sub}</p>
      <button onClick={() => void signOut()}>Sign out</button>
    </>
  )
}

async function signOut() {
  // Ends the session here, then Synq's page asks whether to sign out of the brand too.
  const url = await synq.signOut()
  location.assign(url?.href ?? '/')
}

For the person's profile, wallets and linked accounts, createAccountClient from @synqauth/js calls the brand's account API, from the brand's own apps (first_party), with a token for it: a client whose resource is accountApiUrl(issuer). The package's README shows it.

On a server

On a server of your own, the app is a web app: it keeps a secret, and the browser never holds a Synq token. The browser holds a cookie with a random ID, and the server keeps that person's session under it. With Next.js, @synqauth/nextjs does all of this for you, with sealed cookies and a store for more than one process: start from its page instead.

1. Register the app

A Web app of your brand, with https://app.example.com/callback as its redirect URI and https://app.example.com/ under After signing out, as above, with "app_type": "web" through the management API. Its page shows its secret once, when it's made.

2. Configure

Set four environment variables, on the server only:

VariableWhat it is
APP_URLWhere the app is served, such as https://app.example.com
SYNQ_ISSUERThe brand's issuer, such as https://acme.auth.synq.build
SYNQ_CLIENT_IDThe app's client ID
SYNQ_CLIENT_SECRETThe app's secret

3. The routes

handle takes a web Request and answers a Response: GET /sign-in sends the browser to Synq, GET /callback finishes the sign-in, GET / says who is signed in, and a form posting to /sign-out signs them out.

server.ts
import { type SynqClient, createSynqClient, isSynqError } from '@synqauth/js'

// Where the app is served, such as https://app.example.com: Synq sends
// people back to its /callback, and to / once they've signed out.
const APP_URL = process.env.APP_URL!

// One client per browser, under the random ID in that browser's cookie. Each
// keeps its person's sign-in and session, refresh token included, in this
// process's memory. An app on more than one process keeps them in a store
// the processes share, with a lock (`SynqStorage`), instead.
const clients = new Map<string, SynqClient>()

const COOKIE = 'app_session'

function newClient(): SynqClient {
  return createSynqClient({
    issuer: process.env.SYNQ_ISSUER!,
    clientId: process.env.SYNQ_CLIENT_ID!,
    clientSecret: process.env.SYNQ_CLIENT_SECRET!,
    redirectUri: `${APP_URL}/callback`,
    postLogoutRedirectUri: `${APP_URL}/`,
    scope: 'openid profile email',
  })
}

/** This browser's ID, from its cookie. */
function browserId(request: Request): string | undefined {
  const cookies = request.headers.get('cookie') ?? ''
  return new RegExp(`(?:^|;\\s*)${COOKIE}=([\\w-]+)`).exec(cookies)?.[1]
}

function clientOf(request: Request): SynqClient | undefined {
  const id = browserId(request)
  return id ? clients.get(id) : undefined
}

function redirect(location: string, status: number, cookie?: string): Response {
  const headers = new Headers({ location })
  if (cookie) {
    headers.set('set-cookie', `${COOKIE}=${cookie}; Path=/; HttpOnly; Secure; SameSite=Lax`)
  }
  return new Response(null, { status, headers })
}

function page(body: string, status = 200): Response {
  return new Response(`<!doctype html><meta charset="utf-8"><title>My app</title>${body}`, {
    status,
    headers: { 'content-type': 'text/html; charset=utf-8' },
  })
}

/** Text safe to put in HTML: a person's name is whatever they typed. */
function escapeHtml(text: string): string {
  return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
}

export async function handle(request: Request): Promise<Response> {
  const { pathname } = new URL(request.url)

  if (request.method === 'GET' && pathname === '/sign-in') {
    // A new ID for every sign-in, so nobody can hand this browser theirs.
    const old = browserId(request)
    if (old) clients.delete(old)
    const id = crypto.randomUUID()
    const synq = newClient()
    clients.set(id, synq)
    return redirect((await synq.authorizationUrl()).href, 302, id)
  }

  if (request.method === 'GET' && pathname === '/callback') {
    const synq = clientOf(request)
    if (!synq) return page('<p>This sign-in was started in another browser.</p>', 400)
    try {
      await synq.handleCallback(request.url)
    } catch (error) {
      // access_denied when they said no; unknown_state when this callback was used already.
      const code = isSynqError(error) ? error.code : 'unknown'
      return page(`<p>Sign-in failed: ${escapeHtml(code)}</p><a href="/sign-in">Try again</a>`, 400)
    }
    return redirect('/', 302)
  }

  if (request.method === 'POST' && pathname === '/sign-out') {
    // Only a form on the app's own pages signs anyone out.
    if (request.headers.get('origin') !== new URL(APP_URL).origin) return page('', 403)
    const id = browserId(request)
    const synq = clientOf(request)
    // With the secret, it ends the brand's session from here first, so Synq's page asks nothing.
    const url = synq ? await synq.signOut() : null
    if (id) clients.delete(id)
    return redirect(url?.href ?? '/', 303)
  }

  if (request.method === 'GET' && pathname === '/') {
    const claims = (await clientOf(request)?.getSession())?.claims
    return claims
      ? page(
          `<p>Signed in as ${escapeHtml(claims.name ?? claims.email ?? claims.sub)}</p>` +
            '<form method="post" action="/sign-out"><button>Sign out</button></form>',
        )
      : page('<p>Signed out</p><a href="/sign-in">Sign in</a>')
  }

  return page('<p>Not found</p>', 404)
}

Serve it with anything that hands you a web Request: Deno.serve(handle), Bun.serve({ fetch: handle }), or a Hono app's app.all('*', (c) => handle(c.req.raw)).

A sign-in's transaction (its state, PKCE verifier and nonce) stays with the client of the browser that started it, so a callback from any other browser finds nothing to finish. On a web app, signOut() ends the brand's session from the server before it answers the brand's sign-out URL, so that page asks nothing and comes straight back to the app's root.

A web app that is one of the brand's own (first_party), or asks for offline_access, gets a refresh token, so await synq.getAccessToken() on the server is a current token for your API (the client's resource), refreshed when it must be. Your API checks it as the Next.js page shows.

4. More than one process

The Map above lives in one process, and it keeps every browser's client until that browser signs in again or out. Synq rotates refresh tokens, and ends a grant whose old one comes back, so an app on more than one process (serverless hosts, replicas) keeps each browser's session in a store they all share. Give createSynqClient a storage and a transactionStorage for that browser: a SynqStorage over your store, with get, set and remove, a lock that only one process at a time holds per name, and holdsRefreshTokens: true, since it lives on your server. The client refreshes under that lock, and reads the session again inside it.

Developing on your laptop

A single-page app's and a web app's redirect URIs are https, on localhost too. Register https://localhost:5173/callback and https://localhost:5173/ on an app of its own for development, never on your production app, and serve Vite at exactly that address: https, the redirect URI's host and its port.

With mkcert, your browser trusts the certificate. Run mkcert -install once, then mkcert -key-file localhost-key.pem -cert-file localhost.pem localhost 127.0.0.1 ::1 in the app's folder, and keep both files out of git:

// vite.config.ts
import { readFileSync } from 'node:fs'

import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    // Every address, so https://localhost:5173 answers whether localhost is
    // 127.0.0.1 or ::1 to your browser. Without strictPort, a busy 5173
    // moves Vite to another port, which isn't the redirect URI's.
    host: true,
    port: 5173,
    strictPort: true,
    https: { key: readFileSync('localhost-key.pem'), cert: readFileSync('localhost.pem') },
  },
})

Or let @vitejs/plugin-basic-ssl make one (npm install -D @vitejs/plugin-basic-ssl). Its certificate is self-signed, so your browser warns: open https://localhost:5173/ and accept the warning before you sign in.

// vite.config.ts
import basicSsl from '@vitejs/plugin-basic-ssl'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [basicSsl()],
  // As above: every address, at the redirect URI's port.
  server: { host: true, port: 5173, strictPort: true },
})

host: true matters: with host: 'localhost', Vite listens only on the first address localhost resolves to, which can be ::1 alone, and a browser that reaches 127.0.0.1 gets a closed connection. It also lets other devices on your network reach the dev server, so use it on a network you trust. Either way, open the app at https://localhost:5173/, the redirect URI's host: to Synq, https://localhost:5173/callback and https://127.0.0.1:5173/callback are different redirect URIs.

A server of your own takes the mkcert certificate, on https://localhost:3000.

What's next

On this page