---
title: "Opt-in DevTools with Onboarding"
description: "@devframes/hub-ui-onboard lets a host ship a 20 kB floating button instead of the hub, install the hub on demand, and hand the hub base to it without a restart."
canonical_url: "https://devfra.me/guide/hub-ui-onboard"
---
# Opt-in DevTools with Onboarding

> @devframes/hub-ui-onboard lets a host ship a 20 kB floating button instead of the hub, install the hub on demand, and hand the hub base to it without a restart.

`@devframes/hub-ui-onboard` lets a host ship a 20 kB floating button instead of the hub, install the hub on demand, and hand the hub base to it in the same process.

## Why

A hub UI provider, its Vue runtime, and the devframes it mounts add tens of megabytes to a framework's install size. A host that wants DevTools as an opt-in can move those packages to optional peers and ship only this package: one browser file, a handful of routes, and three small runtime dependencies (a package-manager detector, a process runner, the diagnostics library). The user still discovers DevTools through the usual floating button; the first click installs them.

## What the user sees

The button sits at the bottom left, dimmed until hovered. It opens a panel with the product name and logo, one sentence, the exact command the install will run (for example `pnpm add -D @nuxt/devtools`), and three actions:

- **Install** runs the command in the project after the developer allows it in the terminal (below). The panel shows progress, then either the real dock replaces the button in place, or the panel asks for a restart.
- **Hide for now** removes the button for the current browser tab.
- **Disable entirely** writes a state file so the host stops injecting the button on every later start.

The panel follows the shared design tokens, the host's `primaryColor`, and the user's hub color scheme, so the swap to the real dock looks like one product.

## Create the onboarding

```ts
import { createOnboarding } from '@devframes/hub-ui-onboard'

const onboarding = createOnboarding({
  packages: ['@devframes/hub', '@devframes/hub-ui'],
  branding: { productName: 'My DevTools', logo: '/logo.svg', primaryColor: '#646cff' },
})
```

`createOnboarding()` returns four things:

- `handler(request)`: a web-standard `Request => Response` handler for every path under `base` (default `/__devframes/`).
- `nodeMiddleware(req, res, next)`: the same handler as Connect middleware for Vite, Express, Fastify with `@fastify/middie`, or a plain `node:http` server. It calls `next()` for paths outside `base`.
- `scriptSrc`: `<base>embedded.js`, the URL to inject as `<script type="module">`.
- `disabled` and `installed`: what the host needs to decide whether to inject the script at all (below).

`packages` are package specs as the package manager accepts them. The package manager comes from the lockfile (`npm`, `pnpm`, `yarn`, `bun`, `deno`), `dev: true` adds `-D`, and `cwd` (default `process.cwd()`) is the project that receives the dependency. In a workspace, point `cwd` at the package that runs the dev server. The packages are fixed at creation. An install that runs longer than `installTimeout` (default 5 minutes) is stopped, and the panel asks the user to run the command in a terminal ([DF9009](https://devfra.me/errors/DF9009)).

## Confirm the install

Install changes `package.json` and the lockfile, and a dev server can be reachable from other devices. So each install that the panel asks for needs the developer's permission. By default, the onboarding asks in the terminal that runs the dev server:

1. The user clicks Install. The panel shows "Confirm in your terminal..." and its request waits.
2. The terminal prints [DF9005](https://devfra.me/errors/DF9005). The developer types `y` and presses Enter within 5 minutes to allow the install. Any other answer refuses it. No answer in that time also refuses it ([DF9008](https://devfra.me/errors/DF9008)).
3. The install runs. After a refusal, the panel says that the dev server did not allow the install.

Only one question is open at a time: more clicks while it is open share its answer. A `POST` from another origin is refused with `403` before any question.

The default question needs a terminal that the dev server process reads line by line, as under `vite`. When nobody can answer, the onboarding refuses at once. It reports [DF9006](https://devfra.me/errors/DF9006) when stdin is not a TTY, for example in CI, in a detached container, or under a task runner that pipes stdin. It reports [DF9007](https://devfra.me/errors/DF9007) when another program holds stdin in raw mode to read single-key shortcuts. That program also captures the log, so the question does not show.

A CLI that owns the terminal takes the answer away from the dev server. `nuxi dev` is one: its interactive interface holds stdin in raw mode, it runs the dev server in a child process without stdin after a restart, and in plain mode it reads each line for its own shortcuts. A host that runs under such a CLI must pass `onConfirm` and ask through that CLI.

To ask in another way, pass `onConfirm`. It gets the `packages`, the exact `command`, and the panel's `request`, and returns `true` to allow the install. For example, a host that owns its terminal can ask through `consola`:

```ts
import { consola } from 'consola'

const onboarding = createOnboarding({
  packages: ['@nuxt/devtools'],
  onConfirm: ({ command }) => consola.prompt(`Run \`${command.join(' ')}\` for the browser that asked?`, { type: 'confirm' }),
})
```

Disable entirely does not ask. It changes only the state file in `node_modules/.devframe`.

## Hand the base to the hub

Return a handler from `onInstalled` and the hub takes over `base` in the same process. The button then loads the real `embedded.js` from that handler and removes itself.

```ts
import { createRequire } from 'node:module'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'

const require = createRequire(join(cwd, 'package.json'))
const load = <T>(id: string): Promise<T> => import(pathToFileURL(require.resolve(id)).href)

const onboarding = createOnboarding({
  cwd,
  packages: ['@devframes/hub', '@devframes/hub-ui'],
  async onInstalled() {
    const [{ initHub }, { createUi }] = await Promise.all([
      load<typeof import('@devframes/hub/initiate')>('@devframes/hub/initiate'),
      load<typeof import('@devframes/hub-ui')>('@devframes/hub-ui'),
    ])
    const hub = initHub({
      base: '/__devframes/',
      cwd,
      server: httpServer,
      ui: createUi(),
      devframes: []
    })
    return hub.handler
  },
})
```

Resolve the new packages from the project's `package.json`, as above. Under pnpm they are dependencies of the project, so a bare `import('@devframes/hub')` from the host's own file fails. Pass the live `node:http` server so the hub attaches its WebSocket to it; `initHub` accepts a server after it started listening.

`onInstalled` is also how the onboarding short-circuits. When every named package is already in `node_modules` at creation, `onboarding.installed` is `true`, `onInstalled` runs on the first request, and the user never sees the button. A host can therefore mount the onboarding unconditionally during development: it serves the hub when the packages exist and the button when they are missing.

Without `onInstalled`, or when it returns nothing, the panel reports the install and asks for a restart. The next start finds the packages installed.

## When to inject the button

Inject `scriptSrc` only when `onboarding.disabled` is `false`. The user set that flag with "Disable entirely"; it lives in `<stateDir>/hub-ui-onboard.json`, default `<cwd>/node_modules/.devframe`.

Mount the onboarding only when the user did not set the host's own devtools option. An explicit `devtools: true` means the host installs or requires DevTools itself; an explicit `devtools: false` means no button. The onboarding covers the unset case, and a user who disabled it from the panel turns it back on by setting the option.

## Hosts

### Vite

A plugin mounts the middleware and injects the tag. `examples/hub-onboard-vite` is the complete version with the hub hand-off.

```ts [vite.config.ts]
import type { Plugin } from 'vite'
import { createOnboarding } from '@devframes/hub-ui-onboard'

function hubOnboarding(): Plugin {
  const onboarding = createOnboarding({
    packages: ['@devframes/hub', '@devframes/hub-ui']
  })
  return {
    name: 'hub-onboarding',
    apply: 'serve',
    configureServer(server) {
      server.middlewares.use(onboarding.nodeMiddleware)
    },
    transformIndexHtml() {
      return onboarding.disabled
        ? []
        : [
            {
              tag: 'script',
              attrs: { type: 'module', src: onboarding.scriptSrc },
              injectTo: 'body'
            }
          ]
    },
  }
}
```

### Nuxt

Nuxt runs Vite, so a module reuses the plugin above and adds the tag to `app.head`. Gate it on the dev server, and skip it when the user set your own devtools option. The developer cannot answer the default terminal question under `nuxi dev`, so the module must pass its own `onConfirm`.

```ts [modules/devtools-onboarding.ts]
import { createOnboarding } from '@devframes/hub-ui-onboard'
import { addVitePlugin, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(_, nuxt) {
    if (!nuxt.options.dev)
      return
    const onboarding = createOnboarding({
      cwd: nuxt.options.rootDir,
      packages: ['@nuxt/devtools'],
      branding: { productName: 'Nuxt DevTools', primaryColor: '#00dc82' },
    })
    addVitePlugin({
      name: 'devtools-onboarding',
      configureServer: server => server.middlewares.use(onboarding.nodeMiddleware),
    })
    if (!onboarding.disabled)
      (nuxt.options.app.head.script ??= []).push({ type: 'module', src: onboarding.scriptSrc })
  },
})
```

### Next.js

A route handler forwards `Request` objects, and the root layout renders the tag.

```ts [app/__devframes/[[...path\\]\\]/route.ts]
import { onboarding } from '../../../devtools-onboarding'

export const GET = (request: Request) => onboarding.handler(request)
export const POST = (request: Request) => onboarding.handler(request)
```

```tsx [app/layout.tsx]
import { onboarding } from '../devtools-onboarding'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        {process.env.NODE_ENV === 'development' && !onboarding.disabled && (
          <script type="module" src={onboarding.scriptSrc} />
        )}
      </body>
    </html>
  )
}
```

A Next route handler cannot accept a WebSocket upgrade, so a hub started from `onInstalled` uses a side-car socket (`ws: { sidecar: true }`); see [Next](https://devfra.me/frameworks/next#mounting-a-hub).

### Any Node server

```ts
import { createServer } from 'node:http'

createServer((req, res) => {
  onboarding.nodeMiddleware(req, res, () => {
    res.statusCode = 404
    res.end()
  })
}).listen(3000)
```

Frameworks with a `Request => Response` surface (Hono, Nitro, Deno) mount `onboarding.handler` under `base` instead.

## Strings and branding

`branding` takes `productName`, `logo` (one URL or `{ light, dark }`) and `primaryColor`, the same three fields hub-ui's `DevframeBranding` starts with. Every string in the panel derives from `productName` and is overridable through `messages`; the keys are listed in the [Hub API reference](https://devfra.me/references/hub-api#onboarding-options-and-routes).

## Errors

The Node side reports through `DF9000` to `DF9009`. An install failure or a throwing `onInstalled` also reaches the panel as `{ state: 'error', error: { code, message } }`, with a Retry button. See the [error reference](https://devfra.me/errors).


## Sitemap

See the full [sitemap](https://devfra.me/sitemap.md) for all pages.
