# @pterodactyl/sdk Build extensions and themes for the Pterodactyl panel (v2+). This package provides: - **Types** for the runtime API. The implementation is provided *by the panel* through its import map, so your built extension never bundles the SDK, React, or TanStack Query: it shares the panel's own instances. - **The Vite build presets** (`@pterodactyl/sdk/vite`): `defineExtensionConfig` keeps those modules external and emits `dist/client.js` plus lazy screen chunks; `defineThemeConfig` also builds a theme's stylesheet. - **Test helpers** (`@pterodactyl/sdk/testing`, `@pterodactyl/sdk/vitest`) that render views, UI primitives and screens with the real runtime and no backend. - **The `pterodactyl-theme` CLI**, which lists the panel's views, ejects the stock theme's source for one, and copies its skins. Extensions start at [Quick start](#quick-start). Themes start at [THEMES.md](THEMES.md). ## Quick start ```tsx // src/client/index.tsx import { useState } from 'react'; import { Button, definePterodactylExtension, toast } from '@pterodactyl/sdk'; export default definePterodactylExtension({ setup({ slots, screens }) { slots.register('server.console.before', () => { const [count, setCount] = useState(0); return ; }); screens.register('votes', () => import('./VotesScreen')); }, }); ``` ```js // vite.config.mjs import { defineExtensionConfig } from '@pterodactyl/sdk/vite'; export default defineExtensionConfig({ entry: 'src/client/index.tsx' }); ``` `vite build` emits `dist/client.js`, referenced from your `extension.json`: ```json { "id": "myext", "name": "My Extension", "version": "1.0.0", "ui": { "entry": "dist/client.js", "mode": "native", "screens": [{ "id": "votes", "area": "server", "path": "votes", "nav": { "label": "Votes" }, "permission": ["ext.myext.view"] }] } } ``` The `ext.myext.view` permission above is the extension's own subuser permission. Register it from the extension's PHP provider so subusers can be granted it in the server's user editor: ```php $this->registerPermissions('Manage server votes.', ['view' => 'View the votes page.']); ``` Each key becomes `ext..`. Check it on the backend with `$user->can('ext.myext.view', $server)`. Everything exported from `@pterodactyl/sdk` (and the shared `react` / `react-dom` / `@tanstack/react-query` import-map entries) is semver-governed ABI: additions are minor versions, removals are majors. ## Loading and recovery Screen IDs, paths, navigation, and permissions live in `ui.screens` in the manifest. A screen's `permission` list names the subuser permissions needed to open it and is only accepted on `server` screens; account and admin screens are open to every signed-in user and every root admin respectively. Register each declared screen with `screens.register(id, importer)` during synchronous `setup`. Paths use a static first segment and may include named parameters such as `votes/$tab` (the panel reserves `$id`); duplicate paths, duplicate parameter patterns, and core route collisions reject the offending extension. Screen components receive a `data` prop (`ScreenComponentProps`) with the current `pathname`, `search`, and `params`, so `votes/$tab` reads its value from `data.params.tab`. The panel renders before optional bundles finish importing. Each extension commits atomically when ready; slot display order follows the load order: an extension after the ones it requires, then alphabetical by id. Screens show local loading state while their bundle or chunk loads. Slots have individual Suspense and error boundaries, and SDK websocket callbacks are isolated and attributed to their mod. Native extensions execute in the panel's JavaScript environment; boundaries are not a sandbox and cannot interrupt synchronous code. Recoverable render/query failures offer Retry. Failed screen chunks offer an explicit page reload because resetting an error boundary cannot evict a rejected browser module. Enabling, disabling, updating, or changing frontend configuration takes effect on the next full page load; reload after management changes. Already evaluated JavaScript is not unloaded dynamically. ## Types and shared dependencies The panel supports the React 19.3 client API. Server-only caching APIs, development-only `captureOwnerStack`, and unstable cache-refresh APIs are not part of the shared React facade. React, React DOM, JSX runtime, Query, and SDK entry points stay external through the Vite preset. SDK declarations are generated from the runtime public surface with `npm run sdk:generate` at the panel root. `npm run sdk:check` checks reproducibility and compiles a packed-package consumer, including negative type cases. Component props, form fields, and `useCurrentServer(server => server.attributes.name)` preserve their actual types. SDK peer dependencies include the existing libraries referenced by those declarations; use SDK form hooks/components to share the panel's bound form contexts. Declare screen metadata in the manifest and register each implementation by ID with `screens.register`. Build extensions against the SDK version used by the panel. A `file:` dependency on `packages/sdk` is a link into the panel checkout. TypeScript follows links to their real location by default, so the SDK declarations would take React, TanStack Query and the other peers from the panel's `node_modules` while your code takes them from yours; when the versions differ, `useQuery(serverFileContentQueryOptions(...))` fails on two unrelated `QueryClient` types. Scaffolded extensions set `"preserveSymlinks": true` in `tsconfig.json`, which resolves the SDK's peers from the extension, the same way the Vitest preset does at runtime. Do not add `paths` entries for `react`, `@tanstack/react-query` or `lucide-react`. An SDK installed from a tarball or registry needs neither option. ## Resource hooks and native data Admin screens may declare `parent: "admin.node"`, `"admin.server"`, `"admin.egg"`, or `"admin.user"`. Their paths become detail tabs and `useCurrentResource()` supplies the typed resource. `nav` supports `order`, `group`, `badge`, and `icon`. Parameterized navigation requires `nav.params`, for example `{ "tab": "overview" }` for `votes/$tab`. `PanelLink`, `usePanelNavigate`, and `usePanelLocation` use the host router; navigation by extension id and screen id also works for resource tabs. `serverQueryOptions`, `serverFilesQueryOptions`, `serverFileContentQueryOptions`, `serverStartupQueryOptions`, and `serverBackupsQueryOptions` use core cache keys and transport. Pass the server UUID for files, startup, and backups to share core entries. `serverLogsQueryOptions(uuid, lines?)` reads the latest console output (at most 100 lines, oldest first) and needs the `websocket.connect` permission. Their hooks accept selectors, and `invalidateServerData(uuid, domains)` returns the host invalidation promise. Curated mutation hooks reuse core updates and serialize startup writes. Await `mutateAsync` from a handler wrapped with `useExtensionAction`. `serverResourcesQueryOptions(uuid)` and `useServerResources(uuid, select?)` read power state and resource usage from the cache entry the dashboard's server cards poll, so a screen that shows them adds no request of its own. The panel asks Wings at most every 20 seconds; inside the server area, `useServerWebsocketEvent('stats' | 'status', ...)` delivers live values. `invalidateServerData(uuid, ['resources'])` refetches the entry. `useSendServerPower(uuid)` takes `{ signal: 'start' | 'stop' | 'restart' | 'kill' }` and `useSendServerCommand(uuid)` takes `{ command }`. Both go through the client API, so they work without a console socket, are checked against the user's `control.*` permissions by the panel, and report failures with the panel's own notification before rejecting. `useNavigationBlocker(shouldBlock, options?)` asks before unsaved work is left behind: router links and `usePanelNavigate`, the browser's back and forward buttons, and closing or reloading the tab. Pass a boolean, or a function read at navigation time when the answer lives in a ref. `message` sets the text of the default confirmation, `beforeUnload: false` leaves tab close alone, and `confirm(transition)` replaces the confirmation with your own decision (resolve `true` to leave); it receives the current and next `pathname`, `params` and `search`, so navigation within your own screen can pass. ```tsx const [dirty, setDirty] = useState(false); useNavigationBlocker(dirty, { message: 'Discard your changes to this file?' }); ``` File toolbar, row actions, and selection actions receive typed files, directory, selection, and refresh callbacks. `server.startup.form` receives current configuration and a guarded Docker image setter. `panel.users.detail.form` supplies the native `form`, so contributed `form.AppField` controls share core validation, pending state, submission, and persistence. Keep values in that form rather than copying a separate draft. To add fields of your own to an admin form, see [Admin form fields](#admin-form-fields). `columns.register('admin.nodes', { id, label, component })` adds a typed cell to the native table; servers and eggs are also supported. Columns commit atomically and render inside local error boundaries. Table, Tooltip, DropdownMenu, and Pagination complement the existing form and dialog primitives. `Empty` (with `EmptyHeader`, `EmptyMedia`, `EmptyTitle`, `EmptyDescription`, `EmptyContent`) matches the panel's empty states; pass it as a `Table`'s `emptyState`. `useExtensionTranslation('messages')` loads the provider's registered `resources/lang//messages.php` group. Extension CSS is built with the extension's own Tailwind prefix (see [Styling](#styling)). The Vite preset waits for entry CSS before setup. The active theme sets the panel's CSS tokens (see [Tokens](THEMES.md#tokens)). Extension utilities read the same live tokens (`hw:bg-card`, `hw:w-sidebar`, `hw:p-4` for the prefix `hw`), so an extension follows the theme without knowing it. The console and the `theme-color` meta re-read their tokens when a stylesheet or an inline property on `` changes; `onThemeChange(listener)` gives canvas or chart code the same signal, `readThemeToken('--name')` reads a value, and `notifyThemeChange()` reports changes made through the CSSOM. Only the panel's own `theme-color` tag follows the token; one registered with `registerHeadTags` is left as rendered. `useShortcut('g', handler)` binds a key, or `mod+` and a key for Cmd (Ctrl off Apple devices), while focus is outside fields, dialogs and menus, and returns its names for `aria-keyshortcuts` and a hint (see [Keyboard shortcuts](THEMES.md#keyboard-shortcuts)). ## Conditional screens, badges, and icons A screen's `when` states where it exists. A screen whose conditions fail is absent from navigation and not routable: its URL shows the panel's not-found page. ```json { "id": "mods", "area": "server", "path": "mods", "nav": { "label": "Mods", "icon": "blocks", "badge": "Beta" }, "when": { "eggTags": { "any": ["minecraft"] }, "eggFeatures": { "any": ["eula"] }, "match": "any" } } ``` `eggFeatures` and `eggTags` are for `server` screens. Each takes `all` (every value present) and/or `any` (at least one), compared without regard to case against the server's `egg_features` and `egg_tags`. With both declared they must both pass unless `match` is `"any"`. These rules come from the manifest and the server payload, so they apply before your bundle has loaded. Egg ids are deliberately not matchable: they differ between installations, so decide those cases at runtime from your own configuration. For anything the manifest cannot express, declare `"when": { "runtime": true }` (any area, alone or beside egg rules) and pass a predicate when registering the screen: ```tsx function useHasDomains({ server }: ScreenContext) { return useSuspenseQuery(domainsQueryOptions(server!.attributes.uuid)).data.length > 0; } // The third argument is a ScreenOptions object. screens.register('subdomains', () => import('./SubdomainsScreen'), { visible: useHasDomains, badge: ({ config }) => (config.maintenance === true ? 'Paused' : undefined), }); ``` `visible` and `badge` receive a `ScreenContext` (`user`, `config`, the `server` on server screens, the `resource` on admin resource tabs) and are called while rendering their own isolated mount, so they may use hooks and suspend; name them `use…` when they do. They re-run whenever that data changes. A predicate that throws hides the screen, a badge that throws leaves the manifest badge in place, and both are reported against your extension without disturbing the rest of the navigation. A `runtime` screen stays hidden until its bundle has loaded and the predicate has returned `true`, and its URL shows a spinner in the meantime; entries are never listed first and withdrawn later. That is why the flag lives in the manifest: registering `visible` for a screen without it, or omitting `visible` for a screen with it, fails the extension at load. Egg rules are checked first, so a predicate only runs where they pass. `badge` needs no manifest flag. Return a string or number to show it (32 characters at most), `null` or `''` for no badge, and `undefined` to keep `nav.badge`, which also shows while the bundle loads or the badge suspends. `nav.icon` accepts any [lucide](https://lucide.dev/icons) icon name in kebab-case, such as `life-buoy`. The names this panel ships are listed in `@pterodactyl/sdk/icons.json`; a name outside that list renders the default icon and is reported by `p:extension:doctor`. `` renders the same icons from the panel's copy of lucide, so an icon chosen as data (a setting, an API field) does not require bundling the icon set; `loadIconNames()` resolves the available names for a picker. Common names render immediately; the rest of the set is one lazily fetched chunk shared by every extension. Keep importing icons you reference in code from `lucide-react` and pass them to ``. The top-level `icon` is shown for the extension on the admin extensions page, in place of its initials. It is either a lucide icon name, as above, or the path of a PNG, JPEG or WebP image inside the package, such as `"icon": "icon.png"`. Images may be at most 512 KB and 2048 px per side, and a square image of 128 px or more looks best. The image does not have to sit in `dist`: it is served to administrators from the package itself, so it shows while the extension is disabled, and `p:extension:pack` adds it to the archive. `p:extension:doctor` warns about an image that is missing or unreadable. ```json { "id": "mods", "name": "Mods", "version": "1.0.0", "icon": "icon.png" } ``` ## Author tooling and configuration `p:extension:make ` scaffolds a package in `extensions/`; `--out=` creates it in `/`. Use `p:extension:doctor `, `p:extension:dev --watch`, and `p:extension:pack ` for preflight checks, successful-build publishing with browser reload in debug mode, and runtime-only archives; pack leaves `*.map` files out unless given `--sourcemaps`, since a map can embed your sources. Scaffolds include tests, CI, OpenAPI generation, and styling. `@pterodactyl/sdk/testing` supplies `createExtensionTestHost` and `createTestServer`; `@pterodactyl/sdk/vitest` supplies aliases and setup for the real runtime, including the `ResizeObserver`, `IntersectionObserver` and `matchMedia` jsdom lacks. Unmount the wrapper and dispose the host after each test. The test host shares the real cache; create one host at a time within a test environment. Declare `requires.panel`, `requires.sdk`, `requires.php`, and `requires.extensions` as Composer-style version constraints in the manifest. Incompatible extensions and dependency cycles fail independently. Activation validates the build and runs migrations before enabling metadata. Upgrades retain old asset chunks for open sessions. Failed activation restores the previous package and asset pointer; partially applied database migrations need manual recovery. Successful lifecycle changes invalidate routes and signal queue worker restarts; reload the page to replace already evaluated frontend code. Migrations live in `database/migrations`. The panel registers that directory with Laravel's migrator for every enabled extension, so `migrate:status` lists the migrations and `migrate:rollback` finds them; a provider does not need to call `loadExtensionMigrations()`. Laravel records a migration by its file name, so enabling refuses an extension with a migration named like one of the panel's or another installed extension's, and `p:extension:doctor` reports it. A provider reads its settings with `$this->settings()`. Code outside the provider, such as a controller or a job, uses the `Pterodactyl\Facades\Extensions` facade: `Extensions::settings('billing')` returns the same settings, and `Extensions::isAvailable('billing')` tells whether an extension is enabled and running. Both return an `ExtensionSettings`: `get($key, $default)`, `set($key, $value)`, and `setSecret($key, $value)`, which stores the value encrypted. Backend settings support `forUser($user)` and `forServer($server)`. Mark secrets with `->secret()` to encrypt storage, mask admin output as `********`, and prohibit frontend exposure; `->field('password')` is always secret. A secret submitted empty, as its mask, or not at all keeps the stored value, whatever its field. `->frontend()->frontendType('boolean')` declares and verifies a public value's type. `p:extension:types ` generates literal screen ids, registered permissions, and public config keys. `defineConfiguredExtension` accepts a parser for runtime configuration and these generated types. Undeclared value types remain bounded JSON. Frontend values reach signed-in users only. `->frontend()->public()` also delivers a value to visitors who are not signed in (the login page), so use it only for values anyone may read; `public()` requires `frontend()` and cannot be combined with `secret()`. Generated types add `ExtensionPublicConfigKey` and `ExtensionPublicConfig` for the keys a guest receives; every other key is absent until the user signs in and the page reloads. Submitted values are checked against their field on the server as well as against the definition's rules: `text` and `password` take a string or number, `number` a number, `toggle` a boolean, and `select` one of its option values (compared strictly, so `'25'` does not match `25`). `null` passes all of them. A `number`, `toggle` or `select` default has to pass the same check. Beyond `text`, `password`, `number`, `toggle`, and `select`, settings have five typed fields, each validated server-side and rendered by the admin Extensions form: - `->color()`: a hex colour (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`) or a numeric `oklch(L C H [/ A])` colour, stored lower case. Nothing else is accepted, so the value is safe to place in a style rule. Clearing it restores the default. - `->textarea(maxLength: 5000)`: a multi-line string with normalized line endings. - `->multiselect($options)`: a list of the declared string or integer option values, in declaration order. - `->list(itemRules: ['max:255'], maxItems: 50)`: an ordered list of strings; every item must pass the item rules. - `->file(mimes: ExtensionSettingFiles::IMAGES, maxKilobytes: 1024)`: an admin upload. The type is decided from the content against the allow-list (PNG, JPEG, GIF, WebP and AVIF by default; ICO, WOFF, WOFF2 and SVG only when listed). An SVG must be plain SVG: scripts, event handlers, animation, embedded documents, `javascript:` or non-image `data:` links, and elements or attributes from other XML vocabularies (editor metadata included) are refused. The file is stored under a random name on the `extensions.files_disk` disk, which must be private (a public disk is refused, so files are only served with the panel's sandboxing headers), and `get()` and `ctx.config` return its URL under `/extension-files//` or the default (a URL or `null`). Replacing or clearing a file deletes the old one; removing the extension deletes them all. Files are uploaded through `POST`/`DELETE /api/admin/extensions//settings//file`, never through a settings update. These fields imply their `frontendType` (`string` or `array`; a colour or file with a `null` default stays JSON) and none of them can be `->secret()`. `->tab('Storage')` puts a field in a section of the admin form, chosen from a dropdown above the form; sections appear in the order their first field is defined. Once any field names a tab, fields without one are shown under "General", which comes first. A form with no tabbed fields has no dropdown. Sections only group the form: every field is saved together, and keys and validation are unchanged. The package exports `manifest.schema.json` for editor completion. Frontend scaffolds reference it with `$schema`; the server validates every package before activation. Use `ExtensionJobProgress::begin($extensionId, $user, $server, $permission)` to create a namespaced job snapshot, then `update($extensionId, $id, $percent, $message, $status)` from workers. User jobs are private to their creator and root admins. Server jobs with an extension permission are readable by users who still have that permission; otherwise they remain creator-only. `useExtensionJobProgress(id, { serverUuid })` polls running jobs, recovers on reconnect, and stops when the job finishes or access expires. Use a shared cache store for workers and web requests. Snapshots expire after `extensions.progress_retention_seconds` (one hour by default); they are progress UI, not a durable job audit log. ## Admin form fields An extension can add its own fields to the admin create and edit forms of users, servers, nodes, eggs, locations, mounts and database hosts. The panel validates them with the form, saves them in the same transaction, and returns them on the resource. Declare the fields in PHP with a `Fields` class and register it from the provider, one class per model: ```php use Illuminate\Validation\Rule; use Pterodactyl\Extensions\Fields; use Pterodactyl\Models\User; $this->registerFields(User::class, UserRole::class); final class UserRole extends Fields { public function rules(): array { return ['role' => ['nullable', 'integer', Rule::exists(Role::class, 'id')]]; } public function values(User $user): array { return ['role' => RoleAssignment::query()->whereKey($user->id)->value('role_id')]; } public function save(User $user, array $values): void { RoleAssignment::query()->updateOrCreate(['user_id' => $user->id], ['role_id' => $values['role']]); } } ``` Every method is optional. The panel calls them through the container, like the methods of a FormRequest, so each can type-hint the model it extends and any other dependency. A model parameter always receives the model being changed, never the signed-in user, and every method but `values()` and `save()` also runs while the model is created, so a model parameter there must be nullable. Registering a class that breaks either rule fails the provider's boot. - `rules()` validates the extension's values on their own, so `required_if:plan,pro` refers to the extension's own `plan`. They run for every extension the signed-in user may change when the model is created, whether or not the request sends its values, and when an update includes the extension under `extensions`, even with no values. The admin forms include every extension they show, so `required` holds there on create and on every edit, like the core fields beside it. An update that leaves the extension out leaves its values alone. A `?User $user` parameter receives the model when updating and null when creating. - `values($model)` returns the current values, keyed by field. Values are strings, numbers, booleans, null, or lists of those. - `save($model, array $values)` stores the validated values; the parameter must be named `$values`. It runs inside the transaction that writes the model, after its row is written and before Wings is contacted, so throwing rolls the whole change back. Put work that has to wait for the commit in `DB::afterCommit()`. - `authorize()` decides whether the signed-in user may see and change the values; type-hint `#[CurrentUser] User $admin` to get them. A request that sends values it refuses gets a 403. Only root admins reach these endpoints, and `$admin->can()` passes every check for a root admin, so decide on something else, such as the admin's id or a role the extension keeps. - `secrets()` lists the fields that hold credentials. Their values are encrypted when the panel stores them and returned as `********`. A save that sends the mask, or leaves the field out, keeps the stored value, and `save()` receives it. A save that sends null or an empty string clears it, so a `required` rule then fails. An empty secret is returned as null, so sending back what the form loaded clears nothing. - `attributes()` and `messages()` name the fields in validation messages and replace them, as on a FormRequest. Leave out `values()` and `save()` and the panel stores the values for you, apart from the extension's other settings: read them with `$this->settings()->fields($user)`. Settings from `for()`, `forUser()` and `forServer()` never include them, so an extension that shows users their own settings cannot expose admin fields. Implement both to keep the values in your own tables, where you can index, join and query them. Implementing only one fails the provider's boot. The admin API's create and update endpoints accept `extensions: { "": { "": value } }` and report errors under `extensions..`. Responses about one resource include `attributes.extensions`; lists leave it out. A request that leaves an extension out does not run its `save()`, values sent for an extension that is disabled are ignored, and an extension whose `values()` throws is recorded as failing and left out of the response. One whose methods throw while a save validates its values is recorded as failing too, and the request gets a 422 under `extensions.`. Mark the class `#[ApplicationApi]` (`Pterodactyl\Extensions\Attributes\ApplicationApi`) to accept and return its values on the Application API's user, node, location and server endpoints as well, so a billing system that provisions through it can set them. Draw the fields with `forms.extend()`. The component receives `field(name)`, which binds one field to the form: `value`, `setValue`, an `id` for its label, and `error`, the panel's message from the last save until the field changes. `values` holds every field of the extension: its saved values with the edits made so far. `mode` is `'create'` or `'edit'`, and `resource` is the saved resource when editing. ```tsx import { useQuery } from '@tanstack/react-query'; import { definePterodactylExtension, http, Label, Select, type FormExtension } from '@pterodactyl/sdk'; const RoleSelect: FormExtension<{ role: number | null }, 'admin.user'> = ({ field }) => { const role = field('role'); const { data: roles = [] } = useQuery(rolesQuery); return (