Skip to Content
Signet

React session hooks

Reactive session state in React apps using Signet's typed client.

@shakibdshy/signet-auth-react is an optional React binding over the framework-neutral typed client. It provides SignetProvider, useSession() and sessionGuard, so components can read one shared session state instead of calling the client themselves.

Version alignment

Both packages are released together at 1.0.0-rc.1. signet-auth-react@1.0.0-rc.1 depends on signet-auth-client@1.0.0-rc.1, so a published install pulls in the typed client automatically. The local-checkout install below is for testing unreleased changes.

PackageVersionRole
@shakibdshy/signet-auth-client1.0.0-rc.1Typed HTTP client, framework-neutral
@shakibdshy/signet-auth-react1.0.0-rc.1Provider, hooks and route guard; depends on the client

1. Install

npm install @shakibdshy/signet-auth-react

This also installs @shakibdshy/signet-auth-client@1.0.0-rc.1; do not install the client separately.

2. Create the typed client

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

export const auth = createSignetClient({
  baseURL: 'https://api.example.com/auth', // must include Config.PathPrefix
});

See Frontend client for every available method, error handling and the baseURL rules.

3. Wrap your app in the provider

// main.tsx
import { SignetProvider } from '@shakibdshy/signet-auth-react';
import { auth } from './signet-auth-client';
import { App } from './App';

export function Root() {
  return (
    <SignetProvider client={auth}>
      <App />
    </SignetProvider>
  );
}

The provider performs one GET /me request on mount and shares status, user and error with every consumer.

4. Use the session in a component

// Profile.tsx
import { useState } from 'react';
import { useSession } from '@shakibdshy/signet-auth-react';

export function Profile() {
  const { status, user, error, signIn, signOut, refresh } = useSession();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  if (status === 'loading') return <p>Loading…</p>;
  if (error) return <p role="alert">{error.message}</p>;

  if (status === 'anonymous') {
    return (
      <form onSubmit={async (e) => {
        e.preventDefault();
        await signIn({ email, password });
      }}>
        <input value={email} onChange={(e) => setEmail(e.target.value)} />
        <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
        <button type="submit">Sign in</button>
      </form>
    );
  }

  return (
    <>
      <p>Signed in as {user?.email}</p>
      <button onClick={() => signOut()}>Sign out</button>
      <button onClick={() => refresh()}>Refresh</button>
    </>
  );
}

signIn and signOut update the shared state, so every useSession() consumer re-renders. Errors are the generated SignetApiError from the typed client, unchanged.

If the backend requires a Second factor, signIn resolves without creating a Session: the challenge response is a success, the following Session check fails, and status stays "anonymous". Run the Second factor step with the typed client directly (see Frontend client) and then call refresh().

5. Protect a server-rendered route

// middleware.ts (Next.js example)
import { sessionGuard } from '@shakibdshy/signet-auth-react';

export async function middleware(request: Request) {
  const ok = await sessionGuard(
    'https://api.example.com/auth',
    request.headers.get('cookie') ?? '',
  );
  if (!ok) return Response.redirect(new URL('/signin', request.url));
  return Response.next();
}

export const config = { matcher: ['/private/:path*'] };

sessionGuard appends /me to the configured base URL, preserving a PathPrefix. It checks the incoming cookies and never creates a Session itself.

On this page