Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ export class SubscriberSessionResponseDto {
readonly isDevelopmentMode: boolean;
readonly applicationIdentifier?: string;
readonly schedule?: Schedule;
readonly contextKeys?: string[];
}
1 change: 1 addition & 0 deletions apps/api/src/app/inbox/usecases/session/session.usecase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ export class Session {
maxSnoozeDurationHours,
isDevelopmentMode: environment.name.toLowerCase() !== 'production',
schedule,
contextKeys,
};
}

Expand Down
4 changes: 4 additions & 0 deletions packages/js/src/api/inbox-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type {
ActionTypeEnum,
ChannelPreference,
Context,
DefaultSchedule,
InboxNotification,
NotificationFilter,
Expand Down Expand Up @@ -31,17 +32,20 @@ export class InboxService {
subscriberHash,
subscriber,
defaultSchedule,
context,
}: {
applicationIdentifier?: string;
subscriberHash?: string;
subscriber?: Subscriber;
defaultSchedule?: DefaultSchedule;
context?: Context;
}): Promise<Session> {
const response = (await this.#httpClient.post(`${INBOX_ROUTE}/session`, {
applicationIdentifier,
subscriberHash,
subscriber,
defaultSchedule,
context,
})) as Session;
this.#httpClient.setAuthorizationToken(response.token);
this.#httpClient.setKeylessHeader(response.applicationIdentifier);
Expand Down
1 change: 1 addition & 0 deletions packages/js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export { Novu } from './novu';
export {
ChannelPreference,
ChannelType,
Context,
DaySchedule,
DefaultSchedule,
FiltersCountResponse,
Expand Down
11 changes: 10 additions & 1 deletion packages/js/src/novu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Notifications } from './notifications';
import { Preferences } from './preferences';
import { Session } from './session';
import type { NovuOptions, Subscriber } from './types';
import { buildSubscriber } from './ui/internal';
import { buildContextKey, buildSubscriber } from './ui/internal';
import { createSocket } from './ws';
import type { BaseSocketInterface } from './ws/base-socket';

Expand Down Expand Up @@ -33,6 +33,14 @@ export class Novu implements Pick<NovuEventEmitter, 'on'> {
return this.#session.subscriberId;
}

public get context() {
return this.#session.context;
}

public get contextKey() {
return buildContextKey(this.#session.context);
}
Comment on lines +36 to +42
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The context is passed to the Novu constructor, so it is defined in the client code. I am not sure if it would be helpful to expose that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes thats true I just did it for the consistency with the other attributes.


constructor(options: NovuOptions) {
this.#inboxService = new InboxService({
apiUrl: options.apiUrl || options.backendUrl,
Expand All @@ -45,6 +53,7 @@ export class Novu implements Pick<NovuEventEmitter, 'on'> {
subscriberHash: options.subscriberHash,
subscriber: buildSubscriber({ subscriberId: options.subscriberId, subscriber: options.subscriber }),
defaultSchedule: options.defaultSchedule,
context: options.context,
},
this.#inboxService,
this.#emitter
Expand Down
7 changes: 6 additions & 1 deletion packages/js/src/session/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ export class Session {
return this.#options.subscriber?.subscriberId;
}

public get context() {
return this.#options.context;
}

private handleApplicationIdentifier(method: 'get' | 'store' | 'delete', identifier?: string): string | null {
if (typeof window === 'undefined' || !window.localStorage) {
return null;
Expand Down Expand Up @@ -64,7 +68,7 @@ export class Session {
if (options) {
this.#options = options;
}
const { subscriber, subscriberHash, applicationIdentifier, defaultSchedule } = this.#options;
const { subscriber, subscriberHash, applicationIdentifier, defaultSchedule, context } = this.#options;
let currentTimezone;
if (isBrowser()) {
currentTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
Expand All @@ -90,6 +94,7 @@ export class Session {
timezone: subscriber?.timezone ?? currentTimezone,
},
defaultSchedule,
context,
});

if (response?.applicationIdentifier?.startsWith('pk_keyless_')) {
Expand Down
3 changes: 2 additions & 1 deletion packages/js/src/session/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DefaultSchedule, Subscriber } from '../types';
import { Context, DefaultSchedule, Subscriber } from '../types';

export type KeylessInitializeSessionArgs = {} & { [K in string]?: never }; // empty object,disallows all unknown keys

Expand All @@ -9,4 +9,5 @@ export type InitializeSessionArgs =
subscriber: Subscriber;
subscriberHash?: string;
defaultSchedule?: DefaultSchedule;
context?: Context;
};
11 changes: 11 additions & 0 deletions packages/js/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export type Session = {
isDevelopmentMode: boolean;
maxSnoozeDurationHours: number;
applicationIdentifier?: string;
contextKeys?: string[];
};

export type Subscriber = {
Expand Down Expand Up @@ -204,6 +205,15 @@ export type DefaultSchedule = {
weeklySchedule?: WeeklySchedule;
};

export type ContextValue =
| string
| {
id: string;
data?: Record<string, unknown>;
};

export type Context = Partial<Record<string, ContextValue>>;

export type PreferencesResponse = {
level: PreferenceLevel;
enabled: boolean;
Expand Down Expand Up @@ -247,6 +257,7 @@ export type StandardNovuOptions = {
socketUrl?: string;
useCache?: boolean;
defaultSchedule?: DefaultSchedule;
context?: Context;
} & (
| {
// TODO: Backward compatibility support - remove in future versions (see NV-5801)
Expand Down
4 changes: 4 additions & 0 deletions packages/js/src/ui/context/InboxContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type InboxContextType = {
isSnoozeEnabled: Accessor<boolean>;
isKeyless: Accessor<boolean>;
applicationIdentifier: Accessor<string | null>;
contextKeys: Accessor<string[] | undefined>;
};

const InboxContext = createContext<InboxContextType | undefined>(undefined);
Expand Down Expand Up @@ -77,6 +78,7 @@ export const InboxProvider = (props: InboxProviderProps) => {
);
const [isKeyless, setIsKeyless] = createSignal(false);
const [applicationIdentifier, setApplicationIdentifier] = createSignal<string | null>(null);
const [contextKeys, setContextKeys] = createSignal<string[] | undefined>(undefined);
const [preferenceGroups, setPreferenceGroups] = createSignal<PreferenceGroups | undefined>(props.preferenceGroups);
const [preferencesSort, setPreferencesSort] = createSignal<PreferencesSort | undefined>(props.preferencesSort);

Expand Down Expand Up @@ -141,6 +143,7 @@ export const InboxProvider = (props: InboxProviderProps) => {
setHideBranding(data.removeNovuBranding);
setIsDevelopmentMode(data.isDevelopmentMode);
setMaxSnoozeDurationHours(data.maxSnoozeDurationHours);
setContextKeys(data.contextKeys);

if (data.isDevelopmentMode && !props.applicationIdentifier) {
setIsKeyless(!data.applicationIdentifier || !!identifier?.startsWith('pk_keyless_'));
Expand Down Expand Up @@ -174,6 +177,7 @@ export const InboxProvider = (props: InboxProviderProps) => {
isSnoozeEnabled,
isKeyless,
applicationIdentifier,
contextKeys,
}}
>
{props.children}
Expand Down
2 changes: 1 addition & 1 deletion packages/js/src/ui/helpers/useWebSocketEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const useWebSocketEvent = <E extends SocketEventNames>({
eventHandler: (args: Events[E]) => void;
}) => {
const novu = useNovu();
const channelName = `nv_ws_connection:a=${novu.applicationIdentifier}:s=${novu.subscriberId}:e=${webSocketEvent}`;
const channelName = `nv_ws_connection:a=${novu.applicationIdentifier}:s=${novu.subscriberId}:c=${novu.contextKey}:e=${webSocketEvent}`;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Context = session boundary - we open a new WS connection with separate JWT token for each context.


const { postMessage } = useBrowserTabsChannel({ channelName, onMessage });

Expand Down
30 changes: 30 additions & 0 deletions packages/js/src/ui/internal/buildContextKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Context } from '../../types';

/**
* Builds a compact, stable string key from context objects by extracting only type:id pairs.
*
* This avoids including large `data` payloads in:
* - React dependency arrays (useMemo)
* - Web Locks API channel names (prevents duplicate subscriptions)
*
* @example
* buildContextKey({ tenant: { id: "inbox-1", data: {...} } }) // "tenant:inbox-1"
* buildContextKey({ tenant: "inbox-1" }) // "tenant:inbox-1"
* buildContextKey(undefined) // ""
*/
export function buildContextKey(context: Context | undefined): string {
if (!context) {
return '';
}

const keys: string[] = [];
for (const [type, value] of Object.entries(context)) {
if (value) {
const id = typeof value === 'string' ? value : value.id;
keys.push(`${type}:${id}`);
}
}

// Sort for consistency (order shouldn't matter)
return keys.sort().join(',');
}
1 change: 1 addition & 0 deletions packages/js/src/ui/internal/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './buildContextKey';
export * from './buildSubscriber';
export * from './parseMarkdown';
4 changes: 4 additions & 0 deletions packages/react/src/components/Inbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export const Inbox = React.memo((props: InboxProps) => {
socketUrl: props.socketUrl,
subscriber,
defaultSchedule: props.defaultSchedule,
context: props.context,
} satisfies StandardNovuOptions;

return (
Expand All @@ -139,6 +140,7 @@ const InboxChild = withRenderer(
socketUrl,
subscriber,
defaultSchedule,
context,
} = props;
const novu = useNovu();

Expand All @@ -158,6 +160,7 @@ const InboxChild = withRenderer(
socketUrl,
subscriber: buildSubscriber({ subscriberId, subscriber }),
defaultSchedule,
context,
},
};
}, [
Expand All @@ -173,6 +176,7 @@ const InboxChild = withRenderer(
backendUrl,
socketUrl,
subscriber,
context,
]);

if (isWithChildrenProps(props)) {
Expand Down
4 changes: 3 additions & 1 deletion packages/react/src/hooks/NovuProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const InternalNovuProvider = (props: NovuProviderProps & { userAgentType:
useCache,
userAgentType,
defaultSchedule,
context,
} = props;

const novu = useMemo(
Expand All @@ -67,8 +68,9 @@ export const InternalNovuProvider = (props: NovuProviderProps & { userAgentType:
__userAgent: `${baseUserAgent} ${userAgentType}`,
subscriber: subscriberObj,
defaultSchedule,
context,
}),
[applicationIdentifier, subscriberHash, backendUrl, apiUrl, socketUrl, useCache, userAgentType]
[applicationIdentifier, subscriberHash, backendUrl, apiUrl, socketUrl, useCache, userAgentType, context]
);

useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/hooks/internal/useWebsocketEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const useWebSocketEvent = <E extends SocketEventNames>({
eventHandler: (args: Events[E]) => void;
}) => {
const novu = useNovu();
const channelName = `nv_ws_connection:a=${novu.applicationIdentifier}:s=${novu.subscriberId}:e=${webSocketEvent}`;
const channelName = `nv_ws_connection:a=${novu.applicationIdentifier}:s=${novu.subscriberId}:c=${novu.contextKey}:e=${webSocketEvent}`;

const { postMessage } = useBrowserTabsChannel({
channelName,
Expand Down
3 changes: 2 additions & 1 deletion packages/react/src/utils/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { DefaultSchedule, Subscriber, UnreadCount } from '@novu/js';
import type { Context, DefaultSchedule, Subscriber, UnreadCount } from '@novu/js';
import type {
IconKey,
InboxProps,
Expand Down Expand Up @@ -66,6 +66,7 @@ type StandardBaseProps = {
preferencesSort?: PreferencesSort;
defaultSchedule?: DefaultSchedule;
routerPush?: RouterPush;
context?: Context;
} & (
| {
// TODO: Backward compatibility support - remove in future versions (see NV-5801)
Expand Down
Loading