This is a preview of unreleased docs from main. View the published docs
Skip to main content

Interface: MemberNamespace

Defined in: types.ts:340

Methods for authenticating and identifying audience members.

Access this namespace via allegro.member.

Example​

window.allegro.push((allegro) => {
if (allegro.member.isAuthenticated()) {
const payload = allegro.member.sessionFromJwt();
console.log('Hello,', payload?.audience_member.name);
}
});

Authentication​

Logs the current member out, clears the session JWT, and dispatches allegro:logout.

logout()​

logout(): Promise<void>

Defined in: types.ts:428

Returns​

Promise<void>

Example​

await allegro.member.logout();

Authentication​

Returns true if the current session has a valid, authenticated JWT.

An authenticated session means the member has completed a login flow (magic link, social login, etc.). An identified-but-not-authenticated session only has an email association.

isAuthenticated()​

isAuthenticated(): boolean

Defined in: types.ts:362

Returns​

boolean

Example​

if (allegro.member.isAuthenticated()) {
showMemberContent();
} else {
showLoginPrompt();
}

Authentication​

Returns true if the session has a stored JWT — either identified or fully authenticated.

Use this to check whether an email has been associated with the session without requiring a completed login.

isIdentified()​

isIdentified(): boolean

Defined in: types.ts:371

Returns​

boolean

Authentication​

Returns the raw session JWT string, or null if no valid JWT is present or the token has expired.

Use this to authenticate against your own backend: send the token as a bearer header and verify it against the tenant's JWKS endpoint.

getJwt()​

getJwt(): string | null

Defined in: types.ts:404

Returns​

string | null

Example​

const jwt = allegro.member.getJwt();
if (jwt) {
fetch('/api/user', { headers: { Authorization: `Bearer ${jwt}` } });
}

Authentication​

Stores the given JWT as the active session, persisting it to both the in-memory store and the device session cookie.

Use this when your application obtains a JWT through its own flow and needs to hand it to the SDK.

setJwt()​

setJwt(jwt): void

Defined in: types.ts:386

Parameters​

ParameterType
jwtstring

Returns​

void

Example​

allegro.member.setJwt(jwtFromMyServer);

Entitlements​

Returns true if the member's JWT contains the given product slug in the products claim.

hasProduct()​

hasProduct(slug): boolean

Defined in: types.ts:417

Parameters​

ParameterType
slugstring

Returns​

boolean

Example​

if (allegro.member.hasProduct('voter-game-plan')) {
// show gated content
}

External Profiles​

Fetches the external profile data for the authenticated member from the given OAuth provider (e.g. "google").

Returns the raw attributes stored for that provider. The shape varies by provider — cast the result to a more specific type when needed.

Throws if the member is not authenticated or no profile exists for the provider.

externalProfile()​

externalProfile(provider): Promise<ExternalProfileAttributes>

Defined in: types.ts:775

Parameters​

ParameterTypeDescription
providerstringProvider slug, e.g. "google".

Returns​

Promise<ExternalProfileAttributes>

Example​

const profile = await allegro.member.externalProfile('google');
console.log(profile.email, profile.name);

Login Modal​

Closes the dialog {@link MemberNamespace.showLogin} opened, which resolves its promise with null. Does nothing when no dialog is open.

hideLogin()​

hideLogin(): void

Defined in: types.ts:664

Returns​

void

Login Modal​

Opens a dialog holding an <allegro-login-form>, and resolves with the session payload once the reader signs in, or null if they close the dialog.

The dialog closes itself on sign-in, and every usual event fires, including allegro:authenticated and the allegro:login-form:* events. The form's success screen is skipped. Resolves at once when the reader is already signed in. While a dialog is open, another call returns the same promise and ignores its options. Rejects when the components bundle can't load.

showLogin()​

showLogin(options?): Promise<MemberJwtPayload | null>

Defined in: types.ts:657

Parameters​

ParameterType
options?ShowLoginOptions

Returns​

Promise<MemberJwtPayload | null>

Example​

const session = await allegro.member.showLogin({ heading: 'Sign in to keep reading' });

if (session) {
console.log('Signed in as', session.sub);
}

Request a magic link email for the given address.

Sends an email containing a one-time login link. The session is also marked as "identified" so the member can be associated with future events before they click the link.

After calling this, the SDK automatically polls for authentication in the background — no manual polling is needed.

Call Signature​

requestMagicLink(email, returnUrl?, data?, captchaToken?): Promise<MagicLinkRequestResponse>

Defined in: types.ts:465

Parameters​
ParameterTypeDescription
emailstringThe member's email address.
returnUrl?stringURL the member is redirected to after clicking the link. Defaults to the current page URL.
data?Record<string, unknown>Arbitrary key/value data to store on the resulting session (e.g. referral source, plan selection).
captchaToken?string-
Returns​

Promise<MagicLinkRequestResponse>

Example​
await allegro.member.requestMagicLink('user@example.com');

// With a custom return URL and extra data
await allegro.member.requestMagicLink(
'user@example.com',
'https://example.com/dashboard',
{ plan: 'pro', source: 'homepage' },
);

Call Signature​

requestMagicLink(email, returnUrl, data, captchaToken, registration): Promise<MagicLinkRequestResponse | RegistrationRequiredResponse>

Defined in: types.ts:471

Parameters​
ParameterType
emailstring
returnUrlstring | undefined
dataRecord<string, unknown> | undefined
captchaTokenstring | undefined
registrationLoginRegistration
Returns​

Promise<MagicLinkRequestResponse | RegistrationRequiredResponse>

Validate a magic link token from the URL query string.

You typically don't call this directly — the SDK validates the ?allegro_token= query parameter automatically on page load.

validateMagicLink(token): Promise<MagicLinkValidateResponse>

Defined in: types.ts:495

Parameters​

ParameterTypeDescription
tokenstringThe one-time token from the magic link URL.

Returns​

Promise<MagicLinkValidateResponse>

Example​

const token = new URLSearchParams(location.search).get('allegro_token') ?? '';
const result = await allegro.member.validateMagicLink(token);
console.log(result.return_url);

OTP​

Request a combined magic link and one-time code in a single email.

Emails both a magic sign-in link and a six-digit code. Unlike {@link requestLoginCode}, this DOES start background auth polling so that clicking the link in any browser authenticates this session while the code input is shown.

requestMagicLinkOtp()​

Call Signature​

requestMagicLinkOtp(email, returnUrl?, data?, captchaToken?): Promise<MagicLinkOtpRequestResponse>

Defined in: types.ts:550

Parameters​
ParameterTypeDescription
emailstringThe member's email address.
returnUrl?stringURL the member is redirected to after authenticating. Defaults to the current page URL.
data?Record<string, unknown>Arbitrary key/value data to store on the resulting session.
captchaToken?stringCaptcha token, when the tenant has a provider configured. Omitting it against a captcha-protected tenant is rejected with CAPTCHA_FAILED.
Returns​

Promise<MagicLinkOtpRequestResponse>

Call Signature​

requestMagicLinkOtp(email, returnUrl, data, captchaToken, registration): Promise<RegistrationRequiredResponse | MagicLinkOtpRequestResponse>

Defined in: types.ts:556

Parameters​
ParameterType
emailstring
returnUrlstring | undefined
dataRecord<string, unknown> | undefined
captchaTokenstring | undefined
registrationLoginRegistration
Returns​

Promise<RegistrationRequiredResponse | MagicLinkOtpRequestResponse>

OTP​

Request a one-time passcode email for the given address.

Emails a six-digit code. Unlike {@link requestMagicLink}, this does NOT start background auth polling — the user enters the code on this device and {@link validateLoginCode} completes authentication synchronously.

requestLoginCode()​

Call Signature​

requestLoginCode(email, returnUrl?, data?, captchaToken?): Promise<OtpRequestResponse>

Defined in: types.ts:518

Parameters​
ParameterTypeDescription
emailstringThe member's email address.
returnUrl?stringURL the member is redirected to after authenticating. Defaults to the current page URL.
data?Record<string, unknown>Arbitrary key/value data to store on the resulting session.
captchaToken?stringCaptcha token, when the tenant has a provider configured. Omitting it against a captcha-protected tenant is rejected with CAPTCHA_FAILED.
Returns​

Promise<OtpRequestResponse>

Call Signature​

requestLoginCode(email, returnUrl, data, captchaToken, registration): Promise<RegistrationRequiredResponse | OtpRequestResponse>

Defined in: types.ts:524

Parameters​
ParameterType
emailstring
returnUrlstring | undefined
dataRecord<string, unknown> | undefined
captchaTokenstring | undefined
registrationLoginRegistration
Returns​

Promise<RegistrationRequiredResponse | OtpRequestResponse>

OTP​

Validate a one-time passcode entered by the member. On success the session JWT is stored and an allegro:authenticated event is dispatched. On failure an {@link AllegroApiError} is thrown with errorCode one of INVALID_OTP, OTP_LOCKED.

validateLoginCode()​

validateLoginCode(code): Promise<OtpValidateResponse>

Defined in: types.ts:573

Parameters​

ParameterTypeDescription
codestringThe six-digit code entered by the member.

Returns​

Promise<OtpValidateResponse>

Profile​

Updates the authenticated member's own record. Only the fields passed are written; the rest are left as they are. Returns the stored profile, which can differ from what was sent — the server trims surrounding whitespace. The session JWT is refreshed automatically.

updateProfile()​

updateProfile(profile): Promise<MemberProfile>

Defined in: types.ts:795

Parameters​

ParameterTypeDescription
profilePartial<MemberProfile>The fields to write.

Returns​

Promise<MemberProfile>

Example​

await allegro.member.updateProfile({ name: 'Alex Jones' });

Session​

Associates an email address with the current anonymous session without requiring a full login.

Use this to identify a member before they authenticate — for example, when they enter their email on a registration form. The session will appear as "identified" but not "authenticated".

Pass attributes to store user attribute values against the member, keyed by slug. A value is only stored when the member has none for that attribute yet, so existing values are never overwritten. The whole call is rejected if a slug is undefined or not editable, or a value fails its type or validation rules.

identifyByEmail()​

identifyByEmail(email, data?, attributes?): Promise<IdentifySessionResponse>

Defined in: types.ts:698

Parameters​

ParameterTypeDescription
emailstringThe email address to associate with this session.
data?Record<string, unknown>Extra request data passed to integrations, such as newsletter signups.
attributes?Record<string, unknown>User attribute values to store, keyed by attribute slug.

Returns​

Promise<IdentifySessionResponse>

Example​

await allegro.member.identifyByEmail('user@example.com');

await allegro.member.identifyByEmail('user@example.com', undefined, {
'wants-newsletter': true,
});

Session​

Fetches live session data from the API.

Includes authentication status, timestamps, and the associated audience member record if the session is identified.

session()​

session(): Promise<SessionResponse>

Defined in: types.ts:717

Returns​

Promise<SessionResponse>

Example​

const { data } = await allegro.member.session();
console.log(data.is_authenticated, data.audience_member?.email);

Session​

Fetches the member's active entitlements.

entitlements()​

entitlements(): Promise<MemberEntitlement[]>

Defined in: types.ts:746

Returns​

Promise<MemberEntitlement[]>

Example​

const entitlements = await allegro.member.entitlements();
const hasPro = entitlements.some((e) => e.name === 'pro');

Session​

Reads session data from the JWT stored in the browser cookie — no network request required.

Returns null if no valid JWT is present or the token has expired.

sessionFromJwt()​

sessionFromJwt(): MemberJwtPayload | null

Defined in: types.ts:734

Returns​

MemberJwtPayload | null

Example​

const payload = allegro.member.sessionFromJwt();
if (payload) {
console.log('Member ID:', payload.sub);
}

Session​

Silently refreshes the JWT if it was issued more than 24 hours ago.

Called automatically on SDK initialisation. Safe to call manually if needed — it is a no-op when the token is still fresh.

refreshJwtIfNeeded()​

refreshJwtIfNeeded(): Promise<void>

Defined in: types.ts:755

Returns​

Promise<void>

Social Login​

Authenticate via a third-party OAuth provider by navigating the current window, instead of opening a popup. Use it where popups don't work: mobile browsers, in-app browsers, or a page that is itself a popup.

The provider redirects back to returnUrl once authentication completes; this method never resolves because the current page navigates away. returnUrl must be on one of the tenant's or property's allowed origins. On return the SDK signs the member in automatically and dispatches allegro:social:authenticated, or allegro:social:failed.

loginWithProviderRedirect()​

loginWithProviderRedirect(provider, returnUrl, data?): void

Defined in: types.ts:619

Parameters​

ParameterTypeDescription
providerstringProvider slug, e.g. "google" or "apple".
returnUrlstringThe URL to redirect back to once authentication completes.
data?Record<string, unknown>Arbitrary key/value data to store on the resulting session.

Returns​

void

Social Login​

Authenticate via a third-party OAuth provider using a popup window.

The list of available providers is configured per tenant (allegro.tenant.loginProviders). The calling page's origin must be one of the tenant's or property's allowed origins, or the popup cannot hand the result back.

loginWithProvider()​

loginWithProvider(provider, data?): Promise<SocialLoginResponse>

Defined in: types.ts:602

Parameters​

ParameterTypeDescription
providerstringProvider slug, e.g. "google" or "apple".
data?Record<string, unknown>Arbitrary key/value data to store on the resulting session.

Returns​

Promise<SocialLoginResponse>

Example​

try {
const result = await allegro.member.loginWithProvider('google');
console.log('Logged in, token:', result.token);
} catch (err) {
// err.name is 'PopupBlockedError' when the browser refused to open the popup;
// fall back to loginWithProviderRedirect() in that case.
console.error('Login failed or popup was blocked:', err);
}

Social Login​

Exchange the one-time code a redirect-based social login appends to the returning page for the member's JWT, and store it.

You typically don't call this directly — the SDK exchanges the ?allegro_social_code= query parameter automatically on page load.

exchangeSocialLoginCode()​

exchangeSocialLoginCode(code): Promise<SocialLoginExchangeResponse>

Defined in: types.ts:631

Parameters​

ParameterTypeDescription
codestringThe one-time code from the allegro_social_code query parameter.

Returns​

Promise<SocialLoginExchangeResponse>

User Attributes​

Clears the authenticated member's value for a user attribute. The session JWT is refreshed automatically.

deleteUserAttribute()​

deleteUserAttribute(slug): Promise<void>

Defined in: types.ts:876

Parameters​

ParameterTypeDescription
slugstringThe attribute slug.

Returns​

Promise<void>

User Attributes​

Lists the user attributes defined by the organization together with the authenticated member's current value for each (null when unset).

getUserAttributes()​

getUserAttributes(): Promise<UserAttributeValue[]>

Defined in: types.ts:807

Returns​

Promise<UserAttributeValue[]>

Example​

const attributes = await allegro.member.getUserAttributes();

User Attributes​

Returns the authenticated member's attribute values keyed by slug, read synchronously from a localStorage cache — no network request. Returns null when the member is not authenticated or nothing is cached yet.

The SDK fills the cache on login and on boot when it is missing or more than five minutes old, and clears and refetches it after every attribute write. Each fill or clear fires allegro:user-attributes:updated with { values } in detail (null when cleared).

userAttributesFromCache()​

userAttributesFromCache(): Record<string, unknown> | null

Defined in: types.ts:826

Returns​

Record<string, unknown> | null

Example​

const attributes = allegro.member.userAttributesFromCache();
const firstName = attributes?.name_first;

User Attributes​

Sets the authenticated member's value for a user attribute. The server validates the value against the attribute's declared type and returns the stored (cast) value. The session JWT is refreshed automatically.

setUserAttribute()​

setUserAttribute(slug, value): Promise<unknown>

Defined in: types.ts:842

Parameters​

ParameterTypeDescription
slugstringThe attribute slug.
valueunknownThe value to store.

Returns​

Promise<unknown>

Example​

await allegro.member.setUserAttribute('wants-newsletter', true);

User Attributes​

Sets the authenticated member's values for several user attributes at once, and resolves with the stored (cast) values keyed by slug. A null value clears the member's value for that attribute. The session JWT is refreshed automatically.

The server validates every value before writing any of them, so the whole call is rejected without saving anything if one slug is undefined, one attribute is not editable, or one value fails its type or validation rules.

setUserAttributes()​

setUserAttributes(values): Promise<Record<string, unknown>>

Defined in: types.ts:867

Parameters​

ParameterTypeDescription
valuesRecord<string, unknown>The values to store, keyed by attribute slug.

Returns​

Promise<Record<string, unknown>>

Example​

await allegro.member.setUserAttributes({
'wants-newsletter': true,
'display-name': 'Jane',
color: null, // clears the stored value
});