Skip to main content

Next.js — Group

Associate users with groups (e.g. company, organization) and set group properties. Available on both client and server.

Client: useSignalGroup

Use the same hook as the React integration, re-exported from @signal-js/nextjs/client:
'use client';

import { useSignalGroup } from '@signal-js/nextjs/client';

function CompanySwitcher({ companies }) {
  const { group, getGroups } = useSignalGroup();

  const handleSelectCompany = (companyId, companyName) => {
    group('company', companyId, { name: companyName });
  };

  return (
    <select onChange={(e) => {
      const c = companies.find(c => c.id === e.target.value);
      if (c) handleSelectCompany(c.id, c.name);
    }}>
      {companies.map((c) => (
        <option key={c.id} value={c.id}>{c.name}</option>
      ))}
    </select>
  );
}

Client: group(groupType, groupKey, properties?)

Associate the current user with a group. Optionally set group properties.
ParameterTypeRequiredDescription
groupTypestringyesType of group (e.g. 'company', 'organization')
groupKeystringyesUnique identifier for the group
propertiesRecord<string, unknown>noGroup properties to set

Client: getGroups()

Get all groups the user is currently associated with. Returns an array of group objects.

Server: group(distinctId, groupType, groupKey, properties?, sessionId?, windowId?)

Associate a user with a group from the server. Pass sessionId and windowId for client correlation.
ParameterTypeRequiredDescription
distinctIdstringyesUser identifier
groupTypestringyesType of group (e.g. 'company', 'organization')
groupKeystringyesUnique identifier for the group
propertiesRecord<string, unknown>noGroup properties to set
sessionIdstringnoFrom x-signal-session-id header for client correlation
windowIdstringnoFrom x-signal-window-id header for client correlation
// app/api/user/company/route.ts
import { signal, getSessionInfo } from '@/lib/signal-server';
import { NextRequest } from 'next/server';

export async function POST(request: NextRequest) {
  const { sessionId, windowId, distinctId } = getSessionInfo(request);
  const body = await request.json();

  // Associate user with company
  signal.group(
    distinctId || body.userId,
    'company',
    body.companyId,
    { role: 'admin' },
    sessionId,
    windowId
  );

  return Response.json({ success: true });
}

Server: groupIdentify(options, sessionId?, windowId?)

Set or update group properties from the server. Pass sessionId and windowId for client correlation.
OptionTypeRequiredDescription
groupTypestringyesType of group (e.g. 'company', 'organization')
groupKeystringyesGroup identifier
propertiesRecord<string, unknown>noGroup properties to set
// Update company properties
signal.groupIdentify(
  { groupType: 'company', groupKey: 'acme', properties: { plan: 'enterprise', seats: 50 } },
  sessionId,
  windowId
);

See also