npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cantab/pathway-react

v1.0.0

Published

React SDK for CANTAB Pathway cognitive assessments

Readme

CANTAB Pathway React SDK

A React component that renders CANTAB Pathway cognitive assessments in an iframe and surfaces lifecycle events to your application. Create an assessment with the CANTAB Pathway REST API, then pass the resulting web_assessment_url to the <CantabPathwayView> component.

Regional deployments: Each API host serves assessments on exactly one assessment host. Use the API in your region; the web_assessment_url you receive will always point at the matching assessment origin.

| Region | API base (OpenAPI docs) | Assessment host (web_assessment_url origin) | | --- | --- | --- | | US | us.cantabpathway.com | https://app.cantab.com | | EU | eu.cantabpathway.com | https://eu.cantab.com |

Do not mix regions (for example, creating an assessment via the US API and embedding a URL from the EU assessment host).

Compatibility

| Category | Support | | --- | --- | | React | 18 and above — peer dependencies react and react-dom >=18.0.0 (see package.json). | | Node.js (tooling, tests, SSR pipelines) | 18 and aboveengines.node in package.json. | | TypeScript | Optional but supported. The published package includes .d.ts declaration files; import CantabPathwayView, CantabPathwayViewProps, and the CantabPathway* event types from @cantab/pathway-react. Optional props such as showInstructions are declared on CantabPathwayViewProps. | | Browsers | Current Chrome, Firefox, Safari, and Edge; last two major versions of each. Requires standard APIs used by the SDK: fetch, URL, AbortController, and postMessage (typical evergreen desktop and mobile browsers). |

SSR and static rendering

The SDK uses typeof window === 'undefined' guards around browser-only work. fetch preflight validation and iframe embedding run only on the client after the component mounts in the browser. Server-side rendering does not run validation or load the assessment; full behavior applies after hydration (or if the component is mounted only on the client). Frameworks with SSR often use client-only boundaries (for example, dynamic import with ssr: false in Next.js) when the subtree should never run on the server.

Getting started

1. Install the package

npm install @cantab/pathway-react

2. Create an assessment via the API

Use the CANTAB Pathway REST API for your region (see the table above) to create a subject assessment. The response includes a web_assessment_url field — this is the URL you pass to the component. Its origin will be https://app.cantab.com (US) or https://eu.cantab.com (EU), matching the API you used.

3. Render the component

import { CantabPathwayView } from "@cantab/pathway-react";

function Assessment({ url }: { url: string }) {
  return (
    <div style={{ width: "100vw", height: "100vh" }}>
      <CantabPathwayView
        assessmentURL={url}
        onEvent={(event) => {
          switch (event.type) {
            case "ready":
              console.log("Assessment loaded");
              break;
            case "done":
              console.log(
                "First completion recorded — fast-poll handshake finished; results uploading",
              );
              break;
            case "uploaded":
              console.log("Results uploaded — safe to navigate away");
              break;
            case "error":
              console.error("Assessment error:", event.message);
              break;
          }
        }}
      />
    </div>
  );
}

4. Wait for uploaded, then fetch results

Do not unmount the component until onEvent receives uploaded. You can then use the API to retrieve the assessment results.

Instruction variants (CANTAB One)

For CANTAB One, Pathway can expose two presentation variants: with task instructions and without (DST only). Which combinations are allowed is fixed when the assessment is created on the API (variant.instructions_mode: required, optional, or none) and depends on your project’s Connect configuration supporting instruction variants.

In the embedded UI, set showInstructions (default true) to match what you want for this session: true selects the instructions variant, false the no-instructions variant. For non-CANTAB One assessments or projects without variants, Pathway ignores the flag; behavior is unchanged.

Use them properly: pick instructions_mode at create time so it matches your study rules, then pass showInstructions consistently. If you create an assessment with required instructions, do not open it with showInstructions={false} — validation will fail (see below).

Example usage

import { useState } from "react";
import { CantabPathwayView } from "@cantab/pathway-react";

type Screen = "home" | "assessing" | "done" | "error";

function App() {
  const [screen, setScreen] = useState<Screen>("home");
  const [assessmentURL, setAssessmentURL] = useState("");
  const [error, setError] = useState<string | null>(null);

  const startAssessment = async () => {
    // Create an assessment via your API and get the web_assessment_url
    const url = await createAssessmentViaAPI();
    setAssessmentURL(url);
    setScreen("assessing");
  };

  if (screen === "assessing") {
    return (
      <div style={{ width: "100vw", height: "100vh" }}>
        <CantabPathwayView
          assessmentURL={assessmentURL}
          onEvent={(event) => {
            switch (event.type) {
              case "uploaded":
                setScreen("done");
                break;
              case "error":
                setError(event.message);
                setScreen("error");
                break;
            }
          }}
        />
      </div>
    );
  }

  if (screen === "done") {
    return <div>Assessment complete! Fetching results...</div>;
  }

  if (screen === "error") {
    return <div>Error: {error ?? "Unknown error"}</div>;
  }

  return <button onClick={startAssessment}>Start Assessment</button>;
}

Props reference

| Prop | Type | Default | Description | | --- | --- | --- | --- | | assessmentURL | string | (required) | The assessment URL from the CANTAB Pathway API (web_assessment_url field). Origin is https://app.cantab.com or https://eu.cantab.com depending on region. | | showInstructions | boolean | true | CANTAB One only: true / false selects the instructions or no-instructions variant via the wrapped URL. Must be compatible with how the assessment was created. | | onEvent | (event: CantabPathwayEvent) => void | — | Lifecycle callback. Event union types: ready, done, uploaded, and error (with message). | | iframeAllow | string | "camera; microphone; fullscreen" | The allow attribute for the iframe. Some assessments require camera/microphone access. | | strictOrigin | boolean | false | When true, only exact origins are accepted (assessmentURL origin and trustedOrigins). | | trustedOrigins | string[] | [] | Additional exact origins to trust for postMessage events. With strictOrigin, the assessment origin is typically https://app.cantab.com or https://eu.cantab.com. | | sandbox | string | — | Optional sandbox attribute for the iframe. Set carefully to avoid blocking required assessment features. | | referrerPolicy | React.HTMLAttributeReferrerPolicy | "strict-origin-when-cross-origin" | Referrer policy applied to the iframe request. | | style | React.CSSProperties | — | Inline styles applied to the outermost container <div>. | | className | string | — | CSS class name applied to the outermost container <div>. |

Event lifecycle

First completion and fast polling

When the iframe reports the first successful run completion, the SDK sends a fast polling signal: it POSTs an empty body to assessmentURL (the same wrapped URL from the API). That request retries up to three times, with 200 ms between attempts, if the response is not OK or the network fails.

{ type: "done" } is emitted only after that POST attempt loop finishes (whether or not any attempt returned HTTP 2xx). Further successful completion signals emit { type: "uploaded" } as before.

There is no separate onEvent for POST success or failure. Do not infer server-side acceptance of the fast polling signal from the event types alone.

Event order

After preflight validation succeeds, the component emits onEvent in this order for a successful assessment:

  1. { type: "ready" } — The assessment page has loaded in the iframe and is ready for interaction.
  2. { type: "done" } — The first completion was reported by the iframe, and the SDK has finished its fast-poll POST attempts to assessmentURL. Result upload may still be in progress. Do not unmount the component.
  3. { type: "uploaded" } — Results have been successfully uploaded. It is now safe to unmount and navigate away.

Errors emit { type: "error", message }. The message field may contain a human-readable description, or null (e.g. some iframe-reported errors).

Preflight validation

Before the iframe loads, the SDK requests the same wrapped URL with Accept: application/json to validate parameters (including showInstructions). If that check fails, you get { type: "error", message } and the iframe is never loaded — you will not see ready for that URL.

Typical cases:

  • Configuration mismatch (e.g. showInstructions incompatible with the assessment’s instructions_mode): message is usually Pathway’s error_reason — show it to the user and fix props or create a new assessment.
  • Terminal assessment (already completed, expired, failed): JSON error instead of loading the assessment page.
  • Network / non-JSON response (proxy errors, blocked fetch, etc.): generic validation failure or the thrown error message.

Treat these like any other error event: stop relying on the iframe, surface event.message, and retry only after correcting the URL, props, or auth — or after creating a fresh assessment.

Guidelines

  • Always keep the component mounted until onEvent emits uploaded. Unmounting early can interrupt result upload.
  • The component renders a branded splash screen for a minimum of 3 seconds while the assessment loads.
  • If the assessmentURL prop changes, all internal state resets and the splash screen is shown again.

Content Security Policy

These rules apply to the parent page that embeds CantabPathwayView, not to the assessment iframe’s own policy.

Framing the assessment

Assessments are loaded in the iframe from one host only, depending on which regional API created the assessment:

  • US: https://app.cantab.com
  • EU: https://eu.cantab.com

Allow frame-src for the assessment origin you use. If your app can run against either region, include both origins in frame-src.

Network access from the parent page

The SDK uses fetch() from the parent document to the wrapped assessment URL: a GET (validation, Accept: application/json) before load and **POST**s (fast polling after completion). If your CSP includes connect-src, it must allow that assessment URL origin — the same https://app.cantab.com or https://eu.cantab.com origin as in the table above. A restrictive value such as connect-src 'self' will block these requests unless you add that origin.

Your app may also need connect-src entries for your own API and asset hosts; add those alongside the assessment origin.

Inline styles

The SDK injects inline style="" attributes and embedded <style> tags. The page hosting CantabPathwayView must permit inline styles.

At minimum, your CSP needs to allow framing, connectivity to the assessment origin, and inline styles. Examples for a single region (add your own API and asset origins to connect-src as needed):

US only

Content-Security-Policy: frame-src https://app.cantab.com; connect-src 'self' https://app.cantab.com; style-src 'self' 'unsafe-inline';

EU only

Content-Security-Policy: frame-src https://eu.cantab.com; connect-src 'self' https://eu.cantab.com; style-src 'self' 'unsafe-inline';

US and EU (e.g. one build that can target either API)

Content-Security-Policy: frame-src https://app.cantab.com https://eu.cantab.com; connect-src 'self' https://app.cantab.com https://eu.cantab.com; style-src 'self' 'unsafe-inline';

or (Level 3 style directives)

Content-Security-Policy: frame-src https://app.cantab.com https://eu.cantab.com; connect-src 'self' https://app.cantab.com https://eu.cantab.com; style-src 'self'; style-src-elem 'self' 'unsafe-inline'; style-src-attr 'unsafe-inline';

If you must allow additional hosts (for example legacy or partner assessment domains), extend frame-src and connect-src accordingly. The important part is that the assessment URL origin in assessmentURL is allowed for framing and for fetch.

If your policy does not allow inline styles (for example, if 'unsafe-inline' is disallowed), the SDK's default rendering will be blocked by the browser and the UI may appear unstyled or broken.

Examples

See the examples/assess-yourself directory for a complete example app built with Vite + React + TypeScript.

License

MIT — see LICENSE.md.