# Quickstart — Five SDK

Run the immersive VR template in React, Vue or native TypeScript, then connect Team data when you need it.

Canonical: https://developer.realsee.ai/docs/five-sdk/quickstart
Source: https://developer.realsee.ai/docs/five-sdk/quickstart.md
Language: en

[Download examples](https://developer.realsee.ai/starters/immersive-vr/starter.zip)

## Run the complete starter

Use the current **2.0.1** immersive template. Choose React, Vue or native TypeScript inside this one project.

- [Agent instructions](https://developer.realsee.ai/starters/immersive-vr/agent.md)
- [Release manifest and SHA-256](https://developer.realsee.ai/starters/immersive-vr/manifest.json)
- [Complete project ZIP](https://developer.realsee.ai/starters/immersive-vr/starter.zip)
- [Public Demo guide](https://developer.realsee.ai/starters/immersive-vr/demo.md)
- [Team integration guide](https://developer.realsee.ai/starters/immersive-vr/team.md)

Use Node 24. Read the manifest, download its archive, and verify the SHA-256 before extracting into a new directory. Preserve LICENSE, the lockfile and pinned dependencies. From `realsee-immersive-vr`, run:

```bash
npm run setup -- --framework react
npm ci
npm run check
npm run build
npm run dev
```

Open the actual local URL printed by the server. Verify that the public scene reaches Ready. Switch the viewer from Panorama to Top view and back, check fullscreen. No account or credentials are required for Public Demo. Report browser checks only when actually performed.

For Team data, run `npm run configure -- --device`. The helper tries to open the default browser. Show the verification URL and eight-character code for manual opening, then keep the command running while the user signs in, selects their Team and app, and authorizes. Do not approve for the user. The helper writes the local `.env` and preserves existing credentials. If authorization is unavailable, create `.env` from `.env.example` only if absent and let the user fill AK, SK and Team source locally. Never paste secrets into chat or expose them to browser code. Restart the server and open the local viewer with `?scene-picker=1`. Ask the user to search, preview and confirm a Team scene there. Wait for the selected VR to reach Ready. Check token exchange, the authorized VR list, and selected Work separately. Public Demo success does not prove Team API access; an empty authorized list is a distinct successful read.


Run a complete React + TypeScript project with a real public scene. The starter pins **Five SDK 6.9.2**, **Three.js 0.117.1**, **React 18.3.1**, and its dependency lockfile.

## Choose how to start

Use [fixed starter instructions](https://developer.realsee.ai/starters/immersive-vr/agent.md) with an AI coding tool that can create files and run terminal commands. You can preview the complete prompt before copying it. It points to the official versioned archive, its checksum, and the checks to perform.

For manual setup, download the same ZIP and extract it into a new directory. Open a terminal in the extracted `realsee-immersive-vr` directory. Keep the supplied lockfile.

## What you need

- Node **24** and npm.
- A WebGL-capable browser.
- Network access to the scene's image and model assets.
- No account or keys for the public scene.

[Open Playground](https://developer.realsee.ai/playground) to try a hosted public scene. The public sample and Playground Demo need no sign-in, Developer app, or OpenAPI scope.

## Install, check, and run

```sh
npm ci
npm run check
npm run build
npm run dev
```

Open the address printed in the terminal. The default development frontend is `http://127.0.0.1:5173`; its local Node API is on port `4101`.

For a local production build, run `npm start` after `npm run build` and use the address it prints. Stop the process with Ctrl+C.

## Check the actual result

The project opens directly into a full-screen VR tour. Wait for **Ready**, drag to look around, select a floor point, switch between Panorama and Floorplan, and check fullscreen. The default route has no developer dashboard or reset action.

The viewer needs network access to the image and model assets referenced by that Work.

The project bundles the official photographed Work sample from [Dnalogel’s real dataset](https://github.com/realsee-developer/dnalogel/tree/f7111018ab6ee8bcde7c6008ddf635cfc9b5aa03/open-works/real/80o024DE2xyva3j5BE). Its original media references and signatures are retained; it is not a generated apartment. Five SDK declares `three@^0.117.1`; this starter pins the exact compatible `0.117.1` release.

## Explore the SDK examples

In the React edition, open **Spaces → Open SDK examples**, or append `?sdk-examples=1` to its local URL. This separate page uses the public scene and the source files used in these guides:

- [Load a scene](https://developer.realsee.ai/docs/five-sdk/load-a-scene).
- [Camera and modes](https://developer.realsee.ai/docs/five-sdk/camera-and-modes).
- [Events and coordinates](https://developer.realsee.ai/docs/five-sdk/events-and-coordinates).
- [Capture an image](https://developer.realsee.ai/docs/five-sdk/capture-images).

The SDK examples do not exchange app credentials or test Team access.

## Continue with your data

Follow [Team API Quickstart](https://developer.realsee.ai/docs/open-api/quickstart). Run `npm run configure -- --device` and open its verification link. Sign in, choose the owning Team and an enabled app, then select **Authorize agent** yourself. The helper writes the local server `.env`. If device authorization is unavailable, configure `.env` locally. Never put secrets in a prompt or browser environment variables.

The local server checks token and directory responses, issues a short-lived selection, and fetches the selected Work. The browser then parses and renders that Work. An empty authorized list is a valid API result; it is not scene success.

## If something fails

| Stage | Action |
| --- | --- |
| Install | Check Node 24 and registry access. Keep the lockfile; do not use `--force` to hide dependency conflicts. |
| Local server | Use the printed port or configure an unused port in the local environment. |
| WebGL or scene assets | Check browser support and asset network access. Keep the loading/error state visible. |
| Team API | Follow the stage reported by the local server; public Demo success does not test credentials. |

See [React lifecycle](https://developer.realsee.ai/docs/five-sdk/react-lifecycle) before integrating the viewer into an existing app, and [Production checklist](https://developer.realsee.ai/docs/five-sdk/production) before sharing a Team-backed deployment.

## Read the working viewer

The default viewer uses React lifecycle hooks and the actual SDK. Open the complete source when you are ready to change it. This code is read from the downloadable project during the documentation build.


**View the complete src/Viewer.tsx**


```tsx title="starters/immersive-vr/src/experience.ts"
import type { Five as FiveInstance } from '@realsee/five';
import type { StarterConfig, TeamDirectory, TeamVr } from '../shared/contracts';
import { requestApi } from './api';

export interface TourState {
  phase: 'loading' | 'ready' | 'error';
  title: string;
  source: 'demo' | 'team';
  mode: string;
  message: string;
  returnToAgent: boolean;
  notice: string;
  teamConfigured: boolean;
  catalogOpen: boolean;
  directory: TeamDirectory | null;
  directoryBusy: boolean;
  directoryError: string;
  hasNextPage: boolean;
  hasPreviousPage: boolean;
}
export const initialTourState: TourState = {
  phase: 'loading', title: 'The Apartment', source: 'demo', mode: 'Panorama',
  message: 'Opening your space…', returnToAgent: false, notice: '', teamConfigured: false,
  catalogOpen: false, directory: null, directoryBusy: false, directoryError: '',
  hasNextPage: false, hasPreviousPage: false,
};

export function tourReadyStatus(state: TourState) {
  if (state.phase !== 'ready') return '';
  if (state.returnToAgent) return 'Scene ready. Return to your AI agent to continue creating with this scene.';
  return state.mode === 'Topview' ? 'Ready. Top view.' : `Ready. ${state.mode} view.`;
}

type MountedScene = { five: FiveInstance; layer: HTMLDivElement; stop?: () => void };

/** The renderer and authorized data flow are shared. Each framework owns its UI. */
export function createTour(host: HTMLElement, onChange: (state: TourState) => void) {
  let state: TourState = {
    ...initialTourState,
    catalogOpen: new URLSearchParams(window.location.search).get('spaces') === '1',
  };
  let disposed = false;
  let sceneGeneration = 0;
  let directoryGeneration = 0;
  let current: MountedScene | null = null;
  const pending = new Set<MountedScene>();
  const configRequest = new AbortController();
  let directoryRequest: AbortController | null = null;
  let workRequest: AbortController | null = null;
  let modeBusy = false;
  const selection = new URLSearchParams(window.location.hash.slice(1));
  const emit = (patch: Partial<TourState>) => {
    if (disposed) return;
    state = { ...state, ...patch };
    onChange(state);
  };
  const destroy = (scene: MountedScene) => {
    scene.stop?.();
    scene.five.dispose();
    scene.layer.remove();
    pending.delete(scene);
  };
  const resize = new ResizeObserver(([entry]) => {
    const rect = entry?.contentRect;
    if (rect) current?.five.refresh({ width: rect.width, height: rect.height });
  });
  resize.observe(host);

  async function loadScene(vr?: Pick<TeamVr, 'name' | 'sceneHandle'>, confirmed = false) {
    const generation = ++sceneGeneration;
    workRequest?.abort();
    const request = new AbortController();
    workRequest = request;
    emit({ phase: 'loading', message: 'Opening your space…', notice: '' });
    let staging: MountedScene | null = null;
    try {
      const [{ Five, parseWork }, work] = await Promise.all([
        import('@realsee/five'),
        vr
          ? requestApi<{ work: unknown }>('/api/team/work', {
              method: 'POST', body: JSON.stringify({ sceneHandle: vr.sceneHandle }), signal: request.signal,
            }).then((result) => result.work)
          : import('./real-demo-work.json').then((module) => module.default),
      ]);
      if (disposed || generation !== sceneGeneration) return;
      const five = new Five({ imageOptions: { size: 1024 }, poweredByRealsee: false });
      const layer = document.createElement('div');
      layer.className = 'scene-layer';
      layer.style.opacity = '0';
      host.append(layer);
      staging = { five, layer };
      pending.add(staging);
      five.appendTo(layer);
      await five.load(parseWork(work as Parameters<typeof parseWork>[0]), 'initial');
      if (disposed || generation !== sceneGeneration) {
        if (pending.has(staging)) destroy(staging);
        return;
      }
      if (current) destroy(current);
      current = staging;
      pending.delete(staging);
      layer.style.opacity = '1';
      staging.stop = five.on('modeChange', (mode) => {
        if (current?.five === five) emit({ mode });
      });
      five.refresh({ width: host.clientWidth, height: host.clientHeight });
      emit({ phase: 'ready', title: vr?.name || 'The Apartment', source: vr ? 'team' : 'demo', mode: five.state.mode, message: 'Ready', returnToAgent: false });
      if (vr && confirmed) {
        const flow = selection.get('flow');
        const query = flow ? `?${new URLSearchParams({ flow })}` : '';
        try {
          await requestApi<{ confirmed: true }>(`/api/team/confirmed-scene${query}`, {
            method: 'POST', signal: request.signal,
            body: JSON.stringify({ sceneHandle: vr.sceneHandle }),
          });
          if (!disposed && generation === sceneGeneration) emit({ returnToAgent: true });
        } catch {
          if (!disposed && generation === sceneGeneration) emit({
            notice: 'Your scene opened, but the agent could not receive the selection. Refresh this page to try again.',
          });
        }
      }
    } catch {
      if (staging && pending.has(staging)) destroy(staging);
      if (disposed || generation !== sceneGeneration) return;
      emit({ phase: current ? 'ready' : 'error', message: current ? 'Ready' : 'This space could not load.',
        notice: vr ? 'This Team space could not open. Your current view is unchanged. Refresh the space list and try again.' : 'Check your connection and WebGL support, then try again.' });
    }
  }

  async function loadDirectory(page = 1) {
    const generation = ++directoryGeneration;
    directoryRequest?.abort();
    const request = new AbortController();
    directoryRequest = request;
    emit({ directoryBusy: true, directoryError: '' });
    try {
      const directory = await requestApi<TeamDirectory>(`/api/team/vrs?page=${page}&pageSize=12`, { signal: request.signal });
      if (disposed || generation !== directoryGeneration) return;
      emit({ directory, directoryBusy: false, hasPreviousPage: directory.page > 1,
        hasNextPage: directory.totalPages === null ? directory.list.length === 12 : directory.page < directory.totalPages });
    } catch {
      if (disposed || generation !== directoryGeneration) return;
      emit({ directoryBusy: false, directoryError: 'Your spaces could not be listed. Check the local Team configuration and try again.' });
    }
  }

  async function showScenes() {
    emit({ catalogOpen: true });
    if (state.teamConfigured && !state.directory && !state.directoryBusy) await loadDirectory();
  }
  async function changeMode() {
    if (!current || modeBusy || state.phase !== 'ready') return;
    modeBusy = true;
    const scene = current;
    try {
      await scene.five.changeMode(scene.five.state.mode === 'Panorama' ? 'Topview' : 'Panorama');
      if (current === scene) emit({ mode: scene.five.state.mode, notice: '' });
    } catch {
      if (current === scene) emit({ notice: 'A floorplan is not available for this space. You can keep exploring the current view.' });
    } finally { modeBusy = false; }
  }
  async function toggleFullscreen() {
    try {
      if (document.fullscreenElement) await document.exitFullscreen();
      else if (host.parentElement?.requestFullscreen) await host.parentElement.requestFullscreen();
      else emit({ notice: 'Fullscreen is not available in this browser.' });
    } catch { emit({ notice: 'Fullscreen is not available in this browser.' }); }
  }
  const keyboard = (event: KeyboardEvent) => {
    if (event.key === 'Escape') { emit({ catalogOpen: false }); return; }
    if (event.ctrlKey || event.metaKey || event.altKey || /^(INPUT|TEXTAREA|SELECT|BUTTON|A)$/u.test((event.target as HTMLElement).tagName)) return;
    if (event.key.toLowerCase() === 'f') void toggleFullscreen();
  };
  document.addEventListener('keydown', keyboard);
  const sceneHandle = selection.get('scene');
  const name = selection.get('name');
  const selectedScene = sceneHandle && name ? { sceneHandle, name } : undefined;
  const confirmedSelection = selection.get('confirmed') === '1';
  void loadScene(selectedScene, confirmedSelection);
  void requestApi<StarterConfig>('/api/config', { signal: configRequest.signal }).then((config) => {
    if (disposed) return;
    emit({ teamConfigured: config.teamConfigured });
    if (state.catalogOpen && config.teamConfigured) void loadDirectory();
  }).catch(() => { /* A static public tour remains usable without the local backend. */ });

  return {
    showScenes, loadDirectory, changeMode, toggleFullscreen,
    closeScenes: () => emit({ catalogOpen: false }),
    openDemo: () => { emit({ catalogOpen: false }); void loadScene(); },
    selectScene: (vr: TeamVr) => { emit({ catalogOpen: false }); void loadScene(vr); },
    dismissNotice: () => emit({ notice: '' }),
    retry: () => { if (!current) void loadScene(selectedScene, confirmedSelection); },
    dispose() {
      disposed = true;
      ++sceneGeneration;
      ++directoryGeneration;
      configRequest.abort(); directoryRequest?.abort(); workRequest?.abort();
      resize.disconnect(); document.removeEventListener('keydown', keyboard);
      if (current) destroy(current);
      for (const scene of [...pending]) destroy(scene);
      current = null;
    },
  };
}
export type Tour = ReturnType<typeof createTour>;
```
