Skip to Content
Signet

Frontend client

Call Signet from a browser app with a typed TypeScript client.

The @shakibdshy/signet-auth-client package is generated from Signet's OpenAPI contract, so the methods and error codes match the server. You need Node.js 20+. This page covers the framework-neutral client; for React session state, see React session hooks.

Version alignment

@shakibdshy/signet-auth-client and the optional @shakibdshy/signet-auth-react hooks are released together at 1.0.0-rc.1. The React package depends on the client at that same version.

Install

npm install @shakibdshy/signet-auth-client

Both packages are published to npm. Use the local-checkout install only to test unreleased changes.

Create the client

import { createSignetClient, SignetApiError } from '@shakibdshy/signet-auth-client';

export const auth = createSignetClient({
  // Origin + your backend's Config.PathPrefix. If the Go server mounts
  // auth.Handler() at /auth, baseURL MUST include /auth.
  baseURL: 'https://api.example.com/auth',
});

Most common mistake

Using only https://api.example.com as baseURL when the backend mounts Signet at /auth. The generated client calls /signup, so without the prefix every request goes to https://api.example.com/signup and returns 404.

Cookies are included automatically. The client fetches a CSRF token from GET /csrf-token, caches it, and sends X-CSRF-Token on state-changing calls. You do not manage CSRF yourself.

A complete login form

import { useState } from 'react';
import { auth, SignetApiError } from './signet-auth-client';

export function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [user, setUser] = useState<{ email: string } | null>(null);
  const [challenge, setChallenge] = useState('');
  const [code, setCode] = useState('');

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    setError('');
    try {
      const result = await auth.signIn({ email, password });
      if (result.two_factor_challenge) {
        setChallenge(result.two_factor_challenge);
        return;
      }
      setUser(result.user);
    } catch (err) {
      setError(err instanceof SignetApiError ? 'Invalid email or password.' : 'Something went wrong.');
    }
  }

  async function verifySecondFactor(event: React.FormEvent) {
    event.preventDefault();
    setError('');
    try {
      const result = await auth.verifyTwoFactor({ challenge, code });
      setUser(result.user);
    } catch (err) {
      setError(err instanceof SignetApiError ? 'Invalid or expired code.' : 'Something went wrong.');
    }
  }

  async function logout() {
    await auth.signOut({});
    setUser(null);
  }

  if (user) {
    return <div>Signed in as {user.email} <button onClick={logout}>Sign out</button></div>;
  }
  if (challenge) {
    return (
      <form onSubmit={verifySecondFactor}>
        <input value={code} onChange={e => setCode(e.target.value)} placeholder="Authenticator code" />
        <button type="submit">Verify</button>
        {error && <p role="alert">{error}</p>}
      </form>
    );
  }
  return (
    <form onSubmit={submit}>
      <input value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" />
      <input type="password" value={password} onChange={e => setPassword(e.target.value)} />
      <button type="submit">Sign in</button>
      {error && <p role="alert">{error}</p>}
    </form>
  );
}

signUp works the same way. To render the signed-in User on page load, call GET /me or expose the User from your own server-rendered route. The plain client keeps no reactive session state; the optional React package adds one.

Passwordless sign-in

These endpoints are anonymous and CSRF-exempt.

await auth.sendMagicLink({
  email: 'ada@example.com',
  callback_url: 'https://app.example.com/welcome', // must be allowlisted on the server
});

// If your app owns the link route, exchange the token from the URL:
const sent = await auth.verifyMagicLink({
  token: new URL(location.href).searchParams.get('token')!,
  callback_url: 'https://app.example.com/welcome',
});

await auth.sendOtp({ email: 'grace@example.com' });
const result = await auth.verifyOtp({ email: 'grace@example.com', code: '123456' });

A normal clicked link navigates to GET /verify-magic-link, which sets cookies and redirects; call verifyMagicLink() only when your frontend handles that route itself.

Last sign-in method

When the backend enables Last sign-in method, the client can read the signed cookie through the typed endpoint. Create the client with the backend PathPrefix included in baseURL:

import { createSignetClient } from '@shakibdshy/signet-auth-client';

const auth = createSignetClient({ baseURL: 'https://api.example.com/auth' });
const { method } = await auth.lastSignInMethod();
// "password" | "magic_link" | "otp" | "passkey" | "oauth" | "sso" | "saml" | ""

Common mistake

Using only https://api.example.com as baseURL makes the generated client call /last-sign-in-method instead of /auth/last-sign-in-method. The backend then returns 404.

The value is "" when the feature is disabled, the cookie is absent, or its signature is invalid. This is a read of a non-essential cookie; it does not establish a Session.

Second factor management

const enabled = await auth.enableTwoFactor({ password });
await auth.verifyTwoFactor({ challenge: enabled.challenge, code: '123456' });
const fresh = await auth.regenerateBackupCodes({ password });
await auth.disableTwoFactor({ password });

Enable, regenerate and disable are authenticated. Enrollment stays pending until the first successful TOTP code; only then will signIn return a challenge.

Account controls

The client also covers verified email change, linked provider Accounts and account deletion. Every call needs a Session, except the proof steps that complete a flow.

// Change the email: a proof is sent to the new address.
await auth.changeEmail({ new_email: 'ada@new.example.com', current_password: 'correct horse' });
// Opened on the new address's confirmation page, commit the change with the link's token:
await auth.verifyChangeEmail({ token });

// List linked provider Accounts (OAuth, SSO) and unlink one. Unlinking the last
// credential Account is rejected with last_account.
const { accounts } = await auth.listAccounts();
await auth.unlinkAccount({ account_id: accounts[0].id });

// Delete the account: a confirmation proof is emailed first, then confirm it.
await auth.requestAccountDeletion();
await auth.confirmAccountDeletion({ token });

Handling errors

try {
  await auth.verifyOtp({ email, code });
} catch (err) {
  if (err instanceof SignetApiError) {
    switch (err.code) {
      case 'invalid_code':
      case 'invalid_link':
        return showMessage('That code or link is no longer valid. Request a new one.');
      case 'code_already_used':
      case 'link_already_used':
        return showMessage('You already used that proof. Request a new one.');
      case 'two_factor_required':
        return showMessage('Enter your authenticator code to continue.');
      case 'invalid_request':
        return showMessage('That sign-in link is not valid for this app.');
      case 'rate_limited':
        return showMessage('Too many attempts. Try again shortly.');
    }
  }
  throw err;
}

All codes are listed in Errors; request and response shapes come from the generated OpenAPI contract. Server setup lives in Passwordless sign-in, Second factor and Username and accounts.

OAuth providers

Google, GitHub and generic OIDC providers all use the same OAuth endpoints. The provider ID is whatever the backend registered in Config.OAuth.Providers.

const { url } = await auth.oauthStart({
  provider: 'acme',
  redirect: 'https://app.example.com/callback', // must be allowlisted on the backend
});

window.location.assign(url);

The full browser flow:

  1. Your page calls oauthStart and redirects to the returned provider url.
  2. The provider authenticates the User and redirects to the backend callback (GET /auth/oauth/callback). Signet owns this endpoint — do not implement it.
  3. Signet redeems the code, verifies the identity and creates a Session cookie.
  4. The backend redirects to your redirect URL. Read session state from your own app; the typed client does not keep a reactive session store.

If the User's email is not verified by the provider, the callback response carries a link_token instead of a Session. Pass it to your backend's explicit account-linking step before treating the User as signed in.

Separate backend repository

The backend team can merge this base spec into its own application spec and publish a versioned SDK. The frontend then depends on that SDK; a breaking server shape change becomes a major version and fails the build at the affected call sites. See HTTP API.

API keys

API keys are for non-human clients (CI jobs, scripts, server-to-server calls). The browser never creates or holds a raw key in a persisted store — your backend issues it with Go's Client.CreateAPIKey and shows the raw value to the user once. The frontend can still call the typed endpoints for management and verification:

// Issue a key — the backend's session cookie authenticates the owner.
const created = await auth.createApiKey({
  name: 'ci-pipeline',
  roles: ['ci'],
  remaining: 100,
});
showOnce(created.raw); // display once; never persist it in localStorage

// List and revoke keys owned by the signed-in User.
const { keys } = await auth.listApiKeys();
await auth.revokeApiKey({ id: keys[0].id });

// Verify a key from a non-human client (X-API-Key header, no Session).
const principal = await auth.verifyApiKey(rawKeyFromYourScript);
// principal.owner_user_id, principal.roles

For a browser app that authenticates by key on specific routes, the backend sets Config.APIKeyProtectedEndpoints; on those routes the X-API-Key header is required and the session cookie is ignored. There is no mixed principal. See API keys.

Organizations

Create an Organization, manage Members and switch the active Organization for the authenticated visit. The active organization lives in a signed cookie, so it survives navigation but cannot be forged by the client.

// Create and list Organizations.
const created = await auth.createOrganization({ name: 'Acme' });
const orgId = created.organization.id;
const { organizations: orgs } = await auth.listOrganizations();

// Manage Memberships. Role changes are guarded by the backend Authorizer.
// Add by User ID, or by email when the User already has an account.
await auth.addOrganizationMember({ organization_id: orgId, user_id: userId, role: 'member' });
await auth.addOrganizationMember({ organization_id: orgId, email: 'member@example.com', role: 'member' });
const { members: members } = await auth.listOrganizationMembers(orgId);
await auth.setOrganizationMemberRole({ organization_id: orgId, user_id: userId, role: 'admin' });
await auth.removeOrganizationMember({ organization_id: orgId, user_id: userId });

// Select, read and clear the active Organization.
await auth.setActiveOrganization({ organization_id: orgId });
const active = await auth.activeOrganization(); // { id: '...' }
await auth.clearActiveOrganization();

Every mutation requires a CSRF token (the client handles it automatically) and a fresh Session on the backend. A tampered active-organization cookie is treated as absent — always verify the value returned by activeOrganization() against your own data before rendering privileged UI. See Organizations.

Admin management

Admin endpoints are guarded by the backend's permission checks, fresh Session and Audit events — the frontend only calls them. The permission model is described in Authorization.

const { Users: users } = await auth.adminListUsers();
await auth.adminSetUserRole({ user_id: userId, roles: ['admin'] });
await auth.adminBanUser({ user_id: userId, reason: 'abuse' });
await auth.adminUnbanUser({ user_id: userId });

const { sessions } = await auth.adminListUserSessions(userId);
await auth.adminRevokeUserSession({ session_id: sessions[0].id });

A forbidden (403) response means a missing grant, a stale Session, or a self-action block — show a generic "not allowed" message; do not expose which check failed. See Admin management and Errors.

Impersonation

Impersonation creates a short-lived Session for the target User and a signed one-hour cookie holding the administrator ID and original Session token. The typed client handles both cookies:

const result = await auth.impersonate({ user_id: targetId });
// result.Token is the temporary Session; the browser now acts as the target.
// The client clears its cached CSRF token because the Session changed.

// Later — revoke the temporary Session and restore the original one.
await auth.stopImpersonating(result.Token);
await auth.clearCsrfToken();

While impersonating, admin checks use the administrator ID from the cookie, not the target User. The self-service account-deletion flow is disabled during impersonation. Treat a forbidden response from any guarded call as a reason to exit the impersonated view. See Admin management.

Passkeys

Passkeys are a phishing-resistant first factor. The backend configures the Relying party and stores credentials; the browser only handles the WebAuthn ceremony and the opaque ceremony token returned by Signet.

// Enroll — the caller must already have a Session.
const begin = await auth.beginPasskeyRegistration({ user_id: userId });
const credential = await navigator.credentials.create({
  publicKey: begin.options.publicKey,
});
await auth.finishPasskeyRegistration({
  token: begin.token,
  response: credential,
});

// Sign in — discoverable, so no username is needed.
const challenge = await auth.beginPasskeySignIn();
const assertion = await navigator.credentials.get({
  publicKey: challenge.options.publicKey,
  // Conditional mediation lets the browser offer the passkey as autofill.
  // Pair it with an input using autocomplete="username webauthn".
  mediation: 'conditional',
});
const result = await auth.finishPasskeySignIn({
  token: challenge.token,
  response: assertion,
});
// result.session_token is set as a cookie by the backend.

// Manage passkeys.
const { passkeys } = await auth.listPasskeys();
await auth.deletePasskey({ credential_id: passkeys[0].id });

Do not persist the ceremony token or the raw credential response in local storage — they are single-use. If a ceremony fails, call beginPasskeyRegistration or beginPasskeySignIn again to get a fresh challenge. The typed client clears its cached CSRF token after a passkey sign-in because the Session changes. See Passkeys for the backend setup.

Automatic sign-in

The typed client already returns the optional session token from Sign-up and email verification. When the backend enables automatic sign-in, no second signIn call is needed:

const signedUp = await auth.signUp({ email, password, name });
if (signedUp.session_token) {
  // A Session cookie is already set; proceed straight into the app.
}

const verified = await auth.verifyEmail({ token });
if (verified.session_token) {
  // Verification issued a Session and set the cookie.
}

The token is optional: it is absent whenever the matching automatic sign-in switch is off. See Verification and reset for the backend setup.

Authorization server

The typed client exposes the new OAuth endpoints. Authorization code and device flows are described fully in Authorization server.

// Authorization code with PKCE (the User must have a Session).
const authz = await auth.oauthAuthorize({
  client_id: 'cli',
  redirect_uri: 'http://localhost:8080/callback',
  response_type: 'code',
  scope: 'openid email',
  code_challenge: challenge,
});
const tokens = await auth.oauthToken({
  grant_type: 'authorization_code',
  code: authz.code,
  code_verifier: verifier,
  client_id: 'cli',
});

// Device flow: display the user code, then poll until approval.
const device = await auth.beginDeviceAuthorization({
  client_id: 'tv', scope: 'openid',
});
const deviceTokens = await auth.oauthToken({
  grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
  code: device.device_code,
});

Organization SSO

const start = await auth.startSSOSignIn({ email: 'member@acme.com' });
window.location.assign(start.url);
// On your callback page, read state and code from the URL:
const result = await auth.completeSSOSignIn(state, code);
// result.session_token and result.organization_id are set.

const connections = await auth.listSSOConnections();
await auth.createSSOConnection({
  organization_id: orgId, issuer, client_id, client_secret, domains: ['acme.com'],
});
await auth.deleteSSOConnection(connections[0].id);

React session hooks

For reactive session state in React — SignetProvider, useSession() and sessionGuard — use the separate React session hooks page. The hooks package depends on this client at the same 1.0.0-rc.1 version.

On this page