@healthie/sdk

中文文档
1.5.5发布于 2026/08/17See LICENSE fileTypeScriptESM + CJS近 30 天下载 1.1万

Healthie React SDK

原始使用文档
文档目录12 节
  1. Overview
  2. Before you start
  3. Installation
  4. Basic setup
  5. Server-Side Rendering
  6. Example usage
  7. Components
  8. Conversation List
  9. Chat
  10. Form
  11. Booking & Buying
  12. License

Official React SDK for Healthie API

Overview

Healthie SDK is a React component library built with TypeScript, providing components and hooks to make it easier to work with Healthie's API. Currently supported features include:

  • Chat
  • Forms
  • Booking & Buying

Before you start

This SDK is intended to be used in an existing projects that use Healthie's API. The user authentication flow is not currently part of this SDK and should be implemented separately in your project.

Installation

yarn add @healthie/sdk
yarn add @rails/actioncable graphql-ruby-client
# or
npm i @healthie/sdk
npm i @rails/actioncable graphql-ruby-client

Basic setup

This SDK works on top of the Apollo Client with the assumption that you already have the Apollo Client installed and set up.

Chat and other websocket capabilities are implemented using ActionCable.

The following is a basic configuration of the Apollo Client in order to let the SDK to work properly:

import {
  ApolloProvider,
  HttpLink,
  ApolloClient,
  InMemoryCache,
  split,
} from '@apollo/client'
import { getMainDefinition } from '@apollo/client/utilities'
import * as ActionCable from '@rails/actioncable'
import ActionCableLink from 'graphql-ruby-client/subscriptions/ActionCableLink'

import { HealthieProvider } from '@healthie/sdk'

const httpLink = new HttpLink({
  uri: 'https://api.gethealthie.com/graphql',
  headers: {
    authorization: 'Basic <user_auth_token>',
    authorizationsource: 'API',
  },
})

const cable = ActionCable.createConsumer(
  'wss://ws.gethealthie.com/subscriptions?token=<user_auth_token>'
)
const wsLink = new ActionCableLink({ cable })

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query)
    if (!('operation' in definition)) {
      return false
    }

    const { kind, operation } = definition
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  httpLink
)

const client = new ApolloClient({
  link,
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          // custom configuration if needed
        },
      },
    },
  }),
})

export function App() {
  return (
    <ApolloProvider client={client}>
      <HealthieProvider userId={'<user_id>'}>
        {/* ... your app ... */}
      </HealthieProvider>
    </ApolloProvider>
  )
}

Replace <user_auth_token> with the user's API key obtained during the authentication process and <user_id> with the ID of the currently authenticated user.

Read more about Healthie API authentication here.

Server-Side Rendering

Frameworks such as Next.js, Remix, Astro, and others heavily depend on server-side rendering (SSR). This means they attempt to render the code on the server where browser APIs are not available. Some Healthie SDK components (like Chat) utilize WebSockets through the ActionCable library. If you try to use the above ActionCable code in Next.js or other SSR frameworks, you will likely encounter an error.

To address this issue, follow the steps below. This solution should work for most frameworks. If you prefer a framework-specific solution, such as next/dynamic, consult your framework's documentation.

First, create a useHydrated.ts React hook that will help us determine if the JS has been hydrated already.

import { useEffect, useState } from 'react'

let isHydrating = true

export function useHydrated() {
  let [isHydrated, setIsHydrated] = useState(() => !isHydrating)

  useEffect(function hydrate() {
    isHydrating = false
    setIsHydrated(true)
  }, [])

  return isHydrated
}

Next, define our ClientOnly.tsx component that renders its children only client-side.

import { ReactNode } from 'react'
import { useHydrated } from './useHydrated'

type Props = {
  children(): ReactNode
  fallback?: ReactNode
}

export function ClientOnly({ children, fallback = null }: Props) {
  return useHydrated() ? <>{children()}</> : <>{fallback}</>
}

Then make sure to lazy-load the ApolloProvider and its client definition, so we avoid running the WebSocket code on the server.

Create a file called ApolloForHealthie.tsx which wraps ApolloProvider.

type ProviderProps = {
  children: React.ReactNode
}

// rest of the client initialization code (see the "Basic setup" guide)
// ...
// ...
// ...

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
})

export default function ApolloForHealthie({ children }: ProviderProps) {
  return <ApolloProvider client={client}>{children}</ApolloProvider>
}

Lastly, load the new provider lazily and wrap it with the ClientOnly component:

import { lazy } from 'react'

// it's important to use the React.lazy() instead of regular import
const ApolloForHealthie = lazy(() => import('./ApolloForHealthie'))

function Loading() {
  return (
    <div>
      {/* Ideally this should be the same size as the original component to avoid layout shifts */}
    </div>
  )
}

export default function App() {
  const healthieUserId = '__REPLACE_ME__'

  return (
    <ClientOnlyHydrated fallback={<Loading />}>
      {() => (
        <ApolloForHealthie>
          <HealthieProvider userId={healthieUserId}>
            {/* render Healthie components here */}
          </HealthieProvider>
        </ApolloForHealthie>
      )}
    </ClientOnlyHydrated>
  )
}

The above code will render the ApolloClient and Healthie components client-side, while rendering the custom-defined Loading component on the server. This prevents the use of browser-specific APIs, such as ActionCable, on the server.

Example usage

import { ConversationList, Chat, Form } from '@healthie/sdk'
import '@healthie/sdk/dist/styles/index.css'

// This example assumes you defined the Apollo Client according to the
// instructions described in the "Basic setup" section of the Readme

// const client = ...

export default function App() {
  const healthieUserId = '' // obtain during the auth flow

  return (
    <ApolloProvider client={client}>
      {/* HealthieProvider must be rendered before using any of these components */}
      <HealthieProvider userId={healthieUserId}>
        {/* ... */}
        <div className="conversation-list-container">
          <ConversationList />
        </div>
        <div className="chat-container">
          <Chat />
        </div>

        {/* ... */}
        <div>
          <Form id="1">
        </div>

        {/* ... */}
      </HealthieProvider>
    </ApolloProvider>
  )
}

Components

Make sure to import the stylesheet, usually in the root component of your app:

import '@healthie/sdk/dist/styles/index.css'

Conversation List

This component will fetch the list of active conversations for the currently authenticated user and display it on the screen. If no onConversationClick or activeId props were provided, Healthie SDK will manage the state itself.

:bulb: The default and recommended way to render this component is to leave both props empty and let the HealthieContext manage it's state.

<ConversationList
  onConversationClick={handleOnConversationClick}
  activeId="<conversation_id>"
/>

Props

Prop nameTypeDescription
onConversationClickFunction(optional) Callback to trigger when user clicks on the Conversation item. If not provided, will set the clicked conversaton as active.
activeIdstring / null(optional) ID of the currently selected Conversation. If not provided, the component will set the first conversation on the list as active.

Detailed usage

import { useState } from 'react'

function Example() {
  const [conversationId, setConversationId] = useState(null)

  return (
    <ConversationList
      onConversationClick={(id) => {
        setConversationId(id)
      }}
      activeId={conversationId}
    />
  )
}

Chat

<Chat conversationId="<conversation_id>" />

Warning: If you rendered the ConversationList component without custom props, don't provide the conversationId prop in order to leverage full capabilities of Healthie Context.

Props

Prop nameTypeDescription
conversationIdstring(optional) ID of the Conversation to open. Obtain this information via the GraphQL API or use the Conversation List component. If not provided, will render the active Conversation from HealthieContext

The Chat component takes the full height of the parent container. This enables you to fully control this component's sizing and positioning.

Make sure to correctly specify the height of the container (fixed or fluid), otherwise chat messages may not be visible.

:bulb: Make sure to provide the currently authenticated Healthie User's ID to the HealthieProvider. Otherwise the Chat component will not be able to distinguish incoming and outgoing messages.

Form

The Form component renders a Form Template (known as a Custom Module Form) in the context of the current user. It will automatically prefill the form with the user's data (if applicable) and will submit the form on behalf of the user.

<Form id="<custom_module_form_id>" />

Props

Prop nameTypeDescription
idstringID of the Form Template (Custom Module Form) to render. You can retrieve a Form Template ID by, for example, querying Form Completion Requests for the current user.
submitButtonTextstring?(optional) Text to display on the submit button. Defaults to "Submit".
onSubmit(values: FormFields) => Promise<boolean | void> | boolean | void(optional) Callback to trigger when the form is submitted. The callback will receive form data to submit as an argument. You can optionally return false from the callback to prevent the form from submitting. In this case, you will need to manually submit the form by using the createFormAnswerGroup mutation.
onQueryStateChange({ loading, error, data }: QueryState) => void(optional) Callback to receive Apollo Query state change updates when loading the form.
onMutationStateChange({ loading, error, data }: MutationState) => void(optional) Callback to receive Apollo Mutation state change updates when submitting the form.

Detailed usage

import { useState } from 'react'

function Example() {
  const customModuleFormId = '' // obtain via the GraphQL API

  return (
    <Form
      id={customModuleFormId}
      onSubmit={(data) => {
        // do something with the data
        // return false to prevent the form from submitting
      }}
      onQueryStateChange={({ loading, error, data }) => {
        // access Apollo query status
      }}
      onMutationStateChange={({ loading, error, data }) => {
        // access Apollo mutation statu
      }}
      submitButtonText="Submit form"
    />
  )
}

Styling

Currently the Form component supports custom styling only via overriding the default CSS classes. All fields have generic class names like input-wrapper or form-field-container. Each field type has its own class name, so you can target specific fields.

Additionally, all Healthie SDK components are wrapped in a healthie-container class. To override the default styles, you can leverage the CSS specificity and override the default styles by using the healthie-container class as a parent selector.

For example:

.healthie-container .input-text {
  /* your styles */
}

This way you are not required to use !important to override the default styles, while still being able to style form components according to your needs.

Document and Folder Fields

The Form component supports rendering Document and Folder fields. These fields open a link to the corresponding document or folder in the Healthie Web app. By default, the link will open the app via generic domain (https://secure.gethealthie.com). If you are using a branded Healthie URL, you can pass the brandedUrl prop to the Healthie Context via the HealthieProvider component.

<HealthieProvider userId="<user_id>" brandedUrl="https://myapp.example.com">
  <Form id="<form_id>" />
</HealthieProvider>

This will open Documents or Folders via the branded URL like this: https://myapp.example.com/documents/{id}/download.

Booking & Buying

The Booking components renders the widget for Calendar and Packages, which enables clients to book appointments, browse services, and purchase packages.

<Booking queryString={queryString} />

Appointment calendar links are generated with the Healthie production URL by default. If you are using a branded Healthie Backend URL or Healthie staging environment, you can pass the brandedBackendUrl prop to the Healthie Context via the HealthieProvider component.

<HealthieProvider
  userId="<user_id>"
  brandedBackendUrl="https://staging-api.gethealthie.com"
>
  <Booking queryString={queryString} />
</HealthieProvider>

Props

Prop nameTypeDescription
queryStringstringThe query string used to render the booking embed widget. This is obtained via the Sharing Link generated in the Healthie Dashboard. For example: ?dietitian_id=1&require_offering=true&offering_id=24&hide_package_images=false.

License

This SDK is licensed under The Healthie React SDK license. See the LICENSE file for more details.

版本与发布记录

@healthie/sdk 共发布 55 个版本,首次发布于 2023/04/05;过去 12 个月发布了 7 个版本。

版本发布日期距今
1.5.5latest2026/08/173 个月前
1.5.5-rc.0legacy-next2026/08/173 个月前
1.5.42026/08/033 个月前
1.5.4-rc.0next2026/07/223 个月前
1.5.32026/05/136 个月前
1.5.3-rc.02026/05/136 个月前

关于 @healthie/sdk 的常见问题

@healthie/sdk 是什么?

Healthie React SDK

如何安装 @healthie/sdk?

在项目目录运行 npm install @healthie/sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.2.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@healthie/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@healthie/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@healthie/sdk 可以商用吗?

@healthie/sdk 使用 See LICENSE file 许可。声明的许可为 See LICENSE file,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@healthie/sdk 的下载量有多少?

根据 npm 官方下载统计,@healthie/sdk 在 2026/10/18 – 2026/11/16 这 30 天内被下载 10,892 次,日均约 363 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@healthie/sdk 还在维护吗?

最新版本 1.5.5 发布于 2026/08/17(3 个月前);至今共发布 55 个版本,其中过去 12 个月发布了 7 个;首次发布于 2023/04/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。