AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating the Glean Web SDK: Embedding Unified Search and AI Chat into Internal Portals

Dan Budington · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

When enterprise developers build internal developer portals, intranet knowledge hubs, or employee dashboards, search is often treated as an external bookmark. Forcing engineers and employees to open an external tab for Glean whenever they need an architecture diagram, Jira ticket, or HR policy creates workflow friction. Context-switching breaks productivity, and search adoption drops. Conversely, attempting to build a custom frontend search experience from scratch against raw REST APIs forces engineering teams to reinvent autocomplete debouncing, keyboard navigation, tabbed federated filtering, citation rendering, and streaming chat bubbles.

At 365Finds, our commercial and architectural assessment is straightforward: enterprise teams should not hand-roll custom UI components when integrating workplace search. Glean's official frontend toolkit, @gleanwork/web-sdk, provides modular, production-ready components that inherit enterprise access control lists (ACLs) out of the box. Embedding these components directly into existing platforms preserves employee focus while slashing internal development timelines from months to hours.

This guide provides a comprehensive technical walkthrough for full-stack engineers and enterprise architects integrating the Glean Web SDK into internal web applications, covering component selection, React mounting patterns, and production-grade token authentication.


SDK Installation and Global Setup

The Glean Web SDK can be integrated via modern JavaScript package managers or through a standalone script tag.

1. Package Installation (Recommended)

For modern Single Page Applications (React, Next.js, Vue, Angular) built with Vite, Webpack, or Turbopack:

npm install @gleanwork/web-sdk
# or
yarn add @gleanwork/web-sdk
# or
pnpm add @gleanwork/web-sdk

2. Script Tag Loading (Legacy Portals and CMS)

For server-rendered portals (Django, Rails, PHP, WordPress) where bundlers are absent, include the deferred script in the HTML <head>:

<script 
  defer 
  src="https://{GLEAN_APP_DOMAIN}/glean-web-sdk-latest.min.js">
</script>

When loaded via a script tag, the SDK registers globally on window.GleanWebSDK once the glean:ready lifecycle event fires:

window.addEventListener('glean:ready', () => {
  // window.GleanWebSDK is ready for invocation
});

Critical Domain Architecture

A frequent source of deployment errors is confusing the Web App Domain with the Backend Domain:

Domain TypeExample ValueWhere to Find ItRole in Integration
Web App Domainapp.glean.com or acme.glean.comGlean Admin > About Glean > Web app URLUsed for script CDN loading and redirect links
Backend Domainhttps://acme-be.glean.comGlean Admin > About Glean > Server instance (QE)Passed as backend option in all SDK calls

All SDK methods require the backend URL ending in -be.glean.com (or your on-premise gateway equivalent) to route API calls directly to the customer query engine.


Core Component Integration Patterns

The Glean Web SDK provides three primary embedding strategies. Choosing the right one depends on your internal portal's layout and user interaction goals.

Pattern 1: Fast Global Search via Modal (attach)

If your portal already features a global header with a search input or a keyboard shortcut like Cmd+K, the attach method is the fastest and cleanest path. It binds directly to an existing HTML <input> or focusable container without altering your page layout.

When an employee clicks or focuses the input, Glean automatically triggers an overlay modal containing recent searches, real-time autocomplete suggestions, federated datasource filters, and full search results.

import { attach } from '@gleanwork/web-sdk';

const searchInputElement = document.getElementById('global-search-input');

if (searchInputElement) {
  attach(searchInputElement, {
    backend: 'https://acme-be.glean.com',
    onSearch: (query) => {
      console.log('Search executed for telemetry:', query);
    },
    onDetach: () => {
      console.log('Modal dismissed, focus returned to portal');
    },
    datasourcesFilter: ['jira', 'confluence', 'github', 'slack'],
    searchBoxCustomizations: {
      placeholderText: 'Search engineering specs, tickets, and Slack…',
    },
  });
}

Key Advantages:


Pattern 2: Decoupled Full Search Hub (renderSearchBox + renderSearchResults)

When designing a dedicated "Company Knowledge" landing page or an intranet search portal, you need deep UI layout control. You can decouple the autocomplete input box from the tabbed results feed using renderSearchBox and renderSearchResults.

import { renderSearchBox, renderSearchResults } from '@gleanwork/web-sdk';

const boxContainer = document.getElementById('search-box-container');
const resultsContainer = document.getElementById('search-results-container');

let activeQuery = '';

function synchronizeSearch(newQuery: string) {
  activeQuery = newQuery;
  renderAll();
}

function renderAll() {
  if (!boxContainer || !resultsContainer) return;

  // Render autocomplete search bar
  renderSearchBox(boxContainer, {
    backend: 'https://acme-be.glean.com',
    query: activeQuery,
    onSearch: (query) => synchronizeSearch(query),
  });

  // Render tabbed federated results list
  renderSearchResults(resultsContainer, {
    backend: 'https://acme-be.glean.com',
    query: activeQuery,
    onSearch: (query) => synchronizeSearch(query),
  });
}

// Initial render
renderAll();

Frontend Layout Pitfalls

  1. Container Sizing for the Search Box: Size the boxContainer strictly to the height of the input bar (typically 50px to 90px). Do not size it to accommodate the anticipated dropdown height.
  2. Avoiding CSS Clipping: The autocomplete dropdown renders below the input box and extends beyond container boundaries. Verify that no parent DOM element applies overflow: hidden or overflow: scroll.
  3. Z-Index Layering: Ensure the search box container has a higher CSS z-index than adjacent navigation bars, banners, or results containers beneath it. Otherwise, autocomplete suggestions will render behind the page content.

Pattern 3: In-Situ Generative AI Chat (renderChat)

To empower team members with instant, conversational answers grounded directly in corporate knowledge, you can embed Glean Chat into side panels, helpdesk dashboards, or onboarding portals.

Glean Chat delivers generative responses with verifiable citations back to the source documents in Google Drive, Notion, GitHub, and Jira, tailored to what the active user is permitted to see.

import { renderChat } from '@gleanwork/web-sdk';

const chatContainer = document.getElementById('glean-chat-widget');

if (chatContainer) {
  renderChat(chatContainer, {
    backend: 'https://acme-be.glean.com',
    agent: 'ADVANCED', // Uses Glean's agentic reasoning engine
    initialMessage: 'How do I request AWS sandbox access for my team?',
    customizations: {
      showAgentLibrary: true,
      showPromptLibrary: true,
      showFeedback: true,
    },
  });
}

Container Sizing Rule

The DOM element passed into renderChat must have explicit CSS styling:

#glean-chat-widget {
  position: relative;
  display: block;
  width: 100%;
  height: 650px; /* Explicit height is mandatory */
}

If height is omitted or set to height: auto, the chat scroll container will collapse or produce rendering glitches.


Production React Component Blueprint

In modern web applications, SDK components must be initialized inside React lifecycle hooks, bound to DOM references, and cleaned up cleanly upon unmounting.

Here is a battle-tested React implementation embedding a coordinated search and chat interface:

import React, { useEffect, useRef, useState } from 'react';
import { renderSearchBox, renderSearchResults, renderChat } from '@gleanwork/web-sdk';

interface GleanPortalProps {
  backendUrl: string;
  userAuthToken: string;
  onRefreshToken: () => Promise<string>;
}

export const GleanInternalHub: React.FC<GleanPortalProps> = ({
  backendUrl,
  userAuthToken,
  onRefreshToken,
}) => {
  const [query, setQuery] = useState<string>('');
  const [activeTab, setActiveTab] = useState<'search' | 'chat'>('search');

  const searchBoxRef = useRef<HTMLDivElement>(null);
  const searchResultsRef = useRef<HTMLDivElement>(null);
  const chatRef = useRef<HTMLDivElement>(null);

  // Common authentication options
  const commonOptions = {
    backend: backendUrl,
    authMethod: 'token' as const,
    authToken: userAuthToken,
    onAuthTokenRequired: onRefreshToken,
    theme: 'system' as const,
  };

  useEffect(() => {
    if (activeTab === 'search') {
      if (searchBoxRef.current) {
        renderSearchBox(searchBoxRef.current, {
          ...commonOptions,
          query,
          onSearch: (newQuery: string) => setQuery(newQuery),
        });
      }

      if (searchResultsRef.current) {
        renderSearchResults(searchResultsRef.current, {
          ...commonOptions,
          query,
          onSearch: (newQuery: string) => setQuery(newQuery),
        });
      }
    } else if (activeTab === 'chat' && chatRef.current) {
      renderChat(chatRef.current, {
        ...commonOptions,
        agent: 'ADVANCED',
        initialMessage: query ? `Tell me more about: ${query}` : undefined,
      });
    }
  }, [activeTab, query, userAuthToken]);

  return (
    <div className="glean-embedded-hub">
      <div className="tab-navigation">
        <button
          className={activeTab === 'search' ? 'active' : ''}
          onClick={() => setActiveTab('search')}
        >
          Enterprise Search
        </button>
        <button
          className={activeTab === 'chat' ? 'active' : ''}
          onClick={() => setActiveTab('chat')}
        >
          AI Assistant Chat
        </button>
      </div>

      {activeTab === 'search' ? (
        <div className="search-layout">
          <div 
            ref={searchBoxRef} 
            style={{ position: 'relative', display: 'block', minHeight: '60px', zIndex: 10 }} 
          />
          <div 
            ref={searchResultsRef} 
            style={{ position: 'relative', display: 'block', marginTop: '20px' }} 
          />
        </div>
      ) : (
        <div 
          ref={chatRef} 
          style={{ position: 'relative', display: 'block', width: '100%', height: '700px' }} 
        />
      )}
    </div>
  );
};

Authentication: Why Token-Based Handshake Beats Browser SSO

One of the most consequential architectural choices when embedding Glean is identity propagation. The SDK offers two paths:

  1. Browser Single Sign-On (SSO) Flow (Default)
  2. Server-to-Server Token-Based Authentication (authMethod: 'token')

The 365Finds Institutional Judgment: Do Not Rely on SSO Cookies

While browser SSO popup authentication is convenient for early local prototypes, 365Finds strongly advises enterprise engineering teams against relying on browser SSO cookies for production embedded portals.

Modern browsers (Apple Safari with Intelligent Tracking Prevention, Google Chrome with Third-Party Cookie Phaseout, and hardened Firefox containers) aggressively partition or block third-party cookies across differing origins. When your intranet portal at intranet.corp.com embeds iframes or sends requests to acme-be.glean.com, cross-origin cookie restrictions frequently cause:

The Production Solution: Backend-Minted Short-Lived Tokens

The resilient, enterprise-grade architecture delegates authentication to your internal portal's backend service. Because the user is already authenticated against your internal identity provider (Okta, Entra ID, Ping), your backend can securely issue short-lived Glean tokens on their behalf.

sequenceDiagram
    autonumber
    actor Employee as Employee Browser
    participant PortalFE as Intranet Frontend (Web SDK)
    participant PortalBE as Intranet Backend API
    participant GleanAPI as Glean Server API

    Employee->>PortalFE: Open Internal Portal
    PortalFE->>PortalBE: GET /api/glean/token (Session Cookie / Bearer)
    Note over PortalBE: Verify employee identity (e.g. user@corp.com)
    PortalBE->>GleanAPI: POST /rest/api/v1/createauthtoken<br/>Headers: Authorization: Bearer {SERVER_API_KEY}<br/>X-Scio-ActAs: user@corp.com
    GleanAPI-->>PortalBE: 200 OK (short-lived token + expirationTime)
    PortalBE-->>PortalFE: JSON { token, expirationTime }
    PortalFE->>PortalFE: Initialize Web SDK with authMethod: 'token'
    PortalFE->>GleanAPI: Fetch search & chat queries using token
    Note over PortalFE,GleanAPI: Strict ACL enforcement per user@corp.com
    GleanAPI-->>PortalFE: ACL-filtered results & grounded answers

Implementing Token Rotation

In your frontend SDK configuration, pass the token and configure the onAuthTokenRequired asynchronous callback:

import { renderChat } from '@gleanwork/web-sdk';

async function fetchGleanToken(): Promise<string> {
  const response = await fetch('/api/internal/glean-token', {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
  });
  
  if (!response.ok) {
    throw new Error('Failed to retrieve Glean authentication token');
  }

  const data = await response.json();
  return data.token; // Returns the raw JWT string
}

async function mountGlean() {
  const initialToken = await fetchGleanToken();

  renderChat(document.getElementById('chat-container'), {
    backend: 'https://acme-be.glean.com',
    authMethod: 'token',
    authToken: initialToken,
    onAuthTokenRequired: async () => {
      // Called automatically by the SDK before expiration
      return await fetchGleanToken();
    },
  });
}

Security and Document Access Boundary Verification

Because the backend mints the token using the authenticated employee's verified email via X-Scio-ActAs, no document access elevation can occur.

Before moving to production, execute this verification protocol:

  1. Confidential Content Test: Query a restricted document (such as executive payroll or pending acquisition briefs) using an executive account. Verify the result and citations appear.
  2. Access Boundary Check: Repeat the identical query using an engineering or sales intern account. Confirm that neither Search autocomplete, search results, nor generative Chat references or reveals the restricted document.
  3. Link Integrity: Verify that citation URLs in Chat open the underlying system (Google Docs, Jira, Slack) directly into the user's authentic permissions boundary.

By pairing @gleanwork/web-sdk with backend-driven short-lived token auth, enterprise developers eliminate context switching, ensure uninterrupted workflow continuity, and deliver unified AI search with complete security compliance.


References