Spruce Embedded Secure Messaging Integration Guide

What Spruce Embedded Secure Messaging is and how to embed Spruce secure messaging for a patient inside your own application

📘

Spruce Embedded Secure Messaging is a paid add-on

Spruce Embedded Secure Messaging lets you offer Spruce secure messaging to patients inside your own application. It is a paid add-on and is not included with standard Public API access. Until your organization has purchased Spruce Embedded Secure Messaging and Spruce has enabled it, the endpoints in this guide will refuse requests. Spruce Embedded Secure Messaging is designed and priced for enterprise organizations that typically have Spruce seat commitments of 50–100+ providers and participate in our account management program. To learn more, contact Spruce Support at [email protected].

Spruce Embedded Secure Messaging Integration Guide

Spruce Embedded Secure Messaging lets an application embed secure messaging with a Spruce practice on behalf of one patient. A practice that already runs its own patient-facing product, such as a member portal or a mobile app, can show its patients their Spruce conversations with the practice inside that product, let them read and send messages and attachments, and keep the practice's own team working in Spruce as usual.

An embedded patient is a patient contact in the practice's organization that has been embedded through the Public API. Embedded patients never have a Spruce account of their own and never log in to Spruce; the embedding application is their only way in.

Here's how to build that integration. At a high level, there are four pieces:

  1. Create and embed the patient from your backend using the Public API. Embedding creates the patient's Spruce identity, their secure conversation with your practice, and the first patient token.
  2. Act as the patient on the embed host from your application, presenting the patient token to list conversations, read and post messages, and upload attachments.
  3. Keep the token fresh. Store the rotated token the embed host hands back, and mint again from your backend when a request is refused with 401.
  4. Relay notifications by subscribing to the embedded patient webhook events on your existing webhook endpoint and surfacing them in your application.

For a working reference, see the Spruce Embedded Secure Messaging sample application, which implements this flow end to end.

How it fits with the Public API

The Public API and the Spruce Embedded Secure Messaging API are two halves of one integration. The practice's side stays on the Public API. The patient's side runs on a separate host, the embed host, where every request acts as a single patient.

Public APISpruce Embedded Secure Messaging API
Acts asThe practiceOne patient
Hosthttps://api.sprucehealth.com/v1https://embed.sprucehealth.com/v1
CredentialOrganization access ID and secret keyPatient token minted by the practice
Where the credential livesYour backend onlyThe patient's device or session in your application
Used forCreating contacts, minting patient tokens, deletion, receiving webhooksEvery request made as that patient
Documented inSpruce Health APISpruce Embedded Secure Messaging API

Never send your organization's credential to a browser or a mobile app. Mint patient tokens from your backend and hand only the token, its device id, and the patient organization id to the application.

Step 1: Create the patient contact

Create a Spruce contact for the patient with POST /v1/contacts if one does not already exist, the same way as in the Integration Guide. The contact must be a patient and must not have a Spruce account or a pending Spruce invite; a contact who already uses the Spruce patient app cannot be embedded.

Persist the Spruce contact id (entity_…) against the patient's record in your system, or link the two with an integration link.

Spruce does not verify an embedded patient's identity. Because your application is the patient's only way in, it is responsible for confirming who the patient is before embedding a contact or minting a token, and for making sure the signed-in person matches the Spruce contact you embed. A token minted for the wrong contact gives its holder that contact's conversations with your practice. Embed, or mint a token for, only a contact you have matched to a patient whose identity your application has verified. Match on a stable identifier you control, such as your own patient id linked through an integration link, rather than on name or date of birth alone.

Step 2: Embed the contact and mint the first token

Embed the contact with POST /v1/contacts/{contactId}/embed from your backend. The call requires an S-Device-ID header naming the device the token is for, and a body naming the internal endpoint (Spruce Link) that will own the secure conversation with the patient. That endpoint's default teammates and tags apply to the conversation.

POST /v1/contacts/entity_2N6DEEC93AG00/embed
Authorization: Bearer <base64(access_id:secret_key)>
S-Device-ID: 7ZcG3SOQ_ihHW0KAw2b2Hw
Content-Type: application/json

{
  "internalEndpointId": "organizationCode_2ER39ETHBQ800"
}

Internal endpoint ids come from GET /v1/internalendpoints.

The response carries the contact and an embed object:

{
  "contact": { "...": "the contact, as returned by GET /v1/contacts/{contactId}" },
  "embed": {
    "object": "embed",
    "patientOrganizationId": "entity_2N6DEEC93AG00",
    "conversationId": "t_2MN0O40VN2000",
    "token": "YWNjb3VudF8yTjZERUVDOTNBRzAwOnRva2Vu",
    "deviceId": "7ZcG3SOQ_ihHW0KAw2b2Hw",
    "tokenExpiresAt": "2026-11-09T15:04:05Z"
  }
}

Store three things:

  • patientOrganizationId on the patient's record in your system. It identifies the patient on the embed host and in every webhook event about them.
  • token and deviceId together, with the device or session they were minted for. The token is returned only by this response.
  • conversationId if your application opens the practice conversation directly rather than listing conversations first.

Choosing a device id

The device id is your identifier for the place the token will be used: a browser session, an installed app on one phone, or similar. It may be up to 64 characters. Reuse the same id when you mint again for the same device so the new token replaces that device's old one instead of counting as another device. A patient may hold live tokens on up to three devices; minting for a fourth revokes the oldest.

Minting again

Call the same endpoint again whenever the application needs a fresh token for a patient who is already embedded: after a 401 from the embed host, on a new device, or after the token has expired through inactivity. The call is safe to repeat and answers with a new token each time. It is refused with 409 while a deletion of the patient is pending (cancel the deletion first, Step 6) and with 404 when Spruce Embedded Secure Messaging is not enabled for the organization.

Step 3: Act as the patient on the embed host

Every embed host request carries the patient token as a bearer token and the device id as S-Device-ID:

GET /v1/patient
Authorization: Bearer YWNjb3VudF8yTjZERUVDOTNBRzAwOnRva2Vu
S-Device-ID: 7ZcG3SOQ_ihHW0KAw2b2Hw

The embed host echoes the token's device id back in an s-device-id response header on every authenticated response, so an application that lost the id can recover it.

Show the patient and their conversations

unreadConversationCount is the number of conversations with messages the patient has not read, not the number of unread messages. Most patients have one conversation with the practice, so the value is usually 0 or 1: it tells the application whether there is something new to open, not how much. Show it the way a badge on an app icon works, and compute a per-message count from the items list if your application needs one.

Read messages

GET /v1/conversations/{conversationId}/items lists messages, system messages and change events, oldest first by default, in pages of 20 (up to 200). Pass the returned paginationToken to fetch the next page while hasMore is true.

Each message item carries message.text, message.attachments, authorId, and authorDisplayName. Attachments carry a short-lived signed url and an urlExpiresAt; fetch the attachment when the patient opens it rather than caching the URL. A deleted message stays in the list with deleted set and an empty message, and an event item of type messageDeleted or messageRestored is appended when the change happens.

A systemMessage item has the same fields as a message, but nobody sent it: Spruce wrote its text to describe something that happened in the conversation, such as "Dr. So and So deleted a message." or a changed subject, and its author is whoever caused it. Render only message items as chat messages. The Spruce app shows a systemMessage as a centered status line between the messages, and shows nothing for an event item, which exists so your application can update the message it names. Doing the same shows a deleted message as its placeholder plus one status line.

To poll for new items, pass the newest item's createdAt as startFrom. Items created at or after that time are returned, so an item already seen can appear again and should be matched by id. startFrom cannot be combined with paginationToken.

Show the latest messages and load history on scroll

A chat view usually opens on the newest messages and loads older ones as the patient scrolls up. Page backward with order=newest_first:

  1. Open the thread: request GET /v1/conversations/{conversationId}/items?order=newest_first&pageSize=50. The page holds the 50 newest items, newest first.
  2. Scroll up: while hasMore is true, send the returned paginationToken with order=newest_first again. Each page holds the next older items, newest first. hasMore false means the start of the conversation has been reached.
  3. Render: reverse each page before prepending it if the thread shows the oldest item at the top.
  4. Stay current: request items with startFrom set to the newest item's createdAt and append what comes back, matching by id. Do this when an event names the conversation and on a slow fallback poll, as described in Stay current with events, and poll only as a fallback. These requests use the default order and are independent of the backward pages.

Send order=newest_first on every backward request; a token from a newest-first page is a position in the conversation, and the order sent with it decides which side of that position comes back. startFrom is a lower bound only, and there is no parameter for "items before this time", so history is always reached by paging rather than by timestamp.

Caching and keeping a thread current

It is fine to keep a local copy of the items list so the thread opens instantly, but treat it as a cache, not a record. Three things can change after an item is first fetched:

  • Messages are deleted and restored. Messages are never edited, but the practice can delete a message and later restore it. A deleted message keeps its id and position with deleted set, deletedAt, and an empty message, so a cached copy of the original text and attachments is now wrong. Replace the cached item by id whenever the item is returned again, and when embeddedConversationItem.deleted or embeddedConversationItem.restored arrives (Step 5), either apply the event's data.object to the cache by id or refetch the conversation. Polling with startFrom does not surface these changes, because the item's createdAt is unchanged; modifiedAt moves instead. The messageDeleted and messageRestored event items appended to the list carry the affected itemId, so a thread that only appends new items can still mark the message they refer to. Each change also appends a systemMessage item with the line to show the patient, such as "Dr. So and So deleted a message.", so the event item itself needs no text of its own on screen.
  • Names change. authorDisplayName on each item, the title of a conversation, and each participant's displayName are resolved when the request is served, so they reflect a teammate's current name or the practice's current name. A cached value goes stale when a teammate is renamed or the practice changes its name. Key your own data on authorId and the conversation id, keep display names as cached presentation only, and refresh them when the thread is reopened or the items are refetched.
  • Attachment URLs expire. url on an attachment is signed and stops working at urlExpiresAt, 15 minutes after the item was fetched. Never cache the URL; refetch the item to get a fresh one when the patient opens the attachment.

A simple rule that covers all three: refetch the pages the thread shows when the patient opens it, whether that is the whole conversation or the newest page with order=newest_first, and use startFrom polling and the webhook events only while it is on screen.

Stay current with events, and poll only as a fallback

The webhook events in Step 5 are the signal that something changed. Relay them from your backend to the patient's open sessions, over a channel such as server-sent events, a WebSocket, or your own push notifications, and fetch only what the event names. On embeddedPatientNotification.created, request the conversation's new items with startFrom and refresh the conversation list. On embeddedConversationItem.deleted or embeddedConversationItem.restored, apply the item to the cache by id.

Keep a slow poll of the open thread and the conversation list as a fallback, because some changes produce no event. A message posted without notifying produces no embeddedPatientNotification.created event. No event announces a conversation the practice starts, or a conversation the patient read on another device. Events relayed while the application was offline or its connection was down are lost. Poll on this schedule:

  • About once a minute while the application is receiving relayed events, and no more often than every 30 seconds while it is not.
  • Only while messaging is on screen. Do not poll while the application is in the background or the browser tab is hidden.
  • At once when the application returns to the foreground or reconnects to your event channel, since events may have been missed.
  • Less often after failed requests and after long periods with no change, backing off to a few minutes.

The rate limits apply to each patient across all of their devices and open tabs. An application that polls every few seconds can exceed them when a patient has messaging open in more than one place. Read the unread badge from responses already fetched where you can: unreadConversationCount is the number of conversations in GET /v1/conversations with unread set, and POST /v1/conversations/{conversationId}/read returns the conversation with its unread updated. The sample application follows this schedule.

Post messages and attachments

Upload any attachment first with POST /v1/media as a multipart/form-data request whose media field carries the file, with Content-Type and Content-Disposition set so the practice sees the right name and type. The returned media id belongs to the patient; nobody else can attach it.

Then post with POST /v1/conversations/{conversationId}/messages. At least one of text or attachments is required, and up to five attachments may be sent.

{
  "text": "Thanks, I have a question about the dosage.",
  "attachments": [{ "mediaId": "d7b25969-86ec-7e37-3776-3577-c0637a0c" }]
}

Send an S-Idempotency-Key header, such as a UUID generated when the patient taps send, so a retry after a lost response does not post twice. Every POST on the embed host accepts the header; a second request with the same key, path, and method within a day is refused with 422. The response is the posted item, in the same shape as the items list, so it can be appended to the thread immediately.

Mark as read

POST /v1/conversations/{conversationId}/read marks every message in the conversation as read by the patient and returns the conversation. Call it when the patient opens the conversation so unread and unreadConversationCount stay accurate.

Update the patient's details

PATCH /v1/patient updates the patient's name on the patient's own Spruce record. Absent fields keep their value. The patient's date of birth, email address, and phone number are not part of the embedded patient, so they are neither returned by GET /v1/patient nor changed here: manage them in your own application and on the practice's contact record. This does not change the practice's contact record; keep that in sync through the Public API as in the Integration Guide.

After each successful update, the practice sees an internal note in its copy of each one-to-one conversation with the patient, listing the patient's current name and asking staff to update their own records. The note is not sent to the patient and does not appear in the patient's items list. It is posted for every successful request, including one that leaves every value as it was, so send the request only when the patient has changed something.

Step 4: Keep the token fresh

Patient tokens expire four days after they are minted. A request made during the last day of that window is answered with a new token in the s-embed-token response header. Read the header on every response and, when it is present, store the new value in place of the token you sent. The old token stops working.

When the embed host answers 401, the token is missing, expired, revoked, or no longer belongs to an embedded patient. Have your backend mint again (Step 2) with the same device id and resume with the new token. The practice API keeps its own 403 for bad organization credentials; 401 on the embed host always means "mint again".

Sign the patient out

When the patient signs out of your application, call POST /v1/patient/logout with the token before you discard it. The embed host revokes the token, including any earlier value that was still accepted after a rotation, so a copy left in a browser or on a device stops working at once instead of living until it expires. Only the device the token was issued for is signed out; the patient's sessions on other devices continue. A 401 here means the token was already dead, and there is nothing more to do. Mint again when the patient signs back in.

In a browser, the embed host exposes s-embed-token, s-device-id, and s-request-id through Access-Control-Expose-Headers, so a page can read them from a fetch response.

Step 5: Relay notifications through webhooks

An embedded patient has no Spruce app, so Spruce does not push to them. Instead, your organization's webhook endpoints receive events about embedded patients, and your application notifies the patient however you would like to on your end: a push notification from your own app, an email, an in-app badge, or nothing at all. The events use the same envelope, signature, and delivery rules as every other Spruce webhook event.

EventWhendata.object
embeddedPatientNotification.createdA message was posted to the patient that they would have been notified aboutAn embeddedPatientNotification: patientOrganizationId, conversationId, itemId, and the notification text as the patient would have seen it on a push notification
embeddedConversationItem.deletedA message on the patient's conversation was deletedThe embeddedConversationItem, exactly as the embed host returns it, with deleted set
embeddedConversationItem.restoredA deleted message was restoredThe embeddedConversationItem

Every embedded event carries patientOrganizationId, the value returned when the contact was embedded. Resolve it to your patient record and then to the devices or sessions you notify. Conversation and item ids in these events are the patient-side ids used on the embed host, so they can be passed straight into a deep link to the conversation in your application. A message posted without notifying produces no notification event.

Example embeddedPatientNotification.created event

{
    "eventTime": "2026-09-15T09:12:01Z",
    "object": "event",
    "type": "embeddedPatientNotification.created",
    "data": {
        "object": {
            "object": "embeddedPatientNotification",
            "patientOrganizationId": "entity_2N6DEEC93AG00",
            "conversationId": "t_2MN0O40VN2000",
            "itemId": "ti_2MN0O5A2Q0800",
            "text": "New message"
        }
    }
}

text is the notification as the patient would have seen it on a push notification. For a patient it is the generic "New message" and never contains the message itself or the author's name, so it is safe to show on a lock screen. Use conversationId and itemId to deep link, and fetch the item from the embed host to show the message.

Example embeddedConversationItem.deleted event

{
    "eventTime": "2026-09-15T10:02:00Z",
    "object": "event",
    "type": "embeddedConversationItem.deleted",
    "data": {
        "object": {
            "object": "embeddedConversationItem",
            "id": "ti_2MN0O5A2Q0800",
            "conversationId": "t_2MN0O40VN2000",
            "patientOrganizationId": "entity_2N6DEEC93AG00",
            "type": "message",
            "authorId": "entity_2N6DFKJQJAG00",
            "authorDisplayName": "Dr. So and So",
            "createdAt": "2026-09-15T09:12:00Z",
            "modifiedAt": "2026-09-15T10:02:00Z",
            "deleted": true,
            "deletedAt": "2026-09-15T10:02:00Z",
            "message": { "text": "", "attachments": [] }
        }
    }
}

The embeddedConversationItem.restored event has the same shape with deleted false, no deletedAt, and the message's text and attachments back in message. Both carry the item exactly as GET /v1/conversations/{conversationId}/items returns it, so the object can be written straight into a cached thread by id.

Step 6: Deletion

Deletion is a call from your backend with the practice's Public API credential, like minting. If a patient leaves your application, POST /v1/contacts/{contactId}/embed/delete schedules the patient's Spruce data for deletion after a 30 day grace period and revokes every token for the patient. The practice's conversation with the patient is marked inactive until the deletion is cancelled or completes. The response carries scheduledDeletionTime; there is no cancellation token to store. Calling it again while the deletion is pending answers the same time.

POST /v1/contacts/{contactId}/embed/delete/cancel reverses the deletion inside the grace period. It succeeds and changes nothing when no deletion is pending, so it can be retried after a lost response. Once the deletion is running it answers 409. After a cancellation, mint again to resume messaging.

A patient token cannot schedule or cancel a deletion. To let a patient delete their account from inside your application, have the application ask your backend, and have your backend make the call.

Rate limits and errors

Embed host requests are rate limited per patient rather than per organization, so the per-minute limits are lower than the Public API's: each patient may make 120 GET requests and 30 other requests per minute. The daily limit is the Public API's, applied per patient: 5,000 non-GET requests per 24 hours. GET requests have no daily limit. A request over a limit is refused with 429. Responses carry the same s-ratelimit-* headers as the Public API, described in the rate limiting section of the Public API overview.

Errors on the embed host follow the same structure as the Public API.

{
    "statusCode": 401,
    "type": "unauthorized",
    "message": "Unauthorized."
}

Recommended End-to-End Architecture

The sample application follows this architecture and is a good starting point for your own integration.

  1. Bootstrap: when a patient first opens messaging in your application, your backend creates the Spruce contact if needed (POST /v1/contacts), embeds it with POST /v1/contacts/{id}/embed using a device id for the patient's current session, and persists patientOrganizationId. It returns the token and device id to the application and nothing else.
  2. In the application: present the token and device id on every embed host request. Load GET /v1/patient for the unread badge, GET /v1/conversations for the list, and GET /v1/conversations/{id}/items for the thread. Request new items with startFrom when a relayed event names the open thread, poll slowly as a fallback while it is on screen, and refetch the thread when it is reopened so deletions, restorations, and renamed teammates are picked up. Post with an idempotency key, upload media before attaching it, and mark the conversation read when it is opened. Store any s-embed-token the host returns; on 401, ask your backend to mint again.
  3. Notifications: register one webhook endpoint per environment, or reuse the one you have. On embeddedPatientNotification.created, verify the signature, ack with 2XX, resolve patientOrganizationId to the patient, and send your own notification with a deep link to conversationId. Relay the event to the patient's open sessions too, so an open thread or conversation list refreshes without waiting for its fallback poll. On embeddedConversationItem.deleted and .restored, update the cached item by id or refresh any open thread.
  4. Practice side, unchanged: the practice's team reads and replies in Spruce. Demographic changes continue to flow through the Public API as in the Integration Guide; the embed host's PATCH /v1/patient updates only the patient's own record.
  5. Offboarding: schedule deletion from your backend with the practice credential, and cancel the same way inside the grace period if the patient returns.

Did this page help you?