headlamp Documentation

A Kubernetes web UI that is fully-featured, user-friendly and extensible

7,710 stars TypeScript TypeScript 101 files · ~217,029 tokens #cloud-native#dashboard#debugging#devops#headlamp#k8s#kinvolk#kubernetes
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy headlamp on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name headlamp -p 4466:4466 --restart always kubernetes-sigs/headlamp:latest

Technical Documentation: kubernetes-sigs/headlamp

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (README.md)



Headlamp is an easy-to-use and extensible Kubernetes web UI.

Headlamp lets you view and manage Kubernetes resources through a graphical interface,
with plugins to extend its functionality.

Features

  • Vendor-independent Kubernetes UI
  • Runs in-cluster or locally as a desktop app
  • Multi-cluster support
  • Extensible through plugins
  • UI controls that reflect user permissions
  • Clean, modern UI
  • Cancellable create, update, and delete operations
  • Logs, terminal access, and a resource editor with documentation
  • Read and write access based on user permissions

Screenshots

Quick start

To deploy Headlamp in your cluster, follow the
in-cluster installation guide.
Container images are published as ghcr.io/headlamp-k8s/headlamp on
GitHub Container Registry.

To run Headlamp locally, install the
desktop application
for Linux,
macOS,
or Windows.
Make sure your kubeconfig is configured for the clusters you want to access.
See the desktop configuration options
to use a non-default kubeconfig file or multiple files.

Access and permissions

Headlamp uses Kubernetes role-based access control (RBAC)
to determine which resources you can view and which actions you can perform.
The resources available in Headlamp depend on the permissions granted to your credentials.

For token-based authentication, see how to
create a service account token.

Quick start for contributors

Want to hack on Headlamp? We'd love your help!

See the contributing guidelines for local development setup,
build instructions, and platform-specific tips.

For more detailed documentation, see the development guide.

Tested platforms

See the Kubernetes platforms Headlamp has been tested with.
Please contribute results for other platforms or report regressions.

Extensions and plugins

Browse Headlamp plugins on Artifact Hub
for published plugins.

See the plugins repository for official plugins.

Plugin development

To extend Headlamp for your use cases, see the
plugin development guide.

Get involved

Join the community and contribute:

Roadmap and release planning

Track upcoming releases in GitHub milestones
and proposed changes in GitHub issues.
See the release notes for changes in published versions.

License

Headlamp is released under the terms of the Apache 2.0 license.

Frequently asked questions

For more information about Headlamp, see the Headlamp FAQ.


Index (`docs/index.md`)


title: Introduction sidebar_position: 1

Headlamp is an easy-to-use and extensible Kubernetes web UI.

Headlamp was created to blend the traditional feature set of other web UIs/dashboards
(i.e., to list and view resources) with added functionality.

Headlamp can be used in-cluster, where it's accessed through a web browser,
or as a desktop application (using the information defined in the user's
kubeconfig).

Learn

Learn how to use Headlamp and its unique features in a section dedicated to users. Learn section

Develop

Read about how to build Headlamp for different use-cases, or learn how to create a Headlamp Plugin.

Get involved

Check out our:

Frequently Asked Questions

For more information about Headlamp, see the Headlamp FAQ.


Development Index (`docs/development/index.md`)


title: Development sidebar_position: 5

This is a quickstart guide for building and running Headlamp for development.

Please make sure you read the Contribution Guidelines as well
before starting to contribute to the project.

See platforms to find out which browsers, OS and flavors of Kubernetes we support.

Dependencies to get started

These are the required dependencies to get started. Other dependencies are pulled in by the golang or node package managers (see frontend/package.json, app/package.json, backend/go.mod and Dockerfile).

  • Node.js >= 22.12.0 (LTS recommended). Many of us use nvm for installing multiple versions of Node.
  • npm (>= 11.0.0)
  • Go (>= 1.25.9)
  • Kubernetes, we suggest minikube as one good K8s installation for testing locally. Other k8s installations are supported (see platforms).

You can install the required frontend, app, and backend dependencies by running:

bash
npm run install:all

Code scanning

The Semgrep workflow
checks Go, JavaScript, and TypeScript for potential security issues on pull
requests and pushes to main, alongside existing CodeQL scans. Findings are
available in GitHub code scanning for review.

Build the code

Headlamp is composed of a backend and a frontend.

You can build both the backend and frontend by running:

bash
npm run build

Or individually:

bash
npm run backend:build

and

bash
npm run frontend:build

Container image digests

npm run image:verify-image-digests checks the pinned image itself for a
multi-platform index supporting Linux amd64 and arm64. An upstream tag moving
does not invalidate an existing pin.

npm run image:update-image-digests resolves the existing tags in Dockerfile
and Dockerfile.plugins, validates their indexes, and updates only the digests.
Both commands require Docker Buildx and registry access.

The existing weekly Docker Dependabot job groups image updates into PRs,
including digest-only changes when a tag has not changed. Dependabot is the
single periodic updater; use the manual command above only when needed.

Container CI validates pins when Dockerfile digest lines change. The Test image
digest tooling
workflow runs offline unit tests only when the digest tool,
its tests, or that workflow changes. Neither requires unchanged pins to follow a
moving upstream tag, and there is no separate scheduled updater or bot-token
requirement for digest maintenance.

Run the code

The quickest way to get the backend and frontend running for development is to run both together:

bash
npm start

Or you can run them individually in separate terminal instances:

bash
npm run backend:start

and in a different terminal instance:

bash
npm run frontend:start

Backend logging

Backend log verbosity can be controlled using either a flag or an environment variable.

  • --log-level
  • HEADLAMP_CONFIG_LOG_LEVEL

Supported Values: debug, info, warn, error (default: info)

Example:

bash
npm run backend:start -- --log-level warn

Backend telemetry

Headlamp supports OpenTelemetry tracing and Prometheus metrics on the backend. See the Telemetry guide for how to enable and use them locally or in-cluster.

Generate API documentation

To generate the TypeScript API documentation:

bash
npm run docs

This generates API documentation in docs/development/api/ using TypeDoc.

Build the app

You can build the app for Linux, Windows, or Mac.

Do so on the platform you are building for. That is build the mac app on a Mac,
and the linux app on a linux box.

Choose the relevant command:

bash
npm run app:package:linux
bash
npm run app:package:mac
bash
npm run app:package:win

For Windows, by default it will produce an installer using NSIS (Nullsoft Scriptable Install System).

If you prefer an .msi installer, then be sure to install the WiX Toolset and have its light.exe and candle.exe in the Windows path.
E.g., if you are using WiX Toolset version 3.11, this can be done by running the following command,
before the one above:

bash
set PATH=%PATH%;C:\Program Files (x86)\WiX Toolset v3.11\bin

Then run the following command to generate the .msi installer:

bash
npm run app:package:win:msi

See the generated app files in app/dist/ .

Verifying Builds

After packaging the desktop app using the appropriate npm run app:package command (which creates packaged artifacts in app/dist/), you can verify that the built binaries work correctly by running the appropriate verification command. This is useful to ensure the built binaries run properly, especially when upgrading packages that build binaries or when updating Electron.

Linux

bash
npm run app:verify-build-linux

macOS

bash
npm run app:verify-build-mac

Windows

powershell
npm run app:verify-build-windows

These verification scripts will check that build artifacts exist, test the backend server binary, and run the Electron app to ensure it executes correctly.

Note for macOS: On systems without a display server (like CI environments), the Electron app may timeout. This is expected behavior and is treated as success if the app at least starts.

Running the app

If you already have BOTH the backend and frontend up and running, the quickest way to
get the app running for development is the following:

bash
npm run app:start:client

or else you can simply do

bash
npm run start:app

which runs everything including the backend, frontend and app in parallel.

Running the app on Ubuntu WSL

Headlamp on WSL requires some packages installed (maybe it requires more) to run the app.

Note: libgconf-2-4 was removed starting with Ubuntu 24.04 and newer
releases. If you are on an older release where it is still available you can
install it as well, otherwise you can safely omit it.

bash
sudo apt install libatk1.0-0 libatk-bridge2.0-0 libgdk-pixbuf2.0-0 libgtk-3-0 libgbm1 libnss3 libasound2

Some of these are also needed some of them only for the end to end tests.

bash
sudo apt-get install firefox libgstreamer-plugins-bad1.0-0 libegl1 libnotify4 libopengl0 libwoff1 libharfbuzz-icu0 libgstreamer-gl1.0-0 libwebpdemux2 libenchant1c2a libsecret-1-0 libhyphen0 libevdev2 libgles2 gstreamer1.0-libav

Build a container image

The following command builds a container image for Headlamp from the current
source. It will run the frontend from a backend's static server, and
options can be appended to the main command as arguments.

bash
npm run image:build

Custom container base images

The Dockerfile takes a build argument for the base image used. You can specify the
base image used using the IMAGE_BASE environment variable.

bash
IMAGE_BASE=debian:latest npm run image:build

If no IMAGE_BASE is specified, then a default image is used (see Dockerfile for exact default image used).

This is useful if there are requirements on which base images can be used in an environment.

So far Debian variants (including Ubuntu), and Alpine Linux are supported.
If you have other requirements, please get in touch.

Running the container image

With docker you can run the Headlamp image(ghcr.io/headlamp-k8s/headlamp:latest).
Note, the mount arguments add folders that are referenced in the ~/.kube
folders - you may need to add other folders if your config refers
to more folders.

bash
docker run --network="host" -p 127.0.0.1:4466:4466/tcp --mount type=bind,source="/home/rene/.minikube",target=$HOME/.minikube --mount type=bind,source="$HOME/.kube",target=/root/.kube ghcr.io/headlamp-k8s/headlamp:latest /headlamp/headlamp-server -html-static-dir /headlamp/frontend -plugins-dir=/headlamp/plugins

If you want to make a new container image called headlamp-k8s/headlamp:development
you can run it like this:

bash
$ DOCKER_IMAGE_VERSION=development npm run image:build
...
Successfully tagged headlamp-k8s/headlamp:development

$ docker run --network="host" -p 127.0.0.1:4466:4466/tcp --mount type=bind,source="/home/rene/.minikube",target=$HOME/.minikube --mount type=bind,source="$HOME/.kube",target=/root/.kube headlamp-k8s/headlamp:development /headlamp/headlamp-server -html-static-dir /headlamp/frontend -plugins-dir=/headlamp/plugins

Then go to https://localhost:4466 in your browser.

Minikube "in-cluster"

These instructions are for if you want to run Headlamp "in-cluster",
and test it locally on minikube with a local container image.

We assume you've already set up minikube
(probably with minikube start --driver=docker).

Container image in the minikube docker environment

First, we have to make the container image in the minikube docker environment.
This is needed because minikube looks for container images in there, not
ones made in the local docker environment.

bash
eval $(minikube docker-env)
DOCKER_IMAGE_VERSION=development npm run image:build

Create a deployment yaml

bash
kubectl create deployment headlamp -n kube-system --image=headlamp-k8s/headlamp:development -o yaml --dry-run=client -- /headlamp/headlamp-server -html-static-dir /headlamp/frontend -in-cluster -watch-plugins-changes false -plugins-dir=/headlamp/plugins > minikube-headlamp.yaml

To use the local container image we change the imagePullPolicy to Never.
Making kubectl use local images - which is what you want in development.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: headlamp
  name: headlamp
  namespace: kube-system
spec:
  replicas: 1
  selector:
    matchLabels:
      app: headlamp
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: headlamp
    spec:
      containers:
        - command:
            - /headlamp/headlamp-server
            - -html-static-dir
            - /headlamp/frontend
            - -in-cluster
            - -plugins-dir=/headlamp/plugins
          image: headlamp-k8s/headlamp:development
          name: headlamp
          imagePullPolicy: Never
          resources: {}
status: {}

Now we create the deployment.

bash
kubectl apply -f minikube-headlamp.yaml

Then we expose the deployment, and get a URL where we can see it.

text
$ kubectl expose deployment headlamp -n kube-system --type=NodePort --port=4466
service/headlamp exposed

$ kubectl get service headlamp -n kube-system
NAME       TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
headlamp   NodePort   10.99.144.210   <none>        4466:30712/TCP   6m57s

$ minikube service headlamp -n kube-system --url
http://192.168.49.2:30342

Go to the URL printed by minikube in your browser, and get your token to login.

Shipping plugins in the Docker image

The Headlamp server has an option (-plugins-dir) for indicating where to find any plugins.
Thus, a deployment of Headlamp using the Docker image can mount a plugins folder
and point to it by using the mentioned option.

An alternative is to build an image that ships some plugins in it. For that,
just create a ".plugins" folder in the Headlamp project directory, as the Dockerfile
will include it and point to it by default.

Special Build Options

Here are some options that can be used when building Headlamp to change its default behavior.

Update Checks

In the desktop app, by default, Headlamp will check for new versions from its GitHub page and warn the user about it.
It will also show the release notes after updating to a new version.

This behavior can be turned off by adding the following to a .env file in the app/ folder:

bash
HEADLAMP_CHECK_FOR_UPDATES=false

Build Headlamp Base (Headlamp without any plugins)

For building Headlamp Base (Headlamp without plugins), simply remove the app/app-build-manifest.json and run the build commands in the sections above.


Installation Index (`docs/installation/index.mdx`)


title: Installation sidebar_position: 2

Headlamp can be deployed in a Kubernetes cluster, or run as a desktop application.

Authentication / Log-in

Currently you can log in Headlamp by using a client-certificate (as you may have configured with e.g. minikube), or a bearer token.

Headlamp uses RBAC for checking users' access to resources This means that the
recommended way to log in into Headlamp is to use a Service Account token.

Create a Service Account token

As an example, you can create a service account for using Headlamp and retrieve its token to
authenticate:

  1. Create a Service Account:
shell
kubectl -n kube-system create serviceaccount headlamp-admin
  1. Give admin rights to the account:

:::tip

Check RBAC docs if you want to set more
restrictive permissions.

:::

shell
kubectl create clusterrolebinding headlamp-admin --serviceaccount=kube-system:headlamp-admin --clusterrole=cluster-admin
  1. Create the token using the following command:

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

```shell kubectl create token headlamp-admin -n kube-system ``` ```shell export HEADLAMP_SECRET=$(kubectl get secrets --namespace kube-system -o custom-columns=":metadata.name" | grep "headlamp-admin-token") kubectl get secret $HEADLAMP_SECRET --namespace kube-system --template=\{\{.data.token\}\} | base64 --decode ```

Once you have the Service Account token, paste it when prompted by Headlamp.

Use OIDC

For OpenIDConnect, please see the in-cluster installation docs.

Security

For security requirements, trust boundaries, TLS, RBAC, plugin trust, and release verification, see Security Requirements and Expectations.


Learn Index (`docs/learn/index.md`)


title: Learn sidebar_position: 7

Welcome to the new Learn section.

Here you'll find resources for learning how to use Headlamp.

User Guides

  • Projects, Projects group related Kubernetes resources into an application-focused view; this guide explains what Projects are, how to create them, and how to use their tabs and features.
  • Local Cluster, Local Cluster enables creating and managing a full Kubernetes cluster locally via Headlamp Desktop App; this guide explains how to add, operate, and delete the cluster and deploy sample applications.

Development Guides

If you are looking for how to install Headlamp or develop it, check out these guides:

  • Installation, instructions for installing Headlamp on various platforms and configuring it to connect to your cluster.
  • Development, guide to setting up a local development environment, building and testing the app, and contributing code.
  • Plugins, guide to creating Headlamp plugins to extend its functionality.

Tutorials Index (`docs/tutorials/index.mdx`)


title: Tutorials sidebar_position: 3

Tutorials

Hands-on guides to help you get started with Headlamp development.

Available Tutorial Series

🔌 [Plugin Development](./plugin-development)

A comprehensive tutorial series that takes you from beginner to building production-ready Headlamp plugins.

What you'll build:

  • A feature-rich hello-headlamp plugin with sidebar, pages, settings, themes, and map visualization
  • A complete KEDA plugin showcasing CRD integration, resource relationships, and best practices

More tutorial series coming soon (e.g., Deploying Headlamp in-cluster with OIDC)


Development I18n Index (`docs/development/i18n/index.md`)


title: i18n Internationalization / Localization sidebar_label: Internationalization sidebar_position: 5

Headlamp's internationalization uses the i18next, i18next-parser, and
react-i18next libraries.

Default language, and locales

We started with an international English and that will be the fallback language.

Now we're starting with locales familiar to us and will accept
translations through GitHub.

Browser based language detection

We use
i18next-browser-languagedetector

This can select the browser language through various means like through
cookies or the html language tag.

One way to change the locale is to use ?lng=en in the URL.

Lazy load locale files

Dynamic imports and the webpack code splitting feature we
load locale files from src/i18n/locales/{{lng}}/{{ns}}.json
where {{lng}} is the language code, and {{ns}} is the namespace.


Development Plugins Getting Started (`docs/development/plugins/getting-started.md`)


title: Getting Started with Plugin Development sidebar_label: Getting Started sidebar_position: 1

Getting Started with Plugin Development

This guide will walk you through creating your first Headlamp plugin from start to finish, whether you're a beginner or experienced developer.

What are Headlamp Plugins?

Headlamp plugins are JavaScript/TypeScript modules that extend the functionality of Headlamp's web interface. Plugins can:

  • Add custom components to various parts of the UI (app bar, sidebar, details views)
  • Create new routes and pages
  • Customize how Kubernetes resources are displayed
  • Add new themes and branding
  • Integrate with external tools and services
  • Provide custom settings and configuration options
  • Setting up tokens for clusters, so users do not have to manually enter them
  • Customize how and what columns of lists/tables are displayed

Prerequisites

Before starting plugin development, ensure you have:

  • Node.js (v22.0.0 or later) - Download here
  • npm (v11.0.0 or later) - npm is typically installed with Node.js, but may require a separate upgrade
  • A running Headlamp instance - Either the desktop app or development setup
  • Basic knowledge of JavaScript/TypeScript and React

Quick Start: Your First Plugin

Let's create a simple plugin that displays "Hello Headlamp!" in the top navigation bar.

Step 1: Create the Plugin

Run the following command to scaffold a new plugin using the headlamp-plugin
tool. This command should be run where your plugin project (code) will live, typically in a dedicated projects directory (do not run this in Headlamp's
plugin installation directory).

bash
# Create a new plugin
npx --yes @kinvolk/headlamp-plugin create my-first-plugin

# Navigate to the plugin directory
cd my-first-plugin

# Install dependencies
npm install

Step 2: Understand the Plugin Structure

Your new plugin will have this structure:

text
my-first-plugin/
├── src/
│   └── index.tsx         # Main plugin entry point
├── package.json          # Plugin metadata and dependencies
├── tsconfig.json         # TypeScript configuration
├── dist/                 # Built plugin files (created after build)
└── README.md             # Plugin documentation

Step 3: Examine the Default Code

Open src/index.tsx to see the default plugin code:

tsx
import { registerAppBarAction } from '@kinvolk/headlamp-plugin/lib';

// Below are some imports you may want to use.
//   See README.md for links to plugin development documentation.
// import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
// import { K8s } from '@kinvolk/headlamp-plugin/lib/K8s';
// import { Typography } from '@mui/material';

registerAppBarAction(<span>Hello</span>);

Step 4: Start Development Mode

bash
npm run start

This command:

  • Makes the plugin available to Headlamp
  • Watches file changes to automatically rebuild the plugin

When using a packaged Headlamp Desktop app, open Settings > Plugins. Under
the Installed Plugins list, expand Advanced and enable Load development
plugins
. Packaged apps do not load plugins from the
local development directory by default. Only enable this setting when you trust
every plugin in that directory.

Step 5: See Your Plugin in Action

  1. Desktop App: Open Headlamp Desktop after enabling Load development plugins
    under Advanced in Settings > Plugins; or
  2. Run Headlamp in development mode: Start the Headlamp development server (see development guide).

You should see "Hello" text in the top navigation bar!

Step 6: Make Your First Change

Let's create a more interactive component. Replace the content of src/index.tsx:

tsx
import { registerAppBarAction } from '@kinvolk/headlamp-plugin/lib';
import { Button } from '@mui/material';

function HelloButton() {
  const handleClick = () => {
    alert('Hello from your Headlamp plugin!');
  };

  return (
    <Button
      variant="outlined"
      size="small"
      onClick={handleClick}
      sx={{ mx: 2 }} // Add some horizontal margin
    >
      Hello Headlamp!
    </Button>
  );
}

registerAppBarAction(<HelloButton />);

Save the file and watch Headlamp automatically reload with your changes!

TypeScript versions

Generated plugins use TypeScript 5.6.2 by default. You can opt into stable TypeScript 7
for headlamp-plugin tsc while keeping a legacy compiler API for ESLint,
Storybook, and translation extraction.

This setup requires a headlamp-plugin release containing the TypeScript 7
opt-in support described here; it is not available in the published 0.14.0 tooling.

  1. Add these development dependencies to your plugin's package.json:

    json
    {
      "devDependencies": {
        "@typescript/native": "npm:typescript@^7.0.2",
        "typescript": "npm:@typescript/typescript6@^6.0.2"
      }
    }

    Keep your existing dependencies, including @kinvolk/headlamp-plugin.

  2. Remove only the typescript entry from the root overrides object.
    Do not override every TypeScript dependency to version 7: tools importing
    typescript still need the legacy JavaScript compiler API.

  3. Refresh the lockfile and verify a clean install:

    bash
    npm install
    npm ci
    npm run lint
    npm run tsc

When @typescript/native is declared in dependencies or devDependencies,
headlamp-plugin tsc runs that package's installed compiler directly. A missing,
broken, prerelease, or non-7 compiler produces an error instead of falling back
to a legacy compiler. Projects without this dependency keep their existing checker.
The compatibility package provides tsc6; the native package provides tsc, so
those executables do not conflict.

You can check the two compiler versions with:

bash
node node_modules/@typescript/native/bin/tsc --version
node -p "require('typescript').version"

The compatibility checks use Node 24/npm 11, TypeScript 7.0.2,
@typescript/typescript6 6.0.2, and typescript-eslint 8.72.0 or newer.
The compatibility package resolves a TypeScript 6 compiler; individual tools may
also retain a supported nested TypeScript 5 dependency. This is TypeScript 7
checking alongside legacy tooling
, not native TypeScript 7 support throughout
the toolchain. Syntax that legacy parsers cannot handle is not covered.

Prefer Headlamp's public exports, such as useTranslation from
@kinvolk/headlamp-plugin/lib. If you import another library directly, declare it
as a dependency rather than relying on a transitive package being hoisted.

headlamp-plugin upgrade preserves this opt-in by leaving out the template's
TypeScript override. Its existing behavior for other overrides is unchanged:
it replaces them with the template values rather than merging custom entries.

Understanding Plugin Development

Core Concepts

1. Plugin Registry

The plugin registry is the central system that manages all plugin functionality. Import functions from @kinvolk/headlamp-plugin/lib to register your functionality. For example:

tsx
import {
  registerAppBarAction,
  registerRoute,
  registerSidebarEntry,
  registerDetailsViewSection,
} from '@kinvolk/headlamp-plugin/lib';

2. Shared Dependencies

Headlamp provides common libraries that plugins can use without bundling them:

  • React & React DOM - For building UI components
  • React Router - For navigation and routing
  • Redux - For state management
  • Material-UI (@mui/material) - UI component library
  • Material-UI Lab (@mui/lab) - Additional Material-UI components
  • Lodash - Utility functions
  • Iconify - Icon library
  • Notistack - Snackbar notifications
  • Monaco Editor - Code editor component
  • @iconify/react - Icon components

I.e., even though these components can be imported by the plugin as normal in its
code, they are not bundled with the plugin. Instead, they are provided by Headlamp itself. This means there is no need to add them as dependencies in your plugin's package.json.

3. Kubernetes API Access

Access Kubernetes resources using the built-in K8s module:

tsx
import { K8s } from '@kinvolk/headlamp-plugin/lib';

function PodList() {
  const [pods, error] = K8s.ResourceClasses.Pod.useList();

  if (error) return <div>Error loading pods</div>;
  if (!pods) return <div>Loading...</div>;

  return (
    <div>
      <h3>Pods ({pods.length})</h3>
      {pods.map(pod => (
        <div key={pod.metadata.uid}>{pod.metadata.name}</div>
      ))}
    </div>
  );
}

Development Workflow

1. Development Mode

Always use npm run start during development for:

  • Automatic rebuilding
  • Hot reloading
  • Real-time error checking

2. Code Quality Tools

Your plugin comes with built-in quality tools:

bash
# Format code
npm run format

# Check for linting issues
npm run lint

# Fix auto-fixable linting issues
npm run lint-fix

# Type checking
npm run tsc

# Run tests
npm run test

3. Building for Production

When ready to deploy:

bash
npm run build
npm run package

This will create a tarball archive that can be then extracted into the
Headlamp plugins directory.

bash
# Created tarball: "/tmp/my-first-plugin/my-first-plugin-0.1.0.tar.gz".
# Tarball checksum (sha256): c45397ff5f8fac563c2b85a18c0dbbe732017bed71b24bf852b809911993be6f

Next Steps

Now that you've created your first plugin, explore these advanced topics:

  1. Common Patterns - Learn best practices and reusable patterns for plugin development
  2. Example Plugins - Learn from real-world examples
  3. Plugin Functionality - Complete reference of available APIs
  4. Building & Shipping - Production deployment strategies
  5. Publishing Plugins - Share your plugins with the community

Troubleshooting

Plugin Not Loading

  • Ensure Headlamp is running and accessible
  • Check the browser console for JavaScript errors
  • Verify your plugin's package.json has correct metadata
  • Make sure you're running npm run start in the plugin directory

Plugin's Changes Not Reflecting

  • Ensure you saved your changes
  • Check if the development server is running (npm run start) without errors
  • Remove the installed plugin from Headlamp's plugins folder (see plugin locations) and re-run npm run start
  • Restart Headlamp if necessary

Build Errors

  • Run npm run lint to check for code issues
  • Ensure all imports are correct
  • Check TypeScript errors with npm run tsc

Hot Reloading Issues

  • Restart the development server (npm run start)
  • Make sure you do not have several Headlamp tabs in case you are running
    in development mode
  • Clear browser cache
  • Check file permissions in the plugin directory

Getting Help


Development Plugins Index (`docs/development/plugins/index.md`)


title: Plugins sidebar_position: 6

Headlamp Plugins

Plugins are one of the key features of Headlamp, enabling you to customize and extend the Kubernetes web interface to meet your specific needs. The plugin system allows vendors and developers to add functionality without maintaining a fork of the project.

What Can Plugins Do?

Headlamp plugins can transform your Kubernetes experience by:

  • 🎨 Customizing the UI: Add components to the app bar, sidebar, and resource detail views
  • 📊 Creating Dashboards: Build custom pages with specialized visualizations and metrics
  • 🔗 Integrating External Tools: Connect with monitoring, CI/CD, and other systems
  • ⚙️ Adding Business Logic: Implement organization-specific workflows and automation
  • 🎭 Theming & Branding: Apply custom themes and replace logos to match your brand
  • 📈 Enhancing Resource Views: Add custom sections and actions to Kubernetes resource pages

Quick Start Guide

New to plugin development? Follow our step-by-step guide:

🏗️ [Plugin Architecture](../architecture.md)

Understand how plugins work, where they're loaded from, and how they integrate with Headlamp.

📚 [Getting Started With Plugin Development](./getting-started.md)

Complete tutorial from installation to your first working plugin, with practical examples and troubleshooting tips.

🛠️ [Building & Shipping Plugins](./building.md)

Learn the development workflow, production builds, and deployment strategies.

🔐 [Desktop Command Capabilities](./command-capabilities.md)

Configure product-owned command grants for verified plugins.

[Desktop Cluster Registration Providers](./cluster-registration-providers.md)

Add capability-protected native credential providers for desktop products.

📖 [Common Patterns](./common-patterns.md)

Ready-to-use examples for typical plugin scenarios like dashboards, resource extensions, and external integrations.

🎯 [Plugin Functionality Reference](./functionality/index.md)

Comprehensive API documentation covering all available plugin capabilities.

🚀 [Publishing Plugins](./publishing.md)

Share your plugins with the community through Artifact Hub.

🌍 [Internationalization](./i18n.md)

Add support for multiple languages and locales

Ready to Start?

👉 New to plugins? Start with our Getting Started Guide

👉 Want to see examples? Check out Common Patterns

👉 Ready to build? Jump into Building & Shipping

👉 Need architectural details? Read about Plugin Architecture

The Headlamp plugin ecosystem is growing rapidly. Whether you're building internal tools or creating plugins for the community, you're contributing to making Kubernetes more accessible and powerful for everyone!


Installation Desktop Index (`docs/installation/desktop/index.mdx`)


title: Desktop App sidebar_position: 2

Headlamp can be run as a desktop application for users who do not want to
deploy it in-cluster or those who want to manage unrelated clusters locally.

There are desktop apps for Linux, Mac, and Windows.

:::warning
IMPORTANT (UNSIGNED APPS): After the move under the Kubernetes SIG UI, we are still finishing some last details on how to sign new releases under Kubernetes/CNCF.

This means the Windows version is not signed/notarized as before and the OS will try to block the app from running.

You can still run the app on Windows: When the OS warns you that the application is not signed, choose "More > Run Anyway".

Once we have a way to sign the apps, we will re-upload the assets.
We appreciate your patience while we solve this issue.
:::

Please check the following guides for the installation in your desired platform.

import DocCardList from '@theme/DocCardList';

Use a non-default kube config file

If you wish to use a non-default kubeconfig file, then you can do it by
providing it as an argument to Headlamp, e.g.:

bash
/path/to/headlamp /my/different/kubeconfig

or by using an environment variable:

bash
KUBECONFIG=/my/different/kubeconfig /path/to/headlamp

Use several kube config files

If you need to use more than one kubeconfig file at the same time, you can list
each config file path with a separator.

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

```bash KUBECONFIG=kubeconfig1:kubeconfig2:kubeconfig3 /path/to/headlamp ``` ```powershell KUBECONFIG=kubeconfig1;kubeconfig2;kubeconfig3 /path/to/headlamp ```

Access using OIDC

OIDC has a useful feature for
running Headlamp in a cluster. It allows cluster operators to just
give users a URL that they can use to log in and access Headlamp.
If your kubeconfig is set to use OIDC for authentication (you have already
authenticated and produced a kubeconfig), Headlamp will read those settings. It
will then try to use them to offer effortless login to the cluster.

Still, the kube config OIDC settings will not provide a OIDC callback URL. Make sure that your OIDC configuration for your cluster includes Headlamp's OIDC callback in its redirect URIs. I.e., say you're using
Dex for the OIDC connection and you have it already configured in your
kubeconfig. Then, be sure to add the /oidc-callback endpoint with Headlamp's local address
to Dex's staticClient.redirectURIs: http://localhost:6644/oidc-callback.


Installation In Cluster Index (`docs/installation/in-cluster/index.md`)


title: In-cluster sidebar_position: 1

A common use case for any Kubernetes web UI is to deploy it in-cluster and
set up an ingress server for having it available to users.

Using Helm

The easiest way to install headlamp in your existing cluster is to
use helm with our helm chart.

bash
# first add our custom repo to your local helm repositories
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/

# now you should be able to install headlamp via helm
helm install my-headlamp headlamp/headlamp --namespace kube-system

As usual, it is possible to configure the helm release via the values file or setting your preferred values directly.

bash
# install headlamp with your own values.yaml
helm install my-headlamp headlamp/headlamp --namespace kube-system -f values.yaml

# install headlamp by setting your values directly
helm install my-headlamp headlamp/headlamp --namespace kube-system --set replicaCount=2

Cluster Inventory

Cluster Inventory lets a shared Headlamp deployment discover clusters from
ClusterProfile resources. Each user signs in through Headlamp's OIDC provider;
the discovered Kubernetes API server validates that user's token and applies
that user's RBAC permissions.

yaml
config:
  oidc:
    clientID: headlamp
    clientSecret: your-client-secret
    issuerURL: https://idp.example.com
    scopes: profile,email,offline_access
  clusterInventory:
    enabled: true
    namespaces:
      - inventory-team-a
      - inventory-team-b

All discovered clusters' API servers must trust the same OIDC issuer and client
as Headlamp. offline_access enables refresh tokens when the identity provider
requires that scope. Enabling Inventory without an OIDC client ID and issuer is
an error. Inventory remains an experimental/alpha feature and is disabled by
default.

Connection Credential used Required permission
Headlamp reads ClusterProfiles on the inventory root Pod service account Get, list, and watch ClusterProfiles in the watched namespaces
A user opens a discovered cluster That user's OIDC token RBAC granted to that user on the discovered cluster

Without an explicit namespace list, Headlamp watches its pod namespace. Set
namespaces: ["*"] to watch all namespaces with equivalent cluster-wide
ClusterProfile access; * cannot be combined with named namespaces. The default
label selector excludes profiles carrying headlamp.dev/ignore.

Each valid status.accessProviders entry becomes a selectable connection, with
-<access-provider-name> appended to its context name. Its cluster supplies the
HTTPS endpoint, inline CA data, TLS settings, and proxy URL. Invalid entries are
excluded independently. Provider names do not select credentials.
Headlamp does not execute access-provider plugins or read cluster credentials
from Inventory. The Helm chart ignores the former defaults
accessProvidersConfig: {} and plugins: [] and rejects nonempty settings under
either key. The --cluster-inventory-provider-file flag returns an error.

Cluster API

Set config.clusterAPI.enabled: true to discover v1beta2 Cluster API workloads
using the same OIDC configuration as Cluster Inventory. For example:

yaml
config:
  clusterAPI:
    enabled: true
    namespaces: [workload-team-a]

Headlamp reads each Cluster and its <cluster>-kubeconfig Secret in the same
namespace for connection and TLS information. It uses each signed-in user's OIDC
identity, without using credentials in that Secret for workload access.
The management identity needs get, list, and watch on clusters in
cluster.x-k8s.io and core secrets in the selected namespaces.
See Cluster API discovery for the Secret
contract and supported settings.

Namespace discovery for namespace-scoped users

Users who may not list namespaces (for example OIDC users with only
namespace-scoped RoleBindings) otherwise see empty lists until they configure
Settings > Allowed namespaces by hand. With namespace discovery enabled,
Headlamp finds the namespaces they can work in:

yaml
config:
  extraArgs:
    - -enable-namespace-discovery

How it works:

  • The Headlamp service account lists the namespace names. This is the only
    request made with the service account, so it needs list on namespaces
    (the chart's default cluster-admin binding covers that).
  • For each namespace, Headlamp sends a SelfSubjectAccessReview with the
    user's own token
    . A namespace is shown when the user may get that
    namespace or list pods, deployments, services or configmaps there. Users
    therefore only see the names of namespaces they can already access, and the
    decision comes from the API server's authorizers (RBAC, webhooks such as EKS
    access entries, ...).
  • Users who may list namespaces are not affected. Results are cached for one
    minute per user, and the UI refreshes them every minute and after every
    login, logout or token change.
  • Namespaces configured in Settings > Allowed namespaces (manual list or
    label selector) take precedence over discovered namespaces.

The flag only works with -in-cluster, and only for the in-cluster context.

One discovery run needs up to 5 access reviews per namespace the user cannot
access. With the defaults (-namespace-discovery-qps=100,
-namespace-discovery-timeout=30s) that covers roughly 600 namespaces. For
larger clusters raise either value, for example:

yaml
config:
  extraArgs:
    - -enable-namespace-discovery
    - -namespace-discovery-qps=300

When a run hits the time limit, Headlamp logs a warning and the UI falls back
to the behaviour without discovery.

Using simple yaml

We also maintain a simple/vanilla file
for setting up a Headlamp deployment and service. Be sure to review it and change
anything you need.

If you're happy with the options in this deployment file, and assuming
you have a running Kubernetes cluster and your kubeconfig pointing to it,
you can run:

bash
kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/headlamp/main/kubernetes-headlamp.yaml

Optional TLS Backend Termination

Headlamp supports optional TLS termination at the backend server. The default is to terminate at the ingress (default) or optionally directly at the Headlamp container. This enables use cases such as NGINX TLS passthrough and transport server. See tls for details and usage.

Use a non-default kube config file

When Headlamp runs with the -in-cluster flag (the default for the Helm chart
and the sample deployment YAML), it automatically creates a cluster context
named main from the pod's service account. This context exists only in
memory: no kubeconfig file is written to the pod's filesystem. You do not need
to provide, generate, or mount any kubeconfig file for Headlamp to access the
cluster it is running in.

Mounting extra kubeconfig files is only needed if you want Headlamp to show
additional clusters besides the one it is deployed to.

:::note
In in-cluster mode, the KUBECONFIG environment variable is ignored. To point
Headlamp at kubeconfig files, either mount them at the default location shown
below, pass the -kubeconfig argument, or set the HEADLAMP_CONFIG_KUBECONFIG
environment variable. Kubeconfig files are read when the server starts, so
restart the pod after changing them.
:::

First, store the kubeconfig for the extra cluster(s) in a Secret. The examples
below assume Headlamp is installed in the kube-system namespace:

bash
kubectl create secret generic headlamp-kubeconfig \
  --from-file=config=./my-kubeconfig \
  --namespace kube-system

Option 1: Mount the kubeconfig at the default location

Headlamp loads a kubeconfig file from
/home/headlamp/.config/Headlamp/kubeconfigs/config at startup. Mount the
Secret at that directory with these Helm values (the key inside the Secret
must be named config):

yaml
volumeMounts:
  - name: kubeconfig
    mountPath: /home/headlamp/.config/Headlamp/kubeconfigs
    readOnly: true
volumes:
  - name: kubeconfig
    secret:
      secretName: headlamp-kubeconfig
bash
helm install my-headlamp headlamp/headlamp --namespace kube-system -f values.yaml

Option 2: Mount the kubeconfig anywhere and use the -kubeconfig argument

If you prefer an explicit path, mount the Secret wherever you like and pass
the path with the -kubeconfig argument through config.extraArgs:

yaml
config:
  extraArgs:
    - -kubeconfig=/headlamp/kubeconfig/config
volumeMounts:
  - name: kubeconfig
    mountPath: /headlamp/kubeconfig
    readOnly: true
volumes:
  - name: kubeconfig
    secret:
      secretName: headlamp-kubeconfig

Use several kubeconfig files

If you need to use more than one kubeconfig file at the same time, you can
list each file path with a ":" separator in the -kubeconfig argument:

yaml
config:
  extraArgs:
    - -kubeconfig=/headlamp/kubeconfig/cluster-a:/headlamp/kubeconfig/cluster-b
volumeMounts:
  - name: kubeconfig
    mountPath: /headlamp/kubeconfig
    readOnly: true
volumes:
  - name: kubeconfig
    secret:
      secretName: headlamp-kubeconfig

with a Secret that contains one key per kubeconfig file:

bash
kubectl create secret generic headlamp-kubeconfig \
  --from-file=cluster-a=./cluster-a-kubeconfig \
  --from-file=cluster-b=./cluster-b-kubeconfig \
  --namespace kube-system

Using plain YAML instead of Helm

If you deploy Headlamp with a plain manifest (like
kubernetes-headlamp.yaml),
apply the same idea directly on the Deployment:

yaml
spec:
  template:
    spec:
      containers:
        - name: headlamp
          image: ghcr.io/headlamp-k8s/headlamp:latest
          args:
            - "-in-cluster"
            - "-plugins-dir=/headlamp/plugins"
            - "-kubeconfig=/headlamp/kubeconfig/config"
          volumeMounts:
            - name: kubeconfig
              mountPath: /headlamp/kubeconfig
              readOnly: true
      volumes:
        - name: kubeconfig
          secret:
            secretName: headlamp-kubeconfig

Exposing Headlamp with an ingress server

With the instructions in the previous section, the Headlamp service should be
running, but you still need the
ingress server as mentioned. We provide a sample ingress YAML file
for this purpose, but you have to manually replace the URL placeholder
with the desired URL. The ingress file also assumes that you have Contour
and a cert-manager set up, but if you don't, then you'll just not have TLS.

Assuming your URL is headlamp.mydeployment.io, getting the sample ingress
file and changing the URL can quickly be done by:

bash
curl -s https://raw.githubusercontent.com/kubernetes-sigs/headlamp/main/kubernetes-headlamp-ingress-sample.yaml | sed -e s/__URL__/headlamp.mydeployment.io/ > headlamp-ingress.yaml

and with that, you'll have a configured ingress file, so verify it and apply it:

bash
kubectl apply -f ./headlamp-ingress.yaml

Exposing Headlamp with port-forwarding

If you want to quickly access Headlamp (after having its service running) and
don't want to set up an ingress for it, you can run use port-forwarding as follows:

bash
kubectl port-forward -n kube-system service/headlamp 8080:80

and then you can access localhost:8080 in your browser.

Accessing Headlamp

Once Headlamp is up and running, be sure to enable access to it either by creating
a service account or by setting up
OIDC.

Plugin Management

Headlamp supports managing plugins through a sidecar container when deployed in-cluster.

Using values.yaml

You can directly specify the plugin configuration in your values.yaml:

yaml
config:
  watchPlugins: true
pluginsManager:
  enabled: true
  configContent: |
    plugins:
      - name: my-plugin
        source: https://artifacthub.io/packages/headlamp/my-repo/my_plugin
        version: 1.0.0
    installOptions:
      parallel: true
      maxConcurrent: 2
  baseImage: node:lts-alpine
  version: latest

Using a Separate plugin.yml

Alternatively, you can maintain a separate plugin.yml file:

  1. Create a plugin.yml file:
yaml
plugins:
  - name: my-plugin
    source: https://artifacthub.io/packages/headlamp/my-repo/my_plugin
    version: 1.0.0
    # Optional: specify dependencies if needed
    dependencies:
      - another-plugin

installOptions:
  parallel: true
  maxConcurrent: 2
  1. Install/upgrade Headlamp using the plugin configuration:
bash
helm upgrade --install my-headlamp headlamp/headlamp --namespace kube-system -f values.yaml --set pluginsManager.configContent="$(cat plugin.yml)"

Plugin Configuration Format

The plugin configuration supports the following fields:

  • plugins: Array of plugins to install
    • name: Plugin name (required)
    • source: Plugin source URL from Artifact Hub (required)
    • version: Plugin version (required)
    • dependencies: Array of plugin names that this plugin depends on (optional)
  • installOptions:
    • parallel: Whether to install plugins in parallel (default: false)
    • maxConcurrent: Maximum number of concurrent installations when parallel is true

Auto-updating Plugins

Headlamp's plugin manager can automatically watch for changes in the plugin configuration. However, you need to enable watch for these changes in the main headlamp container. This can be enabled through the watchPlugins setting in values.yaml:

yaml
config:
  watchPlugins: true  # Set to true to enable automatic plugin updates in main headlamp container

When enabled, any plugins' changes (either through Helm upgrades or direct ConfigMap updates) wil update in the main headlamp container by enabling --watch-plugins-changes flag on headlamp server.


Learn Devices Index (`docs/learn/devices/index.md`)


title: Devices (alpha) sidebar_position: 10

The Devices (alpha) section shows the objects of Dynamic Resource Allocation (DRA). Use it to see which devices a cluster offers, which device a Pod got, whether that device is healthy, and how many devices are free.

Requirements

  • Kubernetes v1.34 or later, serving the resource.k8s.io/v1 API.
  • A DRA driver installed in the cluster, for example a GPU or network driver.

Headlamp shows the Devices (alpha) section only for clusters that serve resource.k8s.io/v1. Older beta versions of the API are not supported.

Device Classes

A DeviceClass is a kind of device that can be requested, such as "a GPU from this driver". A driver usually creates its classes when it is installed.

The Device Classes list shows, for each class:

  • Selectors: how many selectors the class has. A class without selectors shows All devices.
  • Drivers: the drivers the class passes settings to.
  • Extended Resource: the name a Pod can use to ask for this device in resources.limits, if the class has one.

A class's page shows its Selectors, its Driver Configuration (the settings it passes to each driver), and its extended resource name.

Resource Claims

A ResourceClaim is a request for devices. After scheduling, it records the devices it got.

The Resource Claims list shows each claim's status:

  • Pending: no device is allocated yet.
  • Allocated: a device is picked, but no consumer has reserved the claim yet.
  • In use by N: N consumers, usually Pods, have reserved the claim. A Pod can reserve a claim before it starts.

A claim's page shows:

  • Status and Node: where the claim is, and the node its devices are on.
  • Requests: each request, its device class, and how many devices it asks for.
  • Allocated Devices: each device the claim got, with its pool and driver. If the request listed alternatives, Chosen Alternative shows which one was used.
  • Health: Healthy, Unhealthy, or Unknown, as reported by the kubelet. Hover over the label to see the reason.
  • Used By: the consumers that reserved the claim, usually Pods.

Resource Claim Templates

A ResourceClaimTemplate creates one claim for each Pod that uses it. A template's page shows its Requests and, for each Pod that uses it, the claim it made. If the claim does not exist yet, it shows Not generated yet.

Resource Slices

A ResourceSlice lists the devices a driver offers, grouped into pools. There is no Device object, so a slice is where a device's details live.

The Resource Slices list shows each slice's driver, pool, number of devices, and where the devices can be used:

  • A node name: all devices are on that node.
  • All nodes: the devices can be used from any node.
  • Selected nodes: the devices can be used from nodes that match a node selector.
  • Set per device: each device says where it can be used.

A slice's Devices table shows each device's attributes, such as model, and capacity, such as memory. For a Set per device slice, a Node column shows where each device is. If a driver marks a device with a taint, a Taints column appears. NoSchedule and NoExecute taints prevent allocation to claims that do not tolerate them. A NoExecute taint also evicts Pods whose claims do not tolerate it. A taint with effect None is informational.

A Pod's claims

On a Pod's page, the Resource Claims section lists each claim the Pod uses, where it comes from, and which containers use it. A claim can come from:

  • a ResourceClaim, by name;
  • a ResourceClaimTemplate, shown as Template: and the template name;
  • an Extended resource, when a container asks for a device in resources.limits.

A claim made from a template has a generated name that is only in the Pod's status. Click it to open the claim.

Pool Availability

Pool Availability shows how many devices of a driver are Available, Allocated, and Unavailable, out of the Total, for each pool. The numbers come from the cluster, through a ResourcePoolStatusRequest.

It needs:

  • Kubernetes v1.36 or later with the DRAResourcePoolStatus feature gate enabled for the API server and controller manager, and the resource.k8s.io/v1alpha3 API explicitly enabled on the API server (for example, with --runtime-config=resource.k8s.io/v1alpha3=true).
  • Permission to list ResourceSlices and to create and get ResourcePoolStatusRequests. Delete permission lets Headlamp clean up requests immediately; by default, only cluster admins can create them.

Headlamp shows Pool Availability in the sidebar only for clusters that serve this API.

To open it, select Pool Availability and pick a driver, or click a pool name in the Resource Slices list to filter the results to that pool. Select Show all pools to remove the pool filter, and Refresh to count again. Results are limited to 100 pools; opening a specific pool only filters the returned results and cannot retrieve a pool omitted by this limit.

A pool that the cluster could not count shows Incomplete or Not counted instead of a number. Hover over the label to see the reason. On Kubernetes v1.38 or later, the page says when a driver is still publishing a pool and waits. On earlier versions, the request can stay pending instead. If there is no result after 30 seconds, Headlamp says that the pool may still be publishing or be incomplete.

Map

Open the Map and turn on the Devices (alpha) group. The Map then shows each Pod linked to its claims and templates, and those linked to their DeviceClasses. Pods that only share a DeviceClass are not grouped together.

Troubleshooting

The Devices (alpha) section is missing. Check that the cluster runs Kubernetes v1.34 or later and serves deviceclasses in resource.k8s.io/v1. Also check that Headlamp can reach the cluster and access API discovery; a failed discovery request hides the section.

A list is empty. For device classes and resource slices, check that a DRA driver is installed and running. For resource claims and templates, check the selected namespaces.

Health shows Unknown. Headlamp has no known health report from the Pods using the claim. Check that a Pod uses the claim, that you can read it, and that the driver reports health to the kubelet. Also check that ResourceHealthStatus is enabled on the API server and kubelets; it is disabled by default on Kubernetes v1.34–v1.35.

Pool Availability is missing from the sidebar. Check that Headlamp can reach the cluster and access API discovery; a failed discovery request hides the entry. Then check that the cluster serves resourcepoolstatusrequests in resource.k8s.io/v1alpha3. If it does not, enable the DRAResourcePoolStatus feature gate for the API server and controller manager, and enable the API with --runtime-config=resource.k8s.io/v1alpha3=true.

Pool Availability says you are not allowed. By default, only cluster admins can create ResourcePoolStatusRequests. A role also needs to list ResourceSlices and get the requests it creates.


Learn Local Cluster Index (`docs/learn/local-cluster/index.md`)


title: Local Cluster sidebar_position: 6

This is the Headlamp Local Cluster Setup Guide. If you are interested in learning how to run a cluster locally with Headlamp, then you are at the right place.

Introduction

Kubernetes is powerful, but getting started can be intimidating. Until now, Headlamp required users to bring their own Kubernetes cluster. This meant setting up infrastructure, managing configurations, and often incurring cloud costs. For developers and Kubernetes operators who just want to test an app or learn Kubernetes basics, this setup was a barrier.

With the new Local Cluster feature, Headlamp removes that friction. You can now create and manage a fully functional Kubernetes cluster directly from the Headlamp UI. No terminal, no cloud provider, no YAML required. This makes Kubernetes more accessible than ever, especially for:

  • Developers testing apps before deploying to production
  • Students and learners exploring Kubernetes for the first time

Whether you're deploying a sample app or just curious about how Kubernetes works, Headlamp now gives you a one-click experience to get started locally.

What You're Creating

When you use Headlamp's Local Cluster feature, you're setting up a fully functional Kubernetes cluster on your local machine using Minikube. This cluster behaves just like a remote Kubernetes environment but runs entirely on your desktop, giving you a fast, cost-free, and isolated space to experiment and build.

This cluster is:

  • Self-contained: No need for cloud infrastructure or external services
  • Integrated with Headlamp: Managed entirely through the Headlamp UI
  • Ideal for testing and learning: Quickly deploy apps, inspect resources, and explore Kubernetes features without setup overhead.

Once created, the cluster appears in your Headlamp interface like any other connected cluster. You can start and stop it, deploy applications, view logs, and interact with it using Headlamp's visual tools. It's a great way to:

  • Try out Kubernetes features without risk
  • Explore application behavior and resource configurations
  • Learn how clusters work in a hands-on, visual way

This setup is especially useful for developers who want to iterate quickly, students who are just getting started, or anyone looking to explore Kubernetes without needing a cloud account or command-line expertise.

Key Capabilities

Once your local cluster is up and running, Headlamp provides a rich set of capabilities to help you interact with it visually and intuitively. These features are designed to support learning, experimentation, and lightweight development workflows.

  • Create and delete clusters directly from the Headlamp UI, without needing to use the terminal or write configuration files
  • Deploy applications using built-in tools, including support for manifests and Helm charts
  • View cluster details such as node status, resource usage, and active workloads
  • Start and stop the cluster as needed, giving you control over local resource usage
  • Explore resources like pods, services, deployments, and volumes
    through a visual interface
  • Edit YAML configurations with syntax highlighting and validation
  • Use context actions to quickly view, edit, or remove resources
    from lists
  • Install and use plugins such as Prometheus for metrics or the AI
    Assistant for natural language queries

These capabilities make Headlamp a powerful tool for working with Kubernetes locally, whether you're exploring how things work or building something new.

Getting Started

With these detailed instructions we're going to show how to add a local cluster, deploy something, and then delete the cluster.

Add Local Cluster

Add Local Cluster (Step 1) - Select the Add cluster button

Add Local Cluster (Step 2) - Select the local cluster provider to create a local cluster on your PC

Add Local Cluster (Step 3) - appropriate driver is detected

Depending on the platform (Mac/Windows PC/Linux), different VM drivers are detected on the user's machine.

Note how there is a warning about memory usage? We try to limit the amount of memory allocated to as small as is needed for development and testing needs. For users with low resource laptops, we warn them in case they don't have enough memory as well.

On Windows HyperV can be used which comes built into Windows. On Mac no extra software is required (it gets bundled with vfkit).

Add Local Cluster (Step 4) - Cluster has been created, now go Home to use it

It shows some logs during cluster creation to show what's happening. When it's done we can go to the Overview on the Home to see what's happening in our cluster.

The cluster has been created. How do you access it from the command line? If you use kubectl on the command line you can access your cluster with that. The .kube/config file has been modified with the new cluster added.

shell
kubectl config use-context minikube-1
kubectl get pods

Deploy an Application

Deploy an Application (Step 1) - Apply some YAML

This is a demo web server deployment to copy/paste into Headlamp.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: demo-nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo-nginx
  template:
    metadata:
      labels:
        app: demo-nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

---
apiVersion: v1
kind: Service
metadata:
  name: demo-nginx-service
spec:
  selector:
    app: demo-nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: NodePort

Deploy an Application (Step 2) - See the pod details that it has deployed

Deploy an Application (Step 3) - See the deployment in the browser

Here we see the deployed application in the browser.

Show Cluster Details

Show Cluster Details (Overview)

On the cluster overview page you can see events related to the cluster and CPU and memory, if the pods are running and if the nodes are healthy.

Show Cluster Details (Search for our demo deployment)

You can search for different resources in the Kubernetes cluster. Here we see the search results for the demo deployment we just made.

Delete Cluster

When you want to clean up the cluster you have the option of deleting it, or stopping it to be started up later.

Deleting it frees all the memory and disk used by the cluster, and deletes all resources in the local Kubernetes cluster.

Delete Cluster (Step 1) - select action menu for cluster you want to delete

Delete Cluster (Step 2) - confirm deletion

Starting and stopping clusters

Instead of deleting a cluster, you might want to just stop it instead. This frees up the memory and CPU usage on your laptop, but the disk space is still allocated to the cluster.

Go to the Overview Home page, and you'll see a start and stop button.

Post-Deployment Experience

Once your local cluster is created, it becomes fully integrated into your Headlamp interface. From here, you can begin interacting with it just like you would with any other Kubernetes cluster.

Here's what you'll see and be able to do:

  • The cluster will appear in the Cluster Chooser, allowing you to switch between clusters easily
  • You'll have access to real-time status indicators, showing whether the cluster is running, stopped, or in transition
  • You can start or stop the cluster with a single click, giving you control over your system's resources
  • The resource explorer lets you browse workloads, services, pods, and more using a visual interface
  • You can view and edit YAML configurations directly in Headlamp, with syntax highlighting and validation
  • Context actions are available throughout the UI, allowing you to quickly inspect, modify, or remove resources

This experience is designed to be intuitive and responsive, making it easy to explore Kubernetes concepts, troubleshoot deployments, and iterate on your work without leaving the Headlamp UI.

What You Can Do Next

With your local cluster running, you can begin exploring Kubernetes in a hands-on way. Headlamp makes it easy to:

  • Familiarize yourself with core concepts like pods, services, and deployments
  • Experiment with resource configurations using the YAML editor
  • Deploy sample applications to observe behavior and structure
  • Monitor activity and resource usage through visual tools
  • Extend your environment with plugins for metrics and insights

This is a safe space to learn, explore, and build without needing cloud infrastructure or command line tools.

See relationships between resources with the map view

Experiment with resource configurations using the YAML editor

Extend your environment with plugins for metrics and insights

Ask the AI assistant

Roadmap

Headlamp Local is growing to support more flexible and complete local Kubernetes experiences. Upcoming improvements include:

  • Support for Windows nodes, enabling local testing across operating systems
  • Resource presets for faster cluster setup based on common development needs

FAQ

  • How much system resource does the local cluster use?
    • By default, the local cluster uses approximately 3 GB of memory
      and 20 GB of disk space.
  • Can I run multiple clusters at once?
    • Yes, you can run multiple clusters simultaneously.
  • What if Minikube fails to start?
    • Headlamp provides error messages with details and suggestions.
      If one driver fails, you can try another supported option such
      as Docker, VirtualBox, or Hyper-V depending on your operating
      system.
  • Where can I get help or report issues?

Tutorials Plugin Development Index (`docs/tutorials/plugin-development/index.mdx`)


title: Plugin Development Tutorials sidebar_label: Plugin Development sidebar_position: 1

Plugin Development Tutorials

Welcome to the Headlamp plugin development tutorial series! This hands-on guide takes you from zero to building production-ready plugins.

Learning Path

🚀 [Getting Started](./getting-started/) — Build Your First Plugin

Learn the fundamentals by building a complete hello-headlamp plugin:

# Tutorial Time What You'll Learn
1 Running Headlamp from Source 20 min Set up your development environment
2 Creating Your First Plugin 15 min "Hello" in app bar
3 Adding Pages and Sidebar Navigation 25 min Custom pages & sidebar navigation
4 Working with Kubernetes Data 25 min Fetch cluster and resource data
5 Advanced Kubernetes Interactions 30 min Custom resource classes, modify resources
6 Building List & Detail Pages 30 min ResourceListView & DetailsGrid components
7 Extending Existing Resource Views 25 min Extend built-in resource list and detail views
8 Adding Plugin Settings 20 min ConfigStore, registerPluginSettings, settings UI
9 Applying Custom Themes 20 min registerAppTheme, AppTheme options, light & dark variants
10 Adding Custom Map Nodes 20 min registerMapSource, node icons, custom detail views
11 Releasing & Publishing 30 min Lint, format, build, package, Artifact Hub

Prerequisites

Before starting, ensure you have:

  • Node.js ≥20.11.1 — Download here
  • npm ≥10.0.0 — Comes with Node.js
  • Git — For cloning repositories
  • A code editor — VS Code recommended

🔍 [WhoAmI Plugin](./whoami-plugin/) — Solve a Real Problem

Apply your fundamentals knowledge to build a focused, single-purpose plugin:

Tutorial Time What You'll Learn
Building a WhoAmI Plugin 20 min Sidebar under Cluster, SelfSubjectReview API, identity display

Ready to Start?

👉 New to Headlamp? Start with Getting Started

👉 Finished Getting Started? Try the WhoAmI Plugin to apply your skills

Additional Resources


Development Plugins Functionality Index (`docs/development/plugins/functionality/index.md`)


title: Plugins Functionality sidebar_label: Functionality sidebar_position: 3

Headlamp's plugins exist to change or add functionality related to
the user interface and experience.

Plugins Lib

The @kinvolk/headlamp-plugin module provides a library
(@kinvolk/headlamp-plugin/lib) with Headlamp development modules.

The main ones are:

  • K8s: Kubernetes functionality.
  • Headlamp: To register plugins.
  • CommonComponents: Commonly used React components in the Headlamp UI.
  • Notification: This module exports two members: Notification and setNotificationsInStore.
    The Notification class creates notifications. The setNotificationsInStore
    function sends the notification to Headlamp to be displayed.
  • Router: To get or generate routes.

Shared Modules

Headlamp shares many npm modules with plugins. It includes VSCode configuration
files to find them.

The canonical list lives in
frontend/src/plugin/index.ts,
where window.pluginLib is assembled. At the time of writing, the shared
third-party modules are:

  • react
  • react-dom
  • @iconify/react
  • react-redux
  • react-router-dom
  • @mui/material (also exposed as MuiCore for backwards compatibility)
  • @mui/lab
  • @mui/styles (only makeStyles is exposed, as an alias of @mui/system's
    styled; this is not API-compatible with the original JSS makeStyles hook)
  • @monaco-editor/react
  • monaco-editor
  • lodash
  • notistack
  • recharts

This means that plugins only need to install dependencies not already in Headlamp. If a plugin
installs a dependency that Headlamp already has, make sure the versions are the
same. The build process will not bundle these shared modules. Instead, they are
replaced by the version in the pluginLib global object.

Older guides suggested using const React: window.pluginLib.React to access
React. This is no longer needed.

Functionality

The plugin registry makes functionality available to plugins.

The goal is to make more functionality available to plugins. Here is what we
have so far:

Translations outside React

Use getPluginTranslation from @kinvolk/headlamp-plugin/lib when commands,
notifications or callbacks need translated text but cannot call the
useTranslation hook. Pass the plugin's package name. The promise resolves after
Headlamp's current language is loaded, and the returned translation function keeps
following later language changes.

ts
import { getPluginTranslation } from '@kinvolk/headlamp-plugin/lib';

async function failedMessage(clusterName: string) {
  const t = await getPluginTranslation('my-plugin');
  return t('Could not connect to {{name}}', { name: clusterName });
}

Call the function when the text is needed rather than while the plugin is loading;
Headlamp registers plugin translations after plugins have run. Configure the
plugin's supported locales as described in the i18n guide.

App Bar Action

Show a component in the top right of the app bar with
registerAppBarAction.

Change the logo in the top left with
registerAppLogo.

App Menus

Add menus when Headlamp runs as an app with
Headlamp.setAppMenu.

Cluster Chooser

Change the Cluster Chooser button in the top right of the app bar with
registerClusterChooser.

Cluster Delete Handlers

A plugin that manages a cluster's lifecycle can take over Delete in the Home
page's cluster action menu with
registerClusterProviderDeleteHandler.
For each cluster the handler's owns function accepts, Delete opens the
plugin's dialog named by dialog, registered with registerClusterProviderDialog,
instead of removing the cluster from the kubeconfig. The first registered
handler that owns a cluster is used; Delete for other clusters behaves as it
does without a handler. A handler is ignored unless owns is a function and
the dialog name is neither empty nor deleteDynamic, the name of Headlamp's own
confirmation.

Cluster Empty State

Customize the Home page shown when no clusters are configured with
registerClusterEmptyState.
The registered component receives Headlamp's standard empty state as
defaultContent. Render it to extend the default onboarding, or omit it to
replace the empty state completely.

Details View Header Action

Show a component in the top right of a detail view with
registerDetailsViewHeaderAction.

Details View Section

Change sections in a Kubernetes resource's details view with
registerDetailsViewSectionsProcessor.
This lets you add, remove, update, or move sections.

Or, add a component to the bottom of a details view with
registerDetailsViewSection.

Dynamic Clusters

Set a cluster dynamically, instead of from a configuration file, with
Headlamp.setCluster.

Secure Storage

Desktop plugins can save small local credentials with the pluginSecureStorage
argument that Headlamp injects when it runs the plugin. Values are encrypted by
Electron safeStorage and scoped to the plugin's trusted installation identity.
The plugin chooses only a key within its own storage area; it cannot choose or
name another plugin's namespace.

Declare the injected argument in TypeScript and check every operation result:

ts
interface PluginSecureStorage {
  save(key: string, value: string): Promise<{ success: boolean; error?: string }>;
  load(key: string): Promise<{ success: boolean; value?: string | null; error?: string }>;
  delete(key: string): Promise<{ success: boolean; error?: string }>;
}

declare const pluginSecureStorage: PluginSecureStorage;

const saved = await pluginSecureStorage.save('oauth-token', token);
if (!saved.success) {
  throw new Error(saved.error);
}

const loaded = await pluginSecureStorage.load('oauth-token');
if (!loaded.success) {
  throw new Error(loaded.error);
}
const tokenOrNull = loaded.value ?? null;

const deleted = await pluginSecureStorage.delete('oauth-token');
if (!deleted.success) {
  throw new Error(deleted.error);
}

load returns value: null when the key does not exist. A failed operation
returns success: false and an error; plugins should not treat a failure as a
missing value. Headlamp may reject an operation when the operating-system key
store is unavailable, when persisted data cannot be read safely, or when an
input or storage limit is exceeded.

This API is available only in the Headlamp desktop app. Check
Headlamp.isRunningAsApp() before registering UI that uses it. It stores data
on the computer running Headlamp and does not synchronize across computers or
create a Kubernetes Secret. Use the Kubernetes API when a credential needs to
be shared with workloads or other cluster users.

Route

Show a component in the main area at a given URL with
registerRoute.

Add items to the left sidebar with
registerSidebarEntry.
Filter items with
registerSidebarEntryFilter.
Filter items from the home (non-cluster) sidebar with
registerHomeSidebarEntryFilter.
Use entryType: 'subheader' with registerSidebarEntry to add a
non-clickable section header that groups sidebar entries. Subheaders render as
dividers when the sidebar is collapsed. Use sx to override the default
subheader styles.

Tables

Change tables in Headlamp with
registerResourceTableColumnsProcessor.
This lets you add, remove, update, or move table columns.

Project Creation

Add a project creation choice with
registerCustomCreateProject.
To replace one of Headlamp's built-in choices in the same position, use its ID
from DefaultCreateProject:

tsx
import { DefaultCreateProject, registerCustomCreateProject } from '@kinvolk/headlamp-plugin/lib';

registerCustomCreateProject({
  id: DefaultCreateProject.NEW_PROJECT,
  name: 'Create Managed Project',
  description: 'Create a project managed by the platform',
  icon: 'mdi:folder-plus',
  component: ManagedProjectForm,
});

Use DefaultCreateProject.NEW_PROJECT to replace the namespace-based project
form, or DefaultCreateProject.FROM_YAML to replace the YAML creation flow.
Use a unique ID to append another choice without replacing either built-in
choice. The custom component receives an onBack callback for returning to the
project creation menu.

Mobile (375 x 812)

Default choices Plugin replacements

Headlamp Events

Headlamp fires events when something important happens.

React to Headlamp events with
registerHeadlampEventCallback.

Plugin Settings

Plugins can have user settings. Create them with
registerPluginSettings.

App Theme

Add a custom Headlamp theme with
registerAppTheme.
The theme name must be unique. You can specify 'light' or 'dark' as a base.
The default is 'light'.

Check the AppTheme
definition for all customizable properties.

After you register your theme, it will be in the 'Theme' selection in General
Settings.

To select a registered theme on first use, pass { default: true } as the
second argument:

ts
registerAppTheme(
  {
    name: 'My Product Theme',
    base: 'light',
    primary: '#ff0000',
    secondary: '#333333',
  },
  { default: true }
);

Headlamp selects this theme only when the user has no saved theme preference.
An explicit selection in General Settings or an administrator-forced theme
always takes precedence. A plugin default takes precedence over backend light
and dark defaults regardless of whether plugins or backend configuration finish
loading first. See
AppThemeRegistrationOptions
for the registration options.

The terminal/log surfaces (pod logs, exec, node shell) follow the active
theme automatically. To override their colors, set the optional terminal
field on AppTheme — background, foreground, cursor, and a 16-color
ansi palette. Anything you leave out is auto-derived from the surrounding
MUI palette and contrast-clamped to stay readable on the chosen background.
See the custom-theme example
for a working registerAppTheme({ ..., terminal: { ... } }) call.

UI Panels

Register a side panel with
registerUIPanel.
A side panel is a UI element on one side of the application. You can define
more than one panel per side. Each panel needs a unique ID, a side (top, left,
right, bottom), and a React component.

Check the
example plugin
for the full code.

Resource Map Relations

Register a custom relation provider for the Resource Map graph with
registerResourceRelationProvider. This enables plugins to define custom edges
and surface implicit dependencies between resources. Each relation needs a
globally unique id, a fromSource graph source ID, and a predicate that
returns whether two graph nodes should be connected. Use a plugin-prefixed
relation ID to avoid colliding with Headlamp's built-in relations.

tsx
import { registerResourceRelationProvider } from '@kinvolk/headlamp-plugin/lib';

registerResourceRelationProvider({
  id: 'my-plugin.deployment-secret',
  fromSource: 'apps/Deployment',
  toSource: 'Secret',
  label: 'Uses Secret',
  predicate: (from, to) => {
    // predicate receives GraphNode objects; access K8s data via kubeObject.
    return (
      from.kubeObject?.jsonData.metadata.name === 'my-deployment' &&
      to.kubeObject?.jsonData.metadata.name === 'my-secret'
    );
  },
});

registerResourceRelationProvider({
  id: 'my-plugin.custom-source-deployment',
  fromSource: 'my-source',
  toSource: 'apps/Deployment',
  label: 'Depends On',
  predicate: (from, to) => {
    // `my-source` is the ID passed to registerMapSource.
    return (
      from.kubeObject?.jsonData.metadata.name === 'my-test-resource' &&
      to.kubeObject?.jsonData.metadata.name === 'my-deployment'
    );
  },
});

See the
customizing-map example
for a complete relation provider registration.

Projects customization

Customize Headlamp's Projects feature with several registration functions:

Group namespaces into separate project entries with
registerProjectGrouping.
By default, Headlamp combines namespaces with the same project ID across clusters,
which is useful when they form one logical application. Use custom grouping when
clusters represent distinct environments, tenants, or ownership boundaries and
users need separate resource counts, health, and actions for each entry.
The callback receives each namespace and its labelled project ID, and returns an
opaque key. Namespaces with the same project ID and key are shown as one project
entry. Return the project ID to preserve Headlamp's default cross-cluster grouping.

Add custom tabs to the project details view with
registerProjectDetailsTab.
Each tab needs a unique ID, a label, and a React component that receives the project as a prop.

Add custom sections to the project overview page with
registerProjectOverviewSection.
Each section needs a unique id and a component. The component receives the current
project and its loaded projectResources.

Use the optional asynchronous isEnabled callback to display a section only for
matching projects. The callback receives { project } and returns a Promise.
Sections without the callback are displayed by default. A section is hidden when the
callback resolves to false, rejects, or throws, and eligibility is checked again when
the project changes.

tsx
registerProjectOverviewSection({
  id: 'multi-cluster-summary',
  component: ({ project, projectResources }) => (
    <MultiClusterSummary project={project} resources={projectResources} />
  ),
  isEnabled: async ({ project }) => project.clusters.length > 1,
});

Add action buttons to the project details header with
registerProjectHeaderAction.
The action component receives the current project and an optional
setSelectedTab?: (tabId: string) => void callback. Call it with the ID of a
registered, enabled tab to select that tab. Unknown tabs and tabs without a
component are ignored.

tsx
registerProjectHeaderAction({
  id: 'view-metrics',
  component: ({ setSelectedTab }) => (
    <Button onClick={() => setSelectedTab?.('my-plugin.metrics')}>View metrics</Button>
  ),
});

Register custom API resources (e.g. CRDs) for project resource tracking with
registerProjectApiResource.
Once registered, the CRD resources will appear in the project's resource count,
health status, and Resources tab. Only namespaced resources can be registered,
since Projects are scoped to namespaces.

Example plugin: How to customize projects,
including conditionally displayed overview sections.

Activities

Activity is a Headlamp feature that allows you to create resizable popup windows.
For example when you click on a resource (like a Pod or ReplicaSet), the details will open in Activity.

You can create and update Actitivities from plugins using Activity API

Check the example plugin for the full code.


Installation In Cluster Aks Cluster Oauth Index (`docs/installation/in-cluster/aks-cluster-oauth/index.md`)


title: AKS Cluster Setup with Azure Entra Login and RBAC Using OAuth2Proxy sidebar_label: "Tutorial: Headlamp on AKS with Azure Entra-ID Using OAuth2Proxy"

This guide walks you through configuring Headlamp in an AKS cluster using OAuth2Proxy for authentication via Azure Entra ID (Microsoft Entra ID) and RBAC.

We'll cover:

  1. Setting up AKS with OIDC
  2. Creating an Azure App Registration
  3. Deploying Headlamp via Helm
  4. Setting up OAuth2Proxy

Step 1: Set Up AKS Cluster with OIDC Enabled

  1. Go to Kubernetes Services in the Azure portal and click Create Cluster.

  2. In the Authentication and Authorization step:

    • Select Microsoft Entra ID authentication.
    • Enable Kubernetes RBAC.
  3. Under Cluster Admin ClusterRoleBinding, choose an Entra group that should have cluster-admin privileges.

  4. Continue with your preferred settings for the agent pool, networking, etc., and create the cluster.

Make sure to enable OIDC Issuer while creating the cluster.


Step 2: Create an Azure App Registration

  1. In the Azure portal, navigate to Microsoft Entra ID > App registrations.

  2. Click + New registration.

  3. Provide:

    • Name of your choice.
    • Supported account type (usually Accounts in this organizational directory only).
    • Redirect URI: For local testing, you can use:
      text
      http://localhost:8000/oidc-callback
  4. Click Register.

  5. Record the Application (client) ID and Directory (tenant) ID.


Step 3: Configure API Permissions for OAuth2Proxy

  1. Go to API permissions → Add a permission.
  2. Choose Microsoft Graph → Delegated permissions.
  3. Add: openid, profile, email.
  4. Click Grant admin consent.

Step 4: Create a Client Secret for OAuth2Proxy

  1. Go to Certificates & secrets → New client secret.
  2. Add and copy the value.

Step 5: Deploy Headlamp to AKS

Prerequisites:

  • Install Helm
  • Download kubeconfig for the AKS cluster

Add Headlamp Helm repo:

bash
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/
helm repo update

Create a `values.yaml` for any customizations (optional) and deploy:

bash
helm install my-headlamp headlamp/headlamp --namespace kube-system

Verify Headlamp is running:

bash
kubectl get pods -n kube-system

Port-forward to access the UI:

bash
kubectl port-forward svc/my-headlamp 8000:80 -n kube-system

Headlamp should now show an Authentication screen.


Step 6: Deploy OAuth2Proxy via Helm

Add the Helm repo:

bash
helm repo add oauth2-proxy https://oauth2-proxy.github.io/manifests
helm repo update

Prepare your `values.yaml`

Below is an example configuration you can start with. Be sure to replace placeholders like <Client-ID>, <Client-Secret>, <Tenant-ID>, etc.

yaml
config:
  configFile: |-
    email_domains = ["*"]
    cookie_secret = <Cookie-Secret>

alphaConfig:
  enabled: true
  configFile: |-
    injectRequestHeaders:
      - name: Authorization
        values:
          - claim: access_token
            prefix: 'Bearer '
    providers:
      - clientID: <Client-ID>
        clientSecret: <Client-Secret>
        id: entra
        oidcConfig:
          issuerURL: https://login.microsoftonline.com/<Tenant-ID>/v2.0
          audienceClaims:
            - aud
          emailClaim: email
          insecureAllowUnverifiedEmail: true
        provider: oidc
        scope: 6dae42f8-4368-4678-94ff-3960e28e3630/user.read openid email profile User.Read
    upstreamConfig:
      upstreams:
        - id: main
          path: /
          uri: http://<your-headlamp-service-name>.<your-headlamp-namespace>.svc.cluster.local

Deploy OAuth2Proxy:

bash
helm install my-release oauth2-proxy/oauth2-proxy -f values.yaml

Verify it's up:

bash
kubectl get pods

Step 7: Set Kubernetes RBAC Policies Based on Azure Entra Groups

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: read-only-binding
subjects:
- kind: Group
  apiGroup: rbac.authorization.k8s.io
  name: "<AzureEntraGroupObjectID>"
roleRef:
  kind: ClusterRole
  name: view
  apiGroup: rbac.authorization.k8s.io

Apply:

bash
kubectl apply -f your-rbac-binding.yaml

Step 8: Login Flow

  • Navigate to the port-forwarded Headlamp UI.
  • Click Sign in.
  • Follow the Entra login prompt.

Note: In a development environment, OAuth2Proxy may try to redirect to https:// by default. For local testing, ensure your redirect URI and settings use http://.

Once authenticated, you'll be redirected back to Headlamp and should have access to your cluster UI.


Step 9: Test Authentication Flow

  • Access your protected endpoint.
  • Login via Entra.
  • Validate RBAC access.

Installation In Cluster Azure Entra Id Index (`docs/installation/in-cluster/azure-entra-id/index.md`)


title: How to Set Up Headlamp on AKS with Azure Entra-ID as the OIDC provider sidebar_label: "Tutorial: Headlamp on AKS with Azure Entra-ID"

This tutorial is about configuring Headlamp 0.30.1 with:

  1. Azure Entra ID OIDC for OpenID Connect (OIDC) authentication
  2. Azure AKS
  3. Kubernetes v1.31.5

Configure Azure AKS for Entra ID OIDC

The AKS-managed Microsoft Entra integration simplifies the Microsoft Entra integration process. Previously, you were required to create a client and server app, and the Microsoft Entra tenant had to assign Directory Readers role permissions. Now, the AKS resource provider manages the client and server apps for you.

Cluster administrators can configure Kubernetes role-based access control (Kubernetes RBAC) based on a user's identity or directory group membership. Microsoft Entra authentication is provided to AKS clusters with OpenID Connect. OpenID Connect is an identity layer built on top of the OAuth 2.0 protocol. For more information on OpenID Connect, see the OpenID Connect documentation.

The following steps follow the Microsoft reference documentation. See the documentation for relevant limitations, prerequisites, and best practices before continuing.

Creating a new AKS Cluster with EntraID OIDC

  1. Create an Azure resource group using the az group create command.
shell
az group create --name myResourceGroup --location centralus
  1. Create an AKS cluster and enable administration access for your Microsoft Entra group using the az aks create command.
shell
az aks create \
    --resource-group myResourceGroup \
    --name myManagedCluster \
    --enable-aad \
    --aad-admin-group-object-ids <id> [--aad-tenant-id <id>] \
    --generate-ssh-keys

A successful creation of an AKS-managed Microsoft Entra ID cluster has the following section in the response body:

json
"AADProfile": {
    "adminGroupObjectIds": [
    "5d24****-****-****-****-****afa27aed"
    ],
    "clientAppId": null,
    "managed": true,
    "serverAppId": null,
    "serverAppSecret": null,
    "tenantId": "72f9****-****-****-****-****d011db47"
}

Use an existing cluster

Enable AKS-managed Microsoft Entra integration on your existing Kubernetes RBAC enabled cluster using the az aks update command. Make sure to set your admin group to keep access on your cluster.

shell
az aks update --resource-group MyResourceGroup --name myManagedCluster --enable-aad --aad-admin-group-object-ids <id-1>,<id-2> [--aad-tenant-id <id>]

A successful activation of an AKS-managed Microsoft Entra ID cluster has the following section in the response body:

json
"AADProfile": {
    "adminGroupObjectIds": [
        "5d24****-****-****-****-****afa27aed"
    ],
    "clientAppId": null,
    "managed": true,
    "serverAppId": null,
    "serverAppSecret": null,
    "tenantId": "72f9****-****-****-****-****d011db47"
    }

Set up Enterprise App for Headlamp integration

  1. Log in to the Microsoft Azure Portal and choose Microsoft Entra ID from the sidebar or search menu.

  2. Under Manage, select App Registrations.

  3. Select New Registration

  4. Enter a meaningful Name for your, for example headlamp-oidc. App users can see this name, and it can be changed at any time. You can have multiple app registrations with the same name.

  5. Under Supported account types, specify who can use the application. We recommend you select Accounts in this organizational directory only for most applications. Refer to the table for more information on each option.

  6. Under Redirect URI, select the Web platform, and for the purposes of this tutorial, input http://localhost:8000/oidc-callback. For an actual production implementation, you would replace this with the ingress url of your headlamp installation with the /oidc-callback path.

  7. Select Register to complete the app registration.

  8. Once the application is created, browse back to App registrations, locate the created application, and click on it.

  9. To allow users to use this App Registration to auth to AKS, we need to assign delegated permissions for Azure Kubernetes. Select API Permissions from the left hand side, then Add a Permission.

Select APIs my organization uses, then input Azure Kubernetes Service AAD Server and select the resulting permission with the clientID of 6dae42f8-4368-4678-94ff-3960e28e3630 (this will be the same for all users of AKS with EntraID)

Select the corresponding user.read permission, then Add permissions.

  1. Now Select Add a Permission again, Microsoft Graph, Delegated Permissions, and then select the checkboxes next to email, openid, and profile before clicking Add at the bottom.

  2. Select Grant admin consent for <Tenant Name> to finish setting up the permissions.

  3. With this complete, we need to record a few pieces of information used when deploying headlamp. The first two can be obtained from the Overview panel of the App Registration. You will need the Application (client) ID and the Directory (tenant) ID

  4. Lastly, you'll need to generate a ClientSecret for headlamp to use. Select Certificates and secrets from the App Registration menu, then New client secret.

  5. Enter a description and expiry length, then select Add. Now copy the value of the newly generated client secret and record it for the next step.

Setting up Headlamp with EntraID OIDC

Now that we have our cluster configured and our App Registration configured for OIDC auth flows, we need to deploy headlamp.

  1. First make sure you have the Helm package manager installed on your local machine. There is a Helm installation guide if you need to install it.

  2. Your cluster should be running and configured with EntraID.

  3. Create a values.yaml file and add the following OIDC configuration to it:

yaml
config:
  oidc:
    clientID: "<Your Application (client) ID>"
    clientSecret: "<Your Application (client) Secret>"
    issuerURL: "https://login.microsoftonline.com/<Your Directory (tenant) ID>/v2.0"
    scopes: "6dae42f8-4368-4678-94ff-3960e28e3630/user.read,openid,email,profile"
    validatorClientID: "6dae42f8-4368-4678-94ff-3960e28e3630"
    validatorIssuerURL: "https://sts.windows.net/<Your Directory (tenant) ID>/"
    useAccessToken: true

Replace <Your Application (client) ID>,<Your Application (client) Secret>, and <Your Directory (tenant) ID>, with your specific Azure Entra ID app registration details obtained in the steps above.

Note: The scopes string must be comma separated so each scope is passed individually to the OIDC provider.

  1. Save the values.yaml file and Install Headlamp using helm with the following commands:
shell
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/
helm install headlamp-oidc headlamp/headlamp -f values.yaml --namespace=headlamp --create-namespace

This will install Headlamp in the headlamp namespace with the OIDC configuration from the values.yaml file.

  1. After a successful installation, you can access Headlamp by port-forwarding to the pod:

Make sure the port-forwarding is done to the port that you set as the callback URL in the Azure App Registration configuration. So in our case if you followed the steps above, the callback URL is http://localhost:8000/oidc-callback, and we should port forward to 8000.

shell
kubectl port-forward svc/headlamp-oidc 8000:80 -n headlamp
  1. Open your web browser and go to http://localhost:8000. Click on "sign-in." After completing the login flow successfully, you'll gain access to your Kubernetes cluster using Headlamp.

Installation In Cluster Dex Index (`docs/installation/in-cluster/dex/index.md`)


title: Set Up Headlamp behind OAuth2-Proxy with Dex sidebar_label: "Tutorial: OIDC with Dex and OAuth2-Proxy"

This guide places OAuth2-Proxy
in front of Headlamp and uses Dex as the OpenID Connect
(OIDC) provider. OAuth2-Proxy signs users in and forwards their ID token to
Headlamp. Headlamp then uses that token for Kubernetes API requests, so the
API server can apply RBAC to the Dex identity.

This follows the upstream
OAuth2-Proxy Headlamp integration.

Architecture

text
Browser ──► OAuth2-Proxy ──► Dex
                 │
                 │ Authorization: Bearer <ID token>
                 ▼
             Headlamp ──► Kubernetes API server
                              │
                              └─ validates the token against Dex and applies RBAC

Choose a setup

This directory supports two different setups. Do not mix their configuration:

  • Local authentication demo: Run test-scripts/run.sh.
    It uses HTTP and kubectl port-forward. OAuth2-Proxy authenticates users,
    but Headlamp uses its ServiceAccount for Kubernetes requests, so every
    signed-in user has the same Kubernetes permissions. It does not demonstrate
    per-user RBAC.
  • Per-user Kubernetes RBAC: Follow the manual steps below. This requires an
    HTTPS Dex issuer that is reachable from the browser, OAuth2-Proxy, and the
    Kubernetes API server.
Local scripts Manual per-user setup
Transport HTTP and port-forwarding HTTPS and Ingress
Kubernetes identity Headlamp ServiceAccount Dex user and groups
API-server OIDC Disabled Enabled
Intended use Login-flow evaluation Per-user authorization

Both paths use the same Dex client ID, OAuth2-Proxy callback path, Headlamp
upstream, and pinned chart versions. Their transport and Kubernetes identity
intentionally differ.

Prerequisites

  • Minikube 1.31 or newer
  • Helm 3.10 or newer
  • kubectl
  • Dex 2.45.1
  • An Ingress controller (the example uses NGINX)
  • DNS names and TLS certificates trusted by every client that connects to them

The examples below use:

  • Dex issuer: https://dex.example.com:5556
  • Headlamp entry point: https://headlamp.example.com
  • OIDC client ID: headlamp

Use those values consistently. In particular, the Dex issuer, Kubernetes
--oidc-issuer-url, and OAuth2-Proxy oidc_issuer_url must be identical.
dex.example.com must resolve and be reachable from your browser, pods, and the
Minikube control plane. headlamp.example.com must resolve to the Ingress
controller from your browser. Replace these reserved example domains with names
from your environment.

Set shell variables for the commands below:

shell
export DEX_HOST="dex.example.com"
export HEADLAMP_HOST="headlamp.example.com"
export HEADLAMP_TLS_CERT="/absolute/path/to/headlamp-tls.crt"
export HEADLAMP_TLS_KEY="/absolute/path/to/headlamp-tls.key"
export OIDC_CLIENT_SECRET="$(openssl rand -hex 32)"
export COOKIE_SECRET="$(openssl rand -base64 32 | tr '+/' '-_' | tr -d '=')"

Keep these variables in the same shell while following the steps.

1. Configure Dex

Create dex-config.yaml:

yaml title="dex-config.yaml"
issuer: https://dex.example.com:5556

storage:
  type: sqlite3
  config:
    file: ./dex.db

web:
  https: 0.0.0.0:5556
  tlsCert: /absolute/path/to/dex-tls.crt
  tlsKey: /absolute/path/to/dex-tls.key

staticClients:
  - id: headlamp
    name: "Headlamp via OAuth2-Proxy"
    secretEnv: OIDC_CLIENT_SECRET
    redirectURIs:
      - "https://headlamp.example.com/oauth2/callback"

# This static account is for evaluating the setup only. Use an external
# connector and managed identities in production.
enablePasswordDB: true
staticPasswords:
  - email: "[email protected]"
    # bcrypt hash of "password":
    #   echo password | htpasswd -BinC 10 admin | cut -d: -f2
    hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
    username: "admin"
    emailVerified: true
    userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
    groups:
      - "headlamp-readers"

The relative database path keeps this walkthrough runnable as an unprivileged
user. Use persistent, access-controlled storage for a real Dex deployment.
Start Dex with:

shell
dex serve dex-config.yaml

Verify from the machine running your browser that its discovery document is
available and advertises the exact issuer URL:

shell
curl --fail "https://${DEX_HOST}:5556/.well-known/openid-configuration"

2. Configure the Kubernetes API server

Start Minikube with Dex as a trusted issuer:

shell
minikube start -p=dex \
  --extra-config=apiserver.authorization-mode=Node,RBAC \
  --extra-config=apiserver.oidc-issuer-url="https://${DEX_HOST}:5556" \
  --extra-config=apiserver.oidc-username-claim=email \
  --extra-config=apiserver.oidc-groups-claim=groups \
  --extra-config=apiserver.oidc-client-id=headlamp

If Dex uses a private certificate authority, also configure
apiserver.oidc-ca-file and mount that CA file into the Minikube control-plane
container. The certificate must also be trusted by OAuth2-Proxy and your
browser.

Verify that a pod can resolve and trust Dex:

shell
kubectl run dex-connectivity-check \
  --image=curlimages/curl:8.12.1 \
  --restart=Never --rm -i -- \
  --fail "https://${DEX_HOST}:5556/.well-known/openid-configuration"

Resolve DNS or certificate errors before installing OAuth2-Proxy.

3. Grant the test user limited access

For this tutorial, grant the Dex group read-only access. Avoid using
cluster-admin for login examples because copied examples often survive into
real environments.

yaml title="clusterrolebinding.yaml"
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: dex-headlamp-view
subjects:
  - kind: Group
    name: headlamp-readers
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: view
  apiGroup: rbac.authorization.k8s.io
shell
kubectl apply -f clusterrolebinding.yaml

The group name matches the groups claim in dex-config.yaml.

4. Install Headlamp

OAuth2-Proxy handles login, so Headlamp does not need its own OIDC client
configuration. Keep unsafeUseServiceAccountToken disabled; Headlamp must use
the forwarded user token for Kubernetes API requests.

shell
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/
helm repo update
helm install headlamp headlamp/headlamp \
  --version 0.44.0 \
  --namespace headlamp \
  --create-namespace \
  --set config.unsafeUseServiceAccountToken=false

5. Install OAuth2-Proxy

Create oauth2-proxy-values.yaml. The install command below supplies the two
generated secrets without writing them to this file:

yaml title="oauth2-proxy-values.yaml"
config:
  clientID: "headlamp"
  configFile: |-
    provider = "oidc"
    oidc_issuer_url = "https://dex.example.com:5556"
    redirect_url = "https://headlamp.example.com/oauth2/callback"
    email_domains = ["example.com"]
    scope = "openid profile email groups"

    # Forward Dex's ID token to Headlamp. Headlamp uses this header for
    # Kubernetes API requests.
    pass_authorization_header = true

    upstreams = ["http://headlamp.headlamp.svc.cluster.local:80"]
    http_address = "0.0.0.0:4180"
    reverse_proxy = true

Install OAuth2-Proxy:

shell
helm repo add oauth2-proxy https://oauth2-proxy.github.io/manifests
helm repo update
helm install oauth2-proxy oauth2-proxy/oauth2-proxy \
  --version 10.7.0 \
  --namespace headlamp \
  --set-string config.clientSecret="$OIDC_CLIENT_SECRET" \
  --set-string config.cookieSecret="$COOKIE_SECRET" \
  -f oauth2-proxy-values.yaml

Wait for both deployments:

shell
kubectl -n headlamp rollout status deployment/headlamp
kubectl -n headlamp rollout status deployment/oauth2-proxy

6. Expose only OAuth2-Proxy

If this Minikube profile does not already have an Ingress controller, enable
the NGINX addon:

shell
minikube addons enable ingress -p=dex

Create the TLS secret from the certificate for $HEADLAMP_HOST:

shell
kubectl -n headlamp create secret tls headlamp-ingress-tls \
  --cert="$HEADLAMP_TLS_CERT" \
  --key="$HEADLAMP_TLS_KEY"

Create headlamp-ingress.yaml:

yaml title="headlamp-ingress.yaml"
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: headlamp
  namespace: headlamp
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - headlamp.example.com
      secretName: headlamp-ingress-tls
  rules:
    - host: headlamp.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: oauth2-proxy
                port:
                  number: 80
shell
kubectl apply -f headlamp-ingress.yaml

Point $HEADLAMP_HOST at your Ingress address. For the Minikube NGINX addon,
obtain the address with minikube ip -p=dex.

Do not create an Ingress for the Headlamp service itself, because doing so
bypasses the authentication gate.

7. Verify login and RBAC

Open https://headlamp.example.com and sign in as
[email protected] / password. After Dex redirects back through
/oauth2/callback, Headlamp should display cluster resources allowed by the
view role.

Confirm the same authorization boundary independently:

shell
kubectl auth can-i [email protected] \
  --as-group=headlamp-readers list pods --all-namespaces
kubectl auth can-i [email protected] \
  --as-group=headlamp-readers delete pods --all-namespaces

The list command should return yes; the delete command should return no.

Local authentication demo

To exercise the browser login flow without configuring TLS or API-server OIDC,
use the scripts next to this guide:

shell
cd test-scripts
./run.sh
./test.sh

Open http://localhost:8080, sign in as [email protected] / password, and
run ./cleanup.sh when finished.

The local scripts deliberately enable Headlamp's
unsafeUseServiceAccountToken setting. OAuth2-Proxy still gates access, but
Kubernetes sees Headlamp's ServiceAccount rather than the Dex user. Never expose
Headlamp directly or use this shared-identity mode when you require per-user
audit or authorization.

Production checklist

  • Replace Dex's static password database with an appropriate connector.
  • Store client and cookie secrets outside Helm values files and rotate them.
  • Restrict email_domains and use least-privilege, group-based RBAC.
  • Use trusted HTTPS certificates or configure the required private CA bundles.
  • Expose only OAuth2-Proxy, and configure your ingress to preserve forwarded
    protocol and host headers.
  • Keep unsafeUseServiceAccountToken disabled for per-user RBAC.
  • Pin and deliberately update chart and image versions.

Troubleshooting

  • Dex returns invalid_redirect_uri: Make Dex's redirectURIs entry
    exactly match OAuth2-Proxy's redirect_url.
  • OAuth2-Proxy cannot discover Dex: Confirm that oidc_issuer_url is
    reachable from its pod and exactly matches the discovery document's issuer.
  • Headlamp returns Kubernetes authentication errors: Confirm that the API
    server trusts the same issuer and client ID, and can validate Dex's TLS chain.
  • Login succeeds but resources are forbidden: Check the token's email and
    group claims, then compare them with the relevant RBAC subjects.

Installation In Cluster Eks Index (`docs/installation/in-cluster/eks/index.md`)


title: How to Set Up Headlamp in EKS with Cognito as the OIDC provider sidebar_label: "Tutorial: Headlamp on EKS with Cognito"

This tutorial is about configuring Headlamp 0.23.2 with:

  1. AWS Cognito for OpenID Connect (OIDC) authentication
  2. AWS EKS Platform eks.6
  3. Kubernetes 1.29

Configuring Cognito

Cognito is a fully managed identity provider that allows you to create and manage users for your applications. In this tutorial, we will use Cognito as the OIDC provider for our EKS cluster. Before proceeding, follow the getting started guide to know more about Cognito.

We will start by creating a Cognito user pool. This tutorial uses the AWS portal, but you can also use the 'ekctl' or AWS CLI tools for configuration.

  1. Go to the AWS console and navigate to the Cognito service.

  2. Click on Create user pool.

  3. On the configure sign-in experience view, select User name, email and Allow user to sign in with a preferred username options.

  4. Click next to go to the Configure security requirements view

  5. You can configure the password policy as per your requirements. For this tutorial we will use the default settings.

  6. Click next to go to the Configure sign-up experience

  7. You can configure the email and phone verification settings as per your requirements. For this tutorial we will use the default settings.

  8. Click next to go to the Configure message delivery view

  9. You can either chose sending email from Amazon SES or with Cognito, These emails are for MFA, account recovery, sign up, sign in workflows. For this tutorial we will use sending emails through Cognito.

  10. Click next to go to the Integrate your app view

  11. There are a few things you have to take care of here,

    • You can either use the hosted UI or create your own UI for the authentication workflows (We are using the Cognito hosted UI).
    • You can also configure the domain name for the hosted UI (Also remember this is the issuer URL as well, which we will later use to set up EKS with). We are using the Cognito domain for this tutorial, but you can choose your own custom domain as well.
    • You can also configure the callback URLs for the auth flow. For this tutorial, we are setting it to be
      http://localhost:8000/oidc-callback as we will be running headlamp on this port. Or, you can choose your own callback host as well based on your needs. Make sure to append /oidc-callback to the host since this is where Headlamp expects the redirect from auth to occur.
    • Client Secret - We want to generate a client secret as our Headlamp app needs it to start the auth dance, so select Generate a client secret client secret column.
    • You can also configure the scopes and claims for the tokens. For this tutorial, make sure the openid, profile, and email scopes are selected; other scopes are optional.

In the above configurations make sure the Oauth 2.0 grant type is set to Authorization code grant.
12. Click next and you will be taken to the Review and Create view where you can review all the settings and create the user pool.

Setting up EKS cluster

We will first start by creating an EKS cluster. For this tutorial we will use the AWS console to create the cluster but you can use the eksctl or AWS CLI as well.

  1. Go to the AWS console and navigate to the EKS service.

  2. Click on Create Cluster or Add Cluster to create a new cluster.

  3. On the Configure Cluster view, select the EKS platform version, Kubernetes version, and the IAM role that has the necessary permissions to create the cluster. You can chose these configurations based on your requirements.

  4. Click next to go to the Configure Networking view

  5. You can configure the VPC, Subnets, and Security Groups for the cluster. For this tutorial we will use the default settings.

  6. Click next to go to the Configure Observability view, For this tutorial we will use the default settings.

  7. Click next to go to the Select Add-ons view, For this tutorial we will use the default selected add-ons.

  8. Click next to go to the Configure selected add-ons view, For this tutorial we will use the default settings.

  9. Click next to go to the Review and Create view where you can review all the settings and create the cluster.

Configuring OIDC provider for EKS

After creating the EKS cluster, we need to configure the OIDC provider for the cluster. This will allow the cluster to authenticate users using Cognito.

  1. Go to the access tab on the cluster overview page of the cluster you created above and click on the Associate OIDC Identity provider.
  2. In the Associate OIDC Identity provider view
    2.1 Enter a name for the Identity Provider Configuration
    2.2 Enter the issuer URL which can be found in the cognito user pool view you created. It should be something like https://cognito-idp.<YOUR_REGION_HERE>.amazonaws.com/USER_POOL_ID
    2.3 Client ID can be found in the app integration tab on the user pool overview page.
    2.4 The other fields can be filled as shown in the image below.

Fetching EKS cluster locally to deploy Headlamp on it

Make Sure you have the AWS CLI installed and setup with the necessary permissions to interact with the EKS cluster.

  1. Installation steps for AWS CLI can be found here
  2. Signin to the AWS CLI can be done by following the steps here

After setting up the AWS CLI, you can fetch the kubeconfig for the EKS cluster by running the following command

bash
aws eks --region <YOUR_REGION_HERE> update-kubeconfig --name <YOUR_CLUSTER_NAME_HERE>

Where <YOUR_REGION_HERE> is the region where the EKS cluster is created and <YOUR_CLUSTER_NAME_HERE> is the name of the EKS cluster.

Deploying Headlamp on the EKS cluster

  1. First make sure you have the Helm package manager installed on your local machine. There is a Helm installation guide if you need to install it.
  2. Your cluster should be running.
  3. Create a Cognito user through the AWS console. You will need the email for the next step.
  4. Inside Kubernetes we need to give users a "cluster-admin" ClusterRole. We do this by setting up a ClusterRoleBinding. So the cluster can authorize these users.

clusterRoleBinding.yaml

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user-clusterrolebinding
subjects:
  - kind: User
    name: [email protected]
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io

Create the ClusterRoleBinding by running the following command:

shell
kubectl apply -f clusterRoleBinding.yaml
  1. Create a values.yaml file and add the following OIDC configuration to it:
yaml
config:
  oidc:
  clientID: "<YOUR-CLIENT-ID>"
  clientSecret: "<YOUR-CLIENT-SECRET>"
  issuerURL: "https://cognito-idp.<YOUR_REGION_HERE>.amazonaws.com/<USER_POOL_ID>"
  scopes: "profile,email,openid"

Replace <YOUR-CLIENT-ID>,<YOUR-CLIENT-SECRET>,<YOUR_REGION_HERE, `` with your specific Cognito user pool app configuration details.


ℹ️ Additional Notes for Other OIDC Providers and Ingress Setups

If you're using an OIDC provider other than Cognito (such as JumpCloud, Auth0, or Okta), or if you're deploying Headlamp behind an ingress controller or load balancer (like AWS NLB or ALB), please review the following:

5.1. Redirect URI construction:
Headlamp automatically builds the redirect_uri using the Host and X-Forwarded-Proto headers. If the X-Forwarded-Proto header is missing, the URI may default to http, which can cause a mismatch with the URI registered in your identity provider.

If you're using NGINX ingress, you can ensure the correct header is forwarded by adding:

yaml
nginx.ingress.kubernetes.io/configuration-snippet: |
  proxy_set_header X-Forwarded-Proto $scheme;

5.2. Registering the correct redirect URI:
In your identity provider, make sure to register the exact redirect URI that Headlamp will use. This is typically:

text
https://<your-headlamp-domain>/oidc-callback

5.3. EKS OIDC trust configuration:
Even if you're not using Cognito, you must still associate your OIDC provider with your EKS cluster. This allows Kubernetes to validate tokens issued by your provider. Follow the same steps shown earlier in the "Configuring OIDC provider for EKS" section, using your provider's issuer URL and client ID.


  1. Save the values.yaml file and Install Headlamp using helm with the following commands:
shell
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/
helm install headlamp-oidc headlamp/headlamp -f values.yaml --namespace=headlamp --create-namespace

This will install Headlamp in the headlamp namespace with the OIDC configuration from the values.yaml file.

  1. After a successful installation, you can access Headlamp by port-forwarding to the pod:

Make sure the portforwarding is done to a port that you also set as the callback URL in the Cognito user pool configuration. So in our case if the callback URL is http://localhost:8000/oidc-callback then we should port forward to 8000.

shell
kubectl port-forward svc/headlamp-oidc 8000:80 -n headlamp
  1. Open your web browser and go to http://localhost:8000. Click on "sign-in." After completing the login flow successfully, you'll gain access to your Kubernetes cluster using Headlamp.

Installation In Cluster Keycloak Index (`docs/installation/in-cluster/keycloak/index.md`)


title: How to Set Up Headlamp in minikube with Keycloak OIDC Authentication sidebar_label: "Tutorial: OIDC with Keycloak"

In this tutorial, we'll walk through the process of configuring Headlamp within a Minikube cluster while utilizing Keycloak for OIDC (OpenID Connect) authentication. This tutorial is based on Keycloak version 22.0.4, Minikube version v1.31.2, and Headlamp version 0.20.1.

Note: This tutorial assumes that you have Keycloak hosted on a remote server. If you're using a local Keycloak instance, you may encounter issues with Minikube OIDC configuration.

Creating a Keycloak Client

To enable OIDC authentication in your Minikube cluster, you'll need to create a Keycloak client. Before proceeding, follow the getting started guide to set up your Keycloak instance. When creating a user in Keycloak, don't forget to also set the email address. Follow these steps to configure the client in your Keycloak admin panel:

  1. Start by accessing your Keycloak admin panel.

    <YOUR-KEYCLOAK-URL>/admin

  2. Navigate to the "Clients" section and Click on the "Create client" option.

  3. Fill in the "client-id" and "Name" fields and proceed to the next step.

  4. In the "Capability Config" step, enable "Client authentication" and proceed to the next step.

  5. Add "http://localhost:8000/\*" to the "Valid redirect URIs" and save your settings.

Setting up Minikube with the Keycloak OIDC Configuration

To configure Minikube for Keycloak OIDC integration, follow these steps:

  1. Run the following command to start Minikube with the necessary configuration options:
shell
minikube start -p=keycloak \
--extra-config=apiserver.authorization-mode=Node,RBAC \
--extra-config=apiserver.oidc-issuer-url=<YOUR-KEYCLOAK-URL>/realms/<REALM-NAME> \
--extra-config=apiserver.oidc-username-claim=email \
--extra-config=apiserver.oidc-client-id=<CLIENT-ID>

Note:
Replace <YOUR-KEYCLOAK-URL>, <REALM-NAME>, and <CLIENT-ID> with the actual values relevant to your Keycloak setup.

Configuring a ClusterRole Binding for the OIDC User

Once your cluster is operational, you need to configure a cluster role and a cluster role binding for the user in your Keycloak realm. This step is essential for enabling the Kubernetes API server to identify the user. In this example, we'll be associating the user with the predefined cluster-admin Role.

clusterRoleBinding.yaml

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user-clusterrolebinding
subjects:
  - kind: User
    name: <USER-EMAIL> # Please note that the name is case-sensitive
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: cluster-admin # Specify the name of the ClusterRole to be bound
  apiGroup: rbac.authorization.k8s.io

Note: Please replace `` with your keycloak user email.

Create the cluster role binding by running the following command:

shell
kubectl apply -f clusterRoleBinding.yaml

Configuring kubectl for OIDC User Authentication

Once you've set up your cluster and created a ClusterRoleBinding, it's time to configure kubectl to work with your OIDC user for authentication. Follow these steps:

  1. Install the oidc-login plugin with krew by executing the following command:
shell
kubectl krew install oidc-login
  1. Set Up oidc-login, Configure oidc-login with the necessary parameters by running the following command:
shell
kubectl oidc-login setup \
  --oidc-issuer-url=<YOUR-KEYCLOAK-URL>/realms/<REALM-NAME> \
  --oidc-client-id=<CLIENT-ID> \
  --oidc-client-secret=<CLIENT-SECRET>

Note: You can find the <CLIENT-SECRET> from the Credentials tab of your client details page in Keycloak.

  1. Create OIDC User for the Cluster, later this user will be mapped to the keycloak cluster.
shell
kubectl config set-credentials keycloak-oidc \
  --exec-api-version=client.authentication.k8s.io/v1beta1 \
  --exec-command=kubectl \
  --exec-arg=oidc-login \
  --exec-arg=get-token \
  --exec-arg=--oidc-issuer-url=<YOUR-KEYCLOAK-URL>/realms/<REALM-NAME> \
  --exec-arg=--oidc-client-id=<CLIENT-ID> \
  --exec-arg=--oidc-client-secret=<CLIENT-SECRET> \
  --exec-arg=--oidc-extra-scope=email \
  --exec-arg=--oidc-extra-scope=profile
  1. Link the User to the Cluster: To associate the user with the cluster, create a new context using these commands:
shell
kubectl config set-context keycloak-oidc --namespace=default --cluster=keycloak --user=keycloak-oidc
kubectl config use-context keycloak-oidc
  1. Test the Configuration: To verify that the configuration is working, list the namespaces in the cluster by executing the command:
shell
kubectl get ns

Upon running this command, a new browser window will open, prompting you to log in. Once you've completed the login process, you can close the window. You should see the namespaces in your cluster.

Note: Make sure to replace <YOUR-KEYCLOAK-URL>, <REALM-NAME>, <CLIENT-ID>, and <CLIENT-SECRET> with your specific Keycloak configuration details wherever necessary.

Setting up Headlamp with OIDC Configuration

To configure Headlamp, you can use the Headlamp Helm chart. Follow these steps to set it up with OIDC (OpenID Connect) authentication:

  1. Before setting up Headlamp Go to Keycloak Admin Dashboard, click on Client > Client Details and Edit Client, Add http://localhost:4466/oidc-callback to the list of Valid redirect URIs.

  2. Create a values.yaml file and add the following OIDC configuration to it:

yaml
config:
  oidc:
    clientID: "<YOUR-CLIENT-ID>"
    clientSecret: "<YOUR-CLIENT-SECRET>"
    issuerURL: "<YOUR-KEYCLOAK-URL>/realms/<REALM-NAME>"
    scopes: "email,profile"

Replace <YOUR-CLIENT-ID>, <YOUR-CLIENT-SECRET>, <YOUR-KEYCLOAK-URL>, and <REALM-NAME> with your specific OIDC configuration details.

  1. Save the values.yaml file and Install Headlamp using helm with the following commands:
shell
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/
helm install headlamp-oidc headlamp/headlamp -f values.yaml --namespace=headlamp --create-namespace

This will install Headlamp in the headlamp namespace with the OIDC configuration from the values.yaml file.

  1. After a successful installation, you can access Headlamp by port-forwarding to the pod:
shell
kubectl port-forward svc/headlamp-oidc 4466:80 -n headlamp
  1. Open your web browser and go to http://localhost:4466. Click on "sign-in." After completing the login flow successfully, you'll gain access to your Kubernetes cluster using Headlamp.

Conclusion

In this tutorial, we've set up Headlamp within a Kubernetes cluster and integrated it with OIDC (OpenID Connect) authentication provided by Keycloak. By following the steps outlined in this guide, you've successfully configured Headlamp to enhance your Kubernetes cluster management.

This setup allows you to enjoy Headlamp's user-friendly interface and advanced features. You can also be assured of secure and streamlined authentication through Dex. With the power of OIDC, you can easily and safely access and manage your Kubernetes resources.


Installation In Cluster Openunison Index (`docs/installation/in-cluster/openunison/index.md`)


title: Use OpenUnison For Headlamp Authentication using OIDC or Impersonation sidebar_label: "Tutorial: Authentication with OpenUnison"

Starting with version 1.0.44, OpenUnison adds support for Headlamp in two scenarios: clusters that support OpenID Connect (OIDC), typically on-premises environments, and cloud-managed clusters that rely on impersonation when OIDC is not available. This opens secure support for Headlamp both on-premises and in cloud hosted environments.

By default, OpenUnison's charts now ship with Headlamp. This means that deploying OpenUnison into a cluster will automatically deploy Headlamp with some additional features:

  • ServiceAccount with No Permissions - Headlamp's dedicated ServiceAccount has no RBAC bindings, so a lost ServiceAccount token is not a danger to your cluster
  • End-to-End TLS - OpenUnison has its own built in certificate automation, making sure that your sessions are encrypted from your Ingress, through OpenUnison's reverse proxy, to Headlamp and makes sure that the certificate is rotated as needed
  • Hardened Deployment - OpenUnison's Headlamp Deployment removes all capabilities, marks the container as read-only, and creates emptyDir volumes where writes are needed
  • Who Am I? - When you're logged into Headlamp, under the cluster there's now a link for a who-am-i feature that shows you who the cluster thinks you are, this is the same information provided by kubectl auth whoami
  • Namespace Listing - OpenUnison can manage which namespaces are listed by Headlamp either by listing all namespaces, testing which namespaces you have access to, or letting you write your own service to map from your user's identity to available namespaces

Additionally, the Headlamp deployment from OpenUnison supports adding plugins just as the stock deployment charts for Headlamp does.

OpenUnison supports multiple identity providers, including EntraID, Okta, and Keycloak. To deploy OpenUnison, follow the instructions per your identity provider and Ingress/Gateway. Headlamp will deploy automatically.

Integration with an Existing Headlamp

If you have an existing Headlamp deployment, you can integrate it with OpenUnison instead of using the OpenUnison-managed Headlamp instance.

NOTE: It's important to use TLS when connecting to Headlamp, since there are tokens being transmitted. If your cluster has a service mesh, you can use that instead of explicitly configuring TLS for Headlamp. If you don't have a service mesh or haven't deployed cert-manager or something similar for your Headlamp instance, you can use OpenUnison's integrated certificate manager. If you want to use OpenUnison's certificate manager, create a RoleBinding that allows the openunison-operator ServiceAccount to create and update Secrets and Pods so that OpenUnison's certificate manager can create TLS keypairs for Headlamp and restart Headlamp Pods when those keypairs need to be renewed:

yaml
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: openunison-secret-admin
  namespace: headlamp
rules:
  - apiGroups: [""]
    resources: ["secrets","pods"]
    verbs:
      - get
      - list
      - watch
      - create
      - update
      - patch
      - delete
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: openunison-operator-secret-admin
  namespace: headlamp
subjects:
  - kind: ServiceAccount
    name: openunison-operator
    namespace: openunison
roleRef:
  kind: Role
  name: openunison-secret-admin
  apiGroup: rbac.authorization.k8s.io

Assuming you have already deployed the OpenUnison authentication portal, update your OpenUnison values.yaml, with the following changes:

text
/* Detailed source-code truncated for AI context efficiency. */

The integration does not deploy the OpenUnison plugin for Headlamp, so the who-am-i and namespace listing functions are not present. Otherwise, you'll have the same access as if using OpenUnison's native Headlamp.

Using OpenUnison for Headlamp, but not kubectl

If you want to securely access Headlamp, but don't want to change how users login to Kubernetes for your cluster, you can deploy OpenUnison to just support Headlamp. These configuration changes can be used if you want to deploy OpenUnison's hardened Headlamp configuration or if you want to use your existing Headlamp deployment:

yaml
# tells OpenUnison to use impersonation, this works
# even if your cluster is configured to use OpenID Connect
enable_impersonation: true

# disables OpenUnison's kubectl integration and
# doesn't deploy the kube-oidc-proxy
openunison:
  kubeAuth:
    enabled: false

Once OpenUnison is (re)deployed, the tokens badge will be gone, but the Headlamp badge will still be there.


Tutorials Plugin Development Getting Started Index (`docs/tutorials/plugin-development/getting-started/index.mdx`)


title: Getting Started sidebar_label: Getting Started sidebar_position: 1

Getting Started with Plugin Development

This section covers the fundamentals of Headlamp plugin development. By the end, you'll have built a complete hello-headlamp plugin with:

  • ✅ App bar actions
  • ✅ Sidebar navigation & custom pages
  • ✅ Kubernetes data integration
  • ✅ List and detail views
  • ✅ Extending resource detail views
  • ✅ Plugin settings
  • ✅ Custom themes
  • ✅ Map visualization
  • ✅ Publish plugins to Artifact Hub

Tutorials

# Tutorial Time What You'll Build
1 Running Headlamp from Source 20 min Set up your development environment
2 Creating Your First Plugin 15 min "Hello" in app bar
3 Adding Pages and Sidebar Navigation 25 min Custom pages & sidebar navigation
4 Working with Kubernetes Data 25 min Fetch cluster and resource data
5 Advanced Kubernetes Interactions 30 min Custom resource classes, modify resources
6 Building List & Detail Pages 30 min ResourceListView & DetailsGrid components
7 Extending Existing Resource Views 25 min Extend built-in resource list and detail views
8 Adding Plugin Settings 20 min ConfigStore, registerPluginSettings, settings UI
9 Applying Custom Themes 20 min registerAppTheme, AppTheme options, light & dark variants
10 Adding Custom Map Nodes 20 min registerMapSource, node icons, custom detail views
11 Releasing & Publishing 30 min Lint, format, build, package, Artifact Hub

Prerequisites

  • Node.js ≥20.11.1
  • npm ≥10.0.0
  • Git
  • A code editor (VS Code recommended)

Tutorials Plugin Development Whoami Plugin Index (`docs/tutorials/plugin-development/whoami-plugin/index.md`)


title: "Building a WhoAmI Plugin" sidebar_label: "WhoAmI Plugin" sidebar_position: 3

Building a WhoAmI Plugin

In the Getting Started series, you learned the full toolkit for Headlamp plugin development — scaffolding, sidebar navigation, Kubernetes data fetching, pages, and more. Now let's apply that knowledge to solve a real problem: "Who am I in this cluster?"

In this tutorial, you'll build a focused, single-purpose plugin that adds a WhoAmI entry under the Cluster section in the cluster sidebar — alongside Namespaces and Nodes. When clicked, it shows the current user's identity — username, UID, and groups — just like kubectl auth whoami.


Table of Contents

  1. Introduction
  2. What You'll Build
  3. Create the Plugin
  4. Add the Sidebar Entry
  5. Fetch User Identity
  6. Display the Identity
  7. Supporting Multi-Cluster
  8. Troubleshooting
  9. Quick Reference

Introduction

Kubernetes tracks who is making API requests. Every request carries an identity — a username, a UID, and a set of groups. You've probably used kubectl auth whoami to see this:

text
ATTRIBUTE   VALUE
Username    [email protected]
UID         abc-123-def
Groups      [system:authenticated, developers]

But when you're working in Headlamp's UI, there's no built-in way to see this identity at a glance. Let's fix that by building a plugin that calls the same Kubernetes API (SelfSubjectReview) and displays the result in a clean page.

Prerequisites

Before starting, ensure you have:

  • Completed the Getting Started tutorial series (at least Tutorials 1-4)
  • Headlamp running locally with a connected cluster
  • Node.js >= 22.0.0 and npm >= 11.0.0
  • Your cluster running Kubernetes >= 1.28 (for SelfSubjectReview API)

Time to complete: ~20 minutes


What You'll Build

A plugin called whoami-headlamp that:

  1. Adds a WhoAmI entry under Cluster in the cluster sidebar (alongside Namespaces and Nodes)
  2. Calls the SelfSubjectReview API to fetch the current user's identity
  3. Displays username, UID, groups, and extra info in a clean layout
text
Sidebar (Cluster View):
├── Home
├── Cluster
│   ├── Namespaces
│   ├── Nodes
│   └── WhoAmI              → /whoami
├── Workloads
└── ...

Create the Plugin

Scaffold a new plugin project:

bash
cd ~/projects
npx --yes @kinvolk/headlamp-plugin create whoami-headlamp
cd whoami-headlamp

Start the plugin in development mode:

bash
npm start

Make sure Headlamp is also running in a separate terminal (npm start in the Headlamp directory).


Add the Sidebar Entry

Open src/index.tsx and replace its contents with:

tsx
import { registerRoute, registerSidebarEntry } from '@kinvolk/headlamp-plugin/lib';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Typography } from '@mui/material';

function WhoAmIPage() {
  return (
    <SectionBox title="WhoAmI">
      <Typography>Loading identity...</Typography>
    </SectionBox>
  );
}

// Register the sidebar entry under Cluster (alongside Namespaces, Nodes)
registerSidebarEntry({
  parent: 'cluster',
  name: 'whoami',
  label: 'Who Am I',
  url: '/whoami',
  icon: 'mdi:badge-account',
});

// Register the route
registerRoute({
  path: '/whoami',
  sidebar: 'whoami',
  component: WhoAmIPage,
  exact: true,
});

What's happening here?

Code Purpose
parent: 'cluster' Places the entry under the Cluster section, alongside Namespaces and Nodes
icon: 'mdi:badge-account' An identity-themed icon from Iconify
sidebar: 'whoami' Links the route to the sidebar entry so it highlights when active

Test It

  1. Save the file
  2. Navigate to a cluster in Headlamp
  3. Expand the Cluster section in the sidebar
  4. You should see WhoAmI alongside Namespaces and Nodes
  5. Click it — you'll see the placeholder page

Fetch User Identity

Now let's call the Kubernetes SelfSubjectReview API to get the current user's identity. This is the same API that kubectl auth whoami uses.

The API works by sending a POST request to /apis/authentication.k8s.io/v1/selfsubjectreviews with an empty body, and the server responds with the authenticated user's info.

Update src/index.tsx:

text
/* Detailed source-code truncated for AI context efficiency. */

Key details about the API call:

Parameter Value Why
Endpoint /apis/authentication.k8s.io/v1/selfsubjectreviews The SelfSubjectReview API endpoint
Method POST This API requires a POST, not a GET
Body { apiVersion, kind } Minimal required body — the server fills in the response
cluster From getCluster() Routes the request to the correct cluster

The response has this structure:

json
{
  "apiVersion": "authentication.k8s.io/v1",
  "kind": "SelfSubjectReview",
  "status": {
    "userInfo": {
      "username": "[email protected]",
      "uid": "abc-123-def",
      "groups": ["system:authenticated", "developers"],
      "extra": {
        "some-key": ["some-value"]
      }
    }
  }
}

Test It

Save the file and click WhoAmI in the sidebar. You should see the username displayed. Now let's make it look better.

Note: The username format depends on your cluster's authentication provider. For example, Azure (AKS) typically shows your email address, minikube shows a client certificate CN, and OIDC providers may show a custom claim. This is expected — the API returns whatever identity the cluster sees for your requests.


Display the Identity

Let's use Headlamp's NameValueTable component to display the identity information cleanly, matching the style of built-in resource detail pages.

Update the WhoAmIPage component:

text
/* Detailed source-code truncated for AI context efficiency. */

What's new?

Component Purpose
NameValueTable Headlamp's built-in key-value display, matching the style of resource detail pages
Chip MUI component for displaying groups as tags
Extra fields Dynamically renders any additional identity attributes the API returns

Test It

Save the file and navigate to the WhoAmI page. You should see a clean table showing:

  • Username — your authenticated identity
  • UID — your unique identifier (if available)
  • Groups — displayed as chips (e.g., system:authenticated, system:masters)
  • Extra — any additional attributes (varies by authentication provider)

Supporting Multi-Cluster

Our plugin works, but there's a problem: it uses getCluster(), which returns only a single cluster name. Headlamp supports multi-cluster views where users can select and work with several clusters at once. If a user has multiple clusters selected, our plugin will only show the identity for one of them.

This is a common oversight in plugin development. Let's fix it by using the useSelectedClusters() hook, which returns all currently selected clusters.

getCluster() useSelectedClusters()
Returns Single cluster name (string | null) All selected clusters (string[])
Multi-cluster Only sees the first/primary cluster Sees every cluster the user selected

Update the Plugin

Replace the contents of src/index.tsx with the multi-cluster version:

text
/* Detailed source-code truncated for AI context efficiency. */

What changed?

Change Why
getCluster() → useSelectedClusters() Gets all selected clusters instead of just one
Import from lib/k8s instead of lib/Utils useSelectedClusters is exported from the K8s module
fetchClusterIdentity() helper Extracted so we can call it once per cluster
ClusterIdentity component Renders one identity section — reused for each cluster
Promise.all(...) Fetches identities for all clusters in parallel
SectionBox title={WhoAmI — ${cluster}} Labels each section with the cluster name so users can tell them apart

With a single cluster selected, the page looks exactly like before (just with the cluster name in the title). With multiple clusters, users see one section per cluster — matching how Headlamp's built-in list pages show resources across clusters.

Test It

  1. Save the file
  2. With a single cluster selected, the page should work as before
  3. If you have multiple clusters configured, select more than one using the cluster chooser in the top bar — you should see a separate identity section for each cluster

Troubleshooting

"Failed to fetch identity" Error

Check your Kubernetes version:

The SelfSubjectReview API requires Kubernetes >= 1.28. Check your version:

bash
kubectl version --short

If your cluster is older, the API won't be available.

Check RBAC permissions:

The SelfSubjectReview API is available to all authenticated users by default. If you see a 403 error, your cluster may have non-standard RBAC policies.

Sidebar Entry Not Under Cluster

Verify parent: 'cluster':

The entry must use parent: 'cluster' (lowercase) to appear under the Cluster section alongside Namespaces and Nodes:

tsx
registerSidebarEntry({
  parent: 'cluster',    // Must be exactly 'cluster'
  name: 'whoami',
  // ...
});

UID Shows "N/A"

Some authentication providers don't set a UID. This is normal — not all identity systems provide one. The username and groups are the primary identity attributes.

Groups or Extra Fields Empty

The groups and extra fields depend on your authentication provider:

Auth Method Typical Groups Extra Fields
Client certificate system:masters, system:authenticated None
OIDC system:authenticated, custom groups Varies by provider
Service account system:serviceaccounts, namespace groups None
Token webhook Depends on provider Depends on provider

Quick Reference

SelfSubjectReview API

tsx
const response = await ApiProxy.request(
  '/apis/authentication.k8s.io/v1/selfsubjectreviews',
  {
    cluster,
    method: 'POST',
    body: JSON.stringify({
      apiVersion: 'authentication.k8s.io/v1',
      kind: 'SelfSubjectReview',
    }),
    headers: {
      'Content-Type': 'application/json',
    },
  }
);

const userInfo = response.status?.userInfo;
// userInfo.username  — string
// userInfo.uid       — string | undefined
// userInfo.groups    — string[] | undefined
// userInfo.extra     — Record<string, string[]> | undefined
tsx
registerSidebarEntry({
  parent: 'cluster',           // Places entry under Cluster (alongside Namespaces, Nodes)
  name: 'whoami',
  label: 'Who Am I',
  url: '/whoami',
  icon: 'mdi:badge-account',
});

Key Concepts Used

Concept From Tutorial Applied Here
registerSidebarEntry with parent Tutorial 3 Sidebar entry under Cluster
registerRoute Tutorial 3 WhoAmI page route
ApiProxy.request with POST Tutorial 4 SelfSubjectReview API call
NameValueTable Tutorial 6 Identity display
getCluster() Tutorial 4 Cluster context

Installation In Cluster Dex Test Scripts README (`docs/installation/in-cluster/dex/test-scripts/README.md`)

Headlamp + OAuth2-Proxy + Dex test scripts

This folder provides a runnable local version of the
Headlamp + OAuth2-Proxy + Dex tutorial.

It brings up:

  • A Minikube profile (dex) with RBAC enabled and no
    apiserver.oidc-* flags.
  • A Dex instance (running on the host machine) acting as the OIDC provider.
  • A Headlamp install via the official Helm chart, with no OIDC config.
  • An OAuth2-Proxy install via the official Helm chart, configured to
    authenticate users against Dex and forward the resulting id_token to
    Headlamp as an Authorization: Bearer … header.

When everything is up, you reach Headlamp by opening
http://localhost:8080 in your browser, signing in to Dex
([email protected] / password), and being redirected back to Headlamp
with access provided by Headlamp's in-cluster ServiceAccount. This is an
explicitly local mode: every authenticated user receives the same Kubernetes
permissions. See the parent tutorial for per-user RBAC.

Prerequisites

Make sure the following are installed and on your PATH:

  • minikube ≥ 1.31
  • kubectl
  • helm ≥ 3.10
  • dex 2.45.1 (built with Go 1.25 or newer;
    Dex does not publish prebuilt binaries)
  • curl (for the smoke test)
  • openssl (for the random cookie secret)
  • Browser-side resolution for host.minikube.internal

The login flow redirects your browser to
http://host.minikube.internal:5556. If that name does not resolve where the
browser runs, add it to that operating system's hosts file. Use 127.0.0.1
when the browser can reach Dex through localhost. For a browser outside WSL or
a VM, use the WSL/VM address that reaches Dex instead.

  • Linux/macOS hosts file: /etc/hosts
  • Windows hosts file: %SystemRoot%\System32\drivers\etc\hosts

For example:

text
127.0.0.1 host.minikube.internal

The scripts pin Headlamp chart 0.44.0, OAuth2-Proxy chart 10.7.0
(OAuth2-Proxy 7.15.3), and Dex 2.45.1. They were tested with Minikube 1.38
on Linux. macOS should work the same way; on Windows, use WSL.

Installing the prerequisites

Pick the section for your OS. kubectl, minikube and helm are not
shipped in the default Ubuntu/Debian repositories, so on those platforms
we use their upstream package sources / install scripts. Dex does not
publish prebuilt dex binaries (only source tarballs and container
images), so on Ubuntu/Debian we build dex from source with go build;
on macOS, all four tools (including dex) are available from Homebrew.

Ubuntu LTS (22.04 / 24.04) and Debian-based WSL

text
/* Detailed source-code truncated for AI context efficiency. */

You'll also need a Minikube driver. On a fresh Ubuntu host, docker.io
from apt is the simplest choice (sudo apt-get install -y docker.io && sudo usermod -aG docker "$USER", then re-login).

macOS with Homebrew

bash
# All four binaries are in homebrew-core
brew install kubectl minikube helm dex
# curl and openssl ship with macOS, no install needed.

# Verify the installation
kubectl version --client
minikube version
helm version
dex version

Minikube on macOS needs a driver too; the easiest is Docker Desktop
(brew install --cask docker) or the QEMU driver (brew install qemu).

Files

File What it is
dex-config.yaml Dex configuration (static client + static password).
headlamp-values.yaml Helm values for Headlamp (auth handled by OAuth2-Proxy, no OIDC needed).
oauth2-proxy-values.yaml.tpl Template Helm values for OAuth2-Proxy (cookie secret is injected).
run.sh Brings up Minikube, Dex, Headlamp, OAuth2-Proxy and port-forwards.
test.sh Smoke-tests that the OAuth2-Proxy login redirects to Dex.
cleanup.sh Stops Dex and deletes stack resources owned by these scripts.

Usage

bash
# Start everything. Leaves Dex running in the background and
# port-forwards OAuth2-Proxy on http://localhost:8080.
./run.sh

# In another terminal, verify the deployment.
./test.sh

# Open Headlamp in your browser:
#   http://localhost:8080
# Sign in as: [email protected] / password

# When you're done:
./cleanup.sh

run.sh is safe to re-run: it reuses the Minikube profile and Dex process that
it created, then reapplies the pinned Helm releases. It refuses to reuse an
existing dex profile that it does not own. cleanup.sh deletes the profile
only when the ownership marker created by run.sh is present.

To use a different profile name, pass the same value to both commands:

bash
HEADLAMP_DEX_MINIKUBE_PROFILE=headlamp-dex ./run.sh
HEADLAMP_DEX_MINIKUBE_PROFILE=headlamp-dex ./test.sh
HEADLAMP_DEX_MINIKUBE_PROFILE=headlamp-dex ./cleanup.sh

How the authentication flow works

This setup follows
OAuth2-Proxy's official Headlamp integration guide:
OAuth2-Proxy sits in front of Headlamp, talks OIDC to Dex, issues a session
cookie to the browser, and forwards the user's id_token to Headlamp as an
Authorization: Bearer … header.

These scripts omit apiserver.oidc-* flags and deliberately set Headlamp's
unsafeUseServiceAccountToken option. OAuth2-Proxy authenticates access to
Headlamp, but Kubernetes authorizes every signed-in user as Headlamp's
ServiceAccount. The parent tutorial explains the HTTPS issuer
and API-server configuration required for per-user RBAC.


Tutorials Plugin Development Getting Started Adding Custom Map Nodes Index (`docs/tutorials/plugin-development/getting-started/adding-custom-map-nodes/index.md`)


title: "Tutorial 10: Adding Custom Map Nodes" sidebar_label: "10. Adding Custom Map Nodes" sidebar_position: 11

Adding Custom Map Nodes

In Tutorial 9 we customised how Headlamp looks. In this tutorial we will extend what Headlamp shows — specifically, we will add the MyPod resources from our plugin to Headlamp's Map view.


Table of Contents

  1. Introduction to the Map View
  2. Concepts: Nodes, Edges, and Sources
  3. Creating a Map Source for MyPod
  4. Registering the Source
  5. Adding a Custom Node Icon
  6. Adding Edges Between Nodes
  7. What's Next
  8. Quick Reference

Introduction to the Map View

Headlamp's Map view (accessible via the Map button in the sidebar when a cluster is connected) renders your cluster as an interactive graph. Every built-in resource — Deployments, ReplicaSets, Pods, Services, and more — is displayed as a node, and the ownership relationships between them are shown as edges.

The map is not limited to built-in resources. Plugins can register their own sources — collections of nodes and edges that teach the map about resources that Headlamp does not know about by default. This is especially useful for:

  • Custom Resource Definitions (CRDs) — controllers like KEDA, Argo CD, or Flux introduce CRDs that the built-in map has no knowledge of. A plugin can add those resources as first-class nodes.
  • Plugin-managed resources — if your plugin works with a specific subset of standard resources (like our MyPod class), you can surface them as a dedicated, filterable source.

In this tutorial we will register our MyPod resource class as a map source so that all pods appear in the map under a "My Pods" entry in the source picker.


Concepts: Nodes, Edges, and Sources

Before writing code it helps to understand the three building blocks:

Concept What it represents Example
Node A single resource displayed on the map One pod, one deployment
Edge A directed relationship between two nodes ReplicaSet → Pod (ownership)
Source A named collection of nodes and edges "My Pods", "KEDA ScaledObjects"

A source is a GraphSource object with three required properties:

tsx
// A leaf source — fetches its own nodes/edges
{
  id: string;        // Unique across all sources
  label: string;     // Shown in the source picker UI
  icon?: ReactNode;  // Optional icon in the source picker
  useData(): { nodes?: GraphNode[]; edges?: GraphEdge[] } | null;
}

// A parent source — groups child sources (cannot have useData)
{
  id: string;
  label: string;
  icon?: ReactNode;
  sources: GraphSource[];
}

The useData() function is a React hook — you can call other hooks inside it (like MyPod.useList()). It must return null while data is loading, or an object with nodes (and optionally edges) once data is ready. Because useData() is called on every render, wrap your return value in useMemo so the map only re-renders when the data actually changes.


Creating a Map Source for MyPod

We will add the map source directly to src/index.tsx, alongside the existing registrations.

Step 1: Update `src/index.tsx`

Add the registerMapSource import and define the source at the bottom of the file, after your existing registrations:

tsx
import { registerMapSource } from '@kinvolk/headlamp-plugin/lib';
import { useMemo } from 'react';
import { MyPod } from './resources/pod';

// ... your existing registerRoute / registerSidebarEntry calls ...

const myPodSource = {
  id: 'hello-headlamp-pods',
  label: 'My Pods',
  useData() {
    const [pods] = MyPod.useList();

    return useMemo(() => {
      // Return null while loading — the map will show a spinner
      if (!pods) return null;

      const nodes = pods.map(pod => ({
        id: pod.metadata.uid,   // Must be unique; uid is a safe choice
        kubeObject: pod,        // Tells the map this node is a Kubernetes resource
      }));

      return { nodes };
    }, [pods]);
  },
};

registerMapSource(myPodSource);

Key points:

Property Purpose
id Unique identifier for the source; namespace it with your plugin name
label Text shown in the source picker
useData() Hook called by the map to fetch nodes and edges
node.id Must be unique across all nodes in the map; metadata.uid is a reliable choice
node.kubeObject Attach the KubeObject instance so the map can show default Kubernetes details

Step 2: Open the Map view

  1. Save the file and let the plugin rebuild.
  2. Open Headlamp and connect to your cluster.
  3. Click Map in the sidebar.
  4. Open the source picker — the filter chip above the map, labelled with the sources currently shown — and make sure "My Pods" is ticked in the list that drops down.

You should see all pods from your cluster appear as nodes on the map under the My Pods source.


Registering the Source

registerMapSource accepts the source object and registers it globally. You can call it at module load time (outside any component or hook):

tsx
import { registerMapSource } from '@kinvolk/headlamp-plugin/lib';

registerMapSource(myPodSource);

That is all — there is no teardown or cleanup required. The source stays registered for the lifetime of the plugin.

Grouping Sources

If your plugin registers multiple sources (for example, you later add a MyService source), you can group them under a single parent:

tsx
const myPluginSource = {
  id: 'hello-headlamp',
  label: 'Hello Headlamp',
  sources: [myPodSource, myServiceSource],  // Nested sources
};

registerMapSource(myPluginSource);

The parent source becomes a collapsible group in the source picker. This is the pattern used by the KEDA plugin, which groups ScaledObjects, ScaledJobs, TriggerAuthentications, and ClusterTriggerAuthentications under a single "KEDA" entry.


Adding a Custom Node Icon

By default, nodes that have a kubeObject show a generic icon based on the resource kind. You can register a custom icon for any kind using registerKindIcon:

tsx
import { registerMapSource, registerKindIcon } from '@kinvolk/headlamp-plugin/lib';

// Register a custom icon for the "Pod" kind
registerKindIcon('Pod', {
  icon: (
    <img
      src="https://kubernetes.io/icons/favicon-64.png"
      alt="Pod"
      style={{ width: '100%', height: '100%' }}
    />
  ),
});

:::info
registerKindIcon applies to all nodes of that kind in the entire map, not just the ones in your source. If you only want a custom icon for your source's nodes, provide it via the source's icon property instead (which only affects the source picker entry, not individual nodes).
:::

You can also use Iconify icons (already bundled with Headlamp via @iconify/react):

tsx
import { Icon } from '@iconify/react';

registerKindIcon('Pod', {
  icon: <Icon icon="mdi:kubernetes" width="100%" height="100%" />,
});

:::info
The map also supports providing a detailsComponent on individual nodes to customise the side panel that appears when a node is selected. However, avoid doing this for resource kinds that Headlamp already handles natively (like Pod, Deployment, etc.) — overriding their default detail views can confuse users who expect the standard Headlamp experience. detailsComponent is most valuable for CRDs and custom resources that Headlamp has no built-in detail view for.
:::


Adding Edges Between Nodes

Edges draw connections between nodes. Each edge needs a source node id and a target node id:

tsx
const edge = {
  id: `${fromNode.id}-${toNode.id}`, // Must be unique
  source: fromNode.id,
  target: toNode.id,
};

For our MyPod example there is no obvious second resource to connect to (our plugin only manages pods). But edges become important when your plugin handles related resources — for instance, if you also had a MyDeployment source, you could draw edges from each deployment to the pods it owns.

The KEDA plugin is a good real-world reference for edges: it connects each ScaledObject to the HorizontalPodAutoscaler that KEDA creates for it, and draws edges from ScaledObjects/ScaledJobs to the TriggerAuthentication resources they reference.

Here is the pattern to produce edges alongside nodes (inside src/index.tsx):

tsx
useData() {
  const [pods] = MyPod.useList();
  // Imagine we also had a MyNode resource
  // const [nodes] = MyNode.useList();

  return useMemo(() => {
    if (!pods) return null;

    const nodes = pods.map(pod => ({
      id: pod.metadata.uid,
      kubeObject: pod,
    }));

    const edges = [];
    // Example: connect each pod to a related resource
    // pods.forEach(pod => {
    //   const relatedNode = kubeNodes?.find(n => n.metadata.name === pod.jsonData.spec.nodeName);
    //   if (relatedNode) {
    //     edges.push({
    //       id: `${pod.metadata.uid}-${relatedNode.metadata.uid}`,
    //       source: pod.metadata.uid,
    //       target: relatedNode.metadata.uid,
    //     });
    //   }
    // });

    return { nodes, edges };
  }, [pods]);
},

What's Next

You've extended Headlamp's Map view with your own resources:

  • ✅ Understood how the map is built from nodes, edges, and sources
  • ✅ Created a GraphSource object for MyPod using the useData() hook
  • ✅ Registered it with registerMapSource
  • ✅ Added a custom node icon with registerKindIcon
  • ✅ Learned how to group sources and add edges

Next: Tutorial 11 – Releasing & Publishing

  • Packaging your plugin for distribution
  • Publishing to Artifact Hub
  • Versioning and changelogs

Quick Reference

Minimal Source

tsx
import { registerMapSource } from '@kinvolk/headlamp-plugin/lib';
import { useMemo } from 'react';

registerMapSource({
  id: 'my-source',
  label: 'My Source',
  useData() {
    const [items] = MyResource.useList();
    return useMemo(() => {
      if (!items) return null;
      return {
        nodes: items.map(item => ({
          id: item.metadata.uid,
          kubeObject: item,
        })),
      };
    }, [items]);
  },
});

Source with Icon

tsx
import { Icon } from '@iconify/react';

registerMapSource({
  id: 'my-source',
  label: 'My Source',
  icon: <Icon icon="mdi:kubernetes" width="100%" height="100%" />,
  useData() { /* ... */ },
});

Custom Kind Icon

tsx
import { registerKindIcon } from '@kinvolk/headlamp-plugin/lib';

registerKindIcon('MyResourceKind', {
  icon: <img src="/path/to/icon.png" style={{ width: '100%', height: '100%' }} />,
});

Edge Between Two Nodes

tsx
const edge = {
  id: `${sourceNode.id}-${targetNode.id}`,
  source: sourceNode.id,
  target: targetNode.id,
};

Grouped Sources

tsx
registerMapSource({
  id: 'my-plugin',
  label: 'My Plugin',
  sources: [sourceA, sourceB, sourceC],
});

Tutorials Plugin Development Getting Started Adding Pages And Sidebar Navigation Index (`docs/tutorials/plugin-development/getting-started/adding-pages-and-sidebar-navigation/index.md`)


title: "Tutorial 3: Adding Pages and Sidebar Navigation" sidebar_label: "3. Adding Pages and Sidebar Navigation" sidebar_position: 4

Adding Pages and Sidebar Navigation

This tutorial will show you how to create custom pages and make them discoverable through Headlamp's sidebar navigation. You'll learn the essential pattern of creating routes and linking them to sidebar entries.


Table of Contents

  1. Introduction
  2. Creating a Custom Page
  3. Connecting the App Bar Button
  4. Why Sidebar Navigation Matters
  5. Adding a Sidebar Entry
  6. Adding an Icon
  7. Creating Subentries
  8. Home View vs Cluster View
  9. Troubleshooting
  10. What's Next
  11. Quick Reference

Introduction

In Tutorial 2, you created a plugin that displays content in the app bar. But what if you want to create entire pages with rich content? And how do users discover those pages?

This tutorial answers both questions:

  1. Create custom pages using registerRoute()
  2. Add sidebar navigation using registerSidebarEntry()

What You'll Build

By the end of this tutorial, your plugin will have:

  • A custom "Welcome" page accessible via URL
  • A sidebar entry that links to your page
  • Subentries for organizing related pages
  • Navigation in both cluster view and home view
text
Sidebar (Home View):
├── [Clusters list]
├── 🆕 My Plugin          → expandable parent
│   ├── Overview          → /my-plugin
│   └── Settings          → /my-plugin/settings
└── 📚 Plugin Docs        → /plugin-docs

Prerequisites

Before starting, ensure you have:

Time to complete: ~20 minutes


Creating a Custom Page

Let's start by creating a page. A page in Headlamp is simply a React component that gets displayed at a specific URL.

Step 1: Create a Page Component

Open src/index.tsx in your hello-headlamp plugin and replace its contents with:

tsx
import { registerRoute } from '@kinvolk/headlamp-plugin/lib';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Typography } from '@mui/material';

function WelcomePage() {
  return (
    <SectionBox title="Welcome to My Plugin">
      <Typography variant="body1">
        This is your first custom page! 🎉
      </Typography>
    </SectionBox>
  );
}

registerRoute({
  path: '/my-plugin',
  sidebar: null,
  component: WelcomePage,
  useClusterURL: false,
  noAuthRequired: true,
});

What's happening here?

Code Purpose
registerRoute() Tells Headlamp to display a component at a specific URL
path: '/my-plugin' The URL path where the page will be accessible
sidebar: null No sidebar entry linked yet (we'll add one later)
component: WelcomePage The React component to render
useClusterURL: false Makes the page accessible at /my-plugin (not cluster-specific)
noAuthRequired: true Page accessible without authentication

SectionBox is imported from @kinvolk/headlamp-plugin/lib/CommonComponents. This module provides ready-to-use UI components that match Headlamp's look and feel. We'll explore more CommonComponents like NameValueTable, ResourceListView etc in future tutorials.

Step 2: Navigate Manually

Save the file and navigate to your page manually:

  1. Open your browser
  2. Go to: http://localhost:3000/my-plugin

You should see your Welcome page! 🎉

The Problem with Manual Navigation

Your page works, but there's a problem: users need to know the exact URL.

This is terrible user experience! Let's improve it step by step.


Connecting the App Bar Button

Remember the "Say Hello" button from Tutorial 2? Let's modify it to navigate to our new page instead of showing an alert.

Step 1: Modify the Hello Button

Update your src/index.tsx:

tsx
import { registerAppBarAction, registerRoute } from '@kinvolk/headlamp-plugin/lib';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Button, Typography } from '@mui/material';

function WelcomePage() {
  return (
    <SectionBox title="Welcome to My Plugin">
      <Typography variant="body1">
        This is your first custom page! 🎉
      </Typography>
    </SectionBox>
  );
}

registerRoute({
  path: '/my-plugin',
  sidebar: null,
  component: WelcomePage,
  useClusterURL: false,
  noAuthRequired: true,
});

function HelloButton() {
  return (
    <Button
      variant="outlined"
      size="small"
      href="/my-plugin"
      sx={{ color: 'inherit', borderColor: 'inherit', mx: 1 }}
    >
      My Plugin
    </Button>
  );
}

registerAppBarAction(<HelloButton />);

What changed from Tutorial 2?

Before (Tutorial 2) After (Tutorial 3)
onClick={() => alert(...)} href="/my-plugin"
Shows an alert popup Navigates to our custom page

Step 2: Test It

  1. Save the file
  2. Hover over the "My Plugin" button in the app bar — you'll see the URL (/my-plugin) appear in the bottom-left corner of your browser
  3. Click the button — you navigate to your Welcome page!

Now we have a page and an app bar button navigating to it. But did you notice something? The page we created doesn't have any sidebar!

That's because we used useClusterURL: false, which creates a standalone page outside the cluster context. Let's explore how to add sidebar navigation.


Why Sidebar Navigation Matters

The app bar button works, but there's a problem: the app bar has limited space.

What if your plugin has multiple pages? You can't add a button for every page!

The solution? Add entries to the sidebar—the navigation menu on the left side of Headlamp. The sidebar:

  • Has room for multiple entries
  • Supports hierarchical organization (parent/child)
  • Shows users where they are (highlighted entry)
  • Is the standard navigation pattern in Headlamp

Adding a Sidebar Entry

Let's make your page discoverable by adding it to the sidebar.

Step 1: Register a Sidebar Entry

Update your src/index.tsx to add a sidebar entry and connect it to your route:

tsx
import { registerAppBarAction, registerRoute, registerSidebarEntry } from '@kinvolk/headlamp-plugin/lib';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Button, Typography } from '@mui/material';

function WelcomePage() {
  return (
    <SectionBox title="Welcome to My Plugin">
      <Typography variant="body1">
        This is your first custom page! 🎉
      </Typography>
      <Typography variant="body2" sx={{ mt: 2, color: 'text.secondary' }}>
        Now accessible from the sidebar!
      </Typography>
    </SectionBox>
  );
}

// Register the page — note sidebar now points to our entry
registerRoute({
  path: '/my-plugin',
  sidebar: 'my-plugin',
  component: WelcomePage,
  useClusterURL: false,
  noAuthRequired: true,
});

// Register the sidebar entry
registerSidebarEntry({
  name: 'my-plugin',
  label: 'My Plugin',
  url: '/my-plugin',
  useClusterURL: false,
});

// Keep the app bar button (optional)
function HelloButton() {
  return (
    <Button
      variant="outlined"
      size="small"
      href="/my-plugin"
      sx={{ color: 'inherit', borderColor: 'inherit', mx: 1 }}
    >
      My Plugin
    </Button>
  );
}

registerAppBarAction(<HelloButton />);

What's new?

registerSidebarEntry options:

Property Purpose
name Unique identifier for this entry (must match sidebar in the route)
label Text displayed in the sidebar
url URL to navigate to when clicked
useClusterURL If false, URL stays as /my-plugin; if true (default), URL becomes /c/:cluster/my-plugin

registerRoute change:

Property Before After
sidebar null 'my-plugin' — now links the route to the sidebar entry

Note: registerRoute also accepts an optional name property (e.g., name: 'My Plugin') which provides a human-readable name that may be used for the browser tab title.

Important: The sidebar value in registerRoute must match the name in registerSidebarEntry. This connection:

  • Highlights the sidebar entry when you're on the page
  • Helps Headlamp know which sidebar to show
  • Works regardless of how you navigate — whether you click the sidebar entry, use the app bar button we created earlier, or type the URL manually, the sidebar entry will be selected

Step 2: See It in Action

  1. Save the file
  2. Go to the Headlamp home screen (http://localhost:3000/)
  3. Look at the sidebar on the left—you should see "My Plugin" as a new entry!
  4. Click it—you'll navigate to your Welcome page

The connection works both ways:

  • Clicking the sidebar entry → navigates to your page
  • Being on your page → highlights the sidebar entry

Adding an Icon

Your sidebar entry works, but it looks plain without an icon. Let's add one!

Headlamp uses Iconify for icons. You can browse thousands of icons and use them by their string identifier.

Step 1: Update the Sidebar Entry

Modify your registerSidebarEntry call to include an icon:

tsx
registerSidebarEntry({
  name: 'my-plugin',
  label: 'My Plugin',
  url: '/my-plugin',
  icon: 'mdi:new-box',
  useClusterURL: false,
});

Step 2: See the Icon

Save the file and look at your sidebar entry—it now has a "new" icon! 🆕

Tip: Browse all available icons at icon-sets.iconify.design/mdi/


Creating Subentries

As your plugin grows, you'll want to organize related pages under a parent entry. Let's create a sidebar section with subentries.

Step 1: Update Your Plugin

Replace your src/index.tsx with this expanded version:

tsx
import { registerRoute, registerSidebarEntry } from '@kinvolk/headlamp-plugin/lib';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Typography } from '@mui/material';

// Page components
function OverviewPage() {
  return (
    <SectionBox title="Overview">
      <Typography>Welcome to the plugin overview!</Typography>
    </SectionBox>
  );
}

function SettingsPage() {
  return (
    <SectionBox title="Plugin Settings">
      <Typography>Configure your plugin settings here.</Typography>
    </SectionBox>
  );
}

// Register routes
registerRoute({
  path: '/my-plugin',
  exact: true,
  name: 'Plugin Overview',
  sidebar: 'my-plugin-overview',
  component: OverviewPage,
});

registerRoute({
  path: '/my-plugin/settings',
  name: 'Plugin Settings',
  exact: true,
  sidebar: 'my-plugin-settings',
  component: SettingsPage,
});

// Register parent sidebar entry
registerSidebarEntry({
  name: 'my-plugin',
  label: 'My Plugin',
  icon: 'mdi:new-box',
  url: '/my-plugin',
});

// Register child sidebar entries
registerSidebarEntry({
  parent: 'my-plugin',
  name: 'my-plugin-overview',
  label: 'Overview',
  url: '/my-plugin',
});

registerSidebarEntry({
  parent: 'my-plugin',
  name: 'my-plugin-settings',
  label: 'Settings',
  url: '/my-plugin/settings',
});

What's new?

Code Purpose
exact: true Ensures the route matches exactly (not just starts with the path)
parent: 'my-plugin' Makes Overview and Settings children of my-plugin
Parent with url Parent is clickable and navigates to Overview page
Child entries Overview and Settings appear as subentries under My Plugin

Step 2: See the Hierarchy

Save and look at your sidebar:

text
My Plugin (🆕)      → expandable parent
├── Overview        → clicks to /my-plugin
└── Settings        → clicks to /my-plugin/settings

Click on "My Plugin" or "Overview" to navigate to the Overview page. Click on "Settings" to navigate to the Settings page. The parent expands to show its children when you're on any of its pages.


Home View vs Cluster View

Headlamp has two main contexts:

  1. Home View — Shown when no cluster is selected (e.g., the cluster selection screen)
  2. Cluster View — Shown when you're working with a specific cluster

By default, sidebar entries appear in the Cluster View. But what if you want to add navigation that's visible even without a cluster?

Adding to Home View

Let's add a sidebar entry that appears in the home view:

tsx
import { registerRoute, registerSidebarEntry } from '@kinvolk/headlamp-plugin/lib';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Typography, Link } from '@mui/material';

// Documentation page (available without a cluster)
function DocsPage() {
  return (
    <SectionBox title="Plugin Documentation">
      <Typography paragraph>
        Welcome to the plugin documentation!
      </Typography>
      <Typography paragraph>
        This page is accessible even when no cluster is selected.
      </Typography>
      <Link href="/">← Back to Clusters</Link>
    </SectionBox>
  );
}

// Register the route (note useClusterURL: false)
registerRoute({
  path: '/plugin-docs',
  name: 'Plugin Docs',
  sidebar: {
    item: 'plugin-docs',
    sidebar: 'HOME',
  },
  component: DocsPage,
  useClusterURL: false,
  noAuthRequired: true,
});

// Register sidebar entry in HOME sidebar
registerSidebarEntry({
  name: 'plugin-docs',
  label: 'Plugin Docs',
  url: '/plugin-docs',
  icon: 'mdi:book-open-variant',
  sidebar: 'HOME',
  useClusterURL: false,
});

Key differences:

Property Purpose
sidebar: { item, sidebar } In registerRoute, specifies which sidebar item to highlight and which sidebar it belongs to
sidebar: 'HOME' In registerSidebarEntry, shows this entry in the home sidebar
useClusterURL: false URL won't include /c/:cluster/ prefix
noAuthRequired: true Page accessible without authentication

Step 2: Test It

  1. Save the file
  2. Go to the home screen (click the Headlamp logo or navigate to http://localhost:3000/)
  3. Look for "Plugin Docs" in the sidebar
  4. Click it—you should see the documentation page!

Complete Example

Here's a complete src/index.tsx that demonstrates both cluster view and home view navigation:

text
/* Detailed source-code truncated for AI context efficiency. */

Troubleshooting

Sidebar Entry Not Appearing

Check your cluster context:

  • Entries without sidebar: 'HOME' only appear when a cluster is selected
  • Make sure you've selected a cluster to see cluster view entries

Check for typos:

  • The name in registerSidebarEntry must match the sidebar in registerRoute

Verify the plugin is loaded:

  • Go to Settings → Plugins
  • Confirm your plugin is listed and enabled

Page Shows 404 or Blank

Check the URL pattern:

  • Cluster view URLs have the format: /c/:cluster/your-path
  • Home view URLs have the format: /your-path

Check useClusterURL:

  • If useClusterURL: false in your route, access it without the cluster prefix
  • If useClusterURL: true (default), include the cluster in the URL

Sidebar Entry Not Highlighted

Ensure sidebar matches name:

tsx
// These must match!
registerRoute({
  path: '/my-plugin',
  sidebar: 'my-plugin',  // ← This...
  component: MyPage,
});

registerSidebarEntry({
  name: 'my-plugin',     // ← ...must match this
  label: 'My Plugin',
  url: '/my-plugin',
});

Subentries Not Showing

Check parent reference:

  • The parent value must exactly match the parent's name
tsx
registerSidebarEntry({
  name: 'my-plugin',  // ← Parent name
  label: 'My Plugin',
});

registerSidebarEntry({
  parent: 'my-plugin',  // ← Must match parent's name
  name: 'my-plugin-child',
  label: 'Child Entry',
  url: '/my-plugin/child',
});

What's Next

You've learned the fundamentals of navigation in Headlamp plugins:

  • ✅ Creating custom pages with registerRoute()
  • ✅ Adding sidebar entries with registerSidebarEntry()
  • ✅ Using icons for visual appeal
  • ✅ Organizing entries with parent-child relationships
  • ✅ Differentiating between home view and cluster view

Your pages are currently static. In the next tutorial, you'll learn how to make them dynamic by fetching and displaying Kubernetes data!

Coming up:

  • Tutorial 4: Working with Kubernetes Data — Fetch cluster info, namespaces using built-in resource classes and ApiProxy
  • Tutorial 5: Advanced Kubernetes Interactions — Create custom resource classes, modify resources via API

Quick Reference

registerRoute Options

tsx
registerRoute({
  path: '/my-path',           // URL path (required)
  sidebar: 'sidebar-name',    // Sidebar entry to highlight (required)
  component: MyComponent,     // React component (required)
  useClusterURL: true,        // Include /c/:cluster/ prefix (default: true)
  noAuthRequired: false,      // Allow unauthenticated access (default: false)
  exact: true,                // Exact path match (default: true)
  name: 'route-name',         // Optional route identifier
});

registerSidebarEntry Options

tsx
registerSidebarEntry({
  name: 'unique-name',        // Unique identifier (required)
  label: 'Display Label',     // Text shown in sidebar (required)
  url: '/my-path',            // URL to navigate to
  icon: 'mdi:icon-name',      // Iconify icon string
  parent: 'parent-name',      // Parent entry name (for subentries)
  sidebar: 'HOME',            // 'HOME' for home view, omit for cluster view
  useClusterURL: true,        // Include /c/:cluster/ prefix (default: true)
});

URL Patterns

Context Pattern Example
Cluster View /c/:cluster/your-path /c/minikube/my-plugin
Home View /your-path /plugin-docs

Tutorials Plugin Development Getting Started Adding Plugin Settings Index (`docs/tutorials/plugin-development/getting-started/adding-plugin-settings/index.md`)


title: "Tutorial 8: Adding Plugin Settings" sidebar_label: "8. Adding Plugin Settings" sidebar_position: 9

Adding Plugin Settings

In Tutorial 7 we extended Headlamp's built-in Pods list and detail views by injecting a Container Images column, an Image Details action button, and a Container Resources section. Those extensions are always active — the user has no way to turn them on or off.

In this tutorial we will make the Image Details button configurable. We'll add a plugin settings page where users can toggle the button on or off with a switch. This will cover:

  • Defining a typed ConfigStore to persist plugin configuration
  • Extracting config logic into a reusable utility module
  • Building a settings UI component with registerPluginSettings
  • Reading config reactively inside a React component using store.useConfig()

Table of Contents

  1. Introduction
  2. How Plugin Settings Work
  3. Step 1 — Define the Config Type and Store
  4. Step 2 — Build the Settings UI Component
  5. Step 3 — Register the Settings Page
  6. Step 4 — Make the Button Respect the Setting
  7. Understanding ConfigStore
  8. Understanding registerPluginSettings
  9. Complete Example
  10. Troubleshooting
  11. What's Next
  12. Quick Reference

Introduction

Headlamp has a built-in Plugin Settings page (accessible via Settings → Plugins → your plugin name). To add a settings UI for your plugin, you register a React component with registerPluginSettings. Headlamp renders your component on that page and your component reads and writes configuration through a ConfigStore instance.

ConfigStore gives you three ways to interact with your plugin's config:

Method When to use
store.get() Read config once, outside React (e.g. in a processor function)
store.set(value) / store.update(partial) Write or update config (from any context)
store.useConfig() Read config reactively inside a React component

What You'll Build

By the end of this tutorial your plugin will have:

  • A src/config.ts module that defines the config type and exports the shared ConfigStore instance
  • A src/settings.tsx settings component with an on/off toggle for the Image Details button
  • The ImageDetailsAction component from Tutorial 7 updated to react to the setting in real time

Prerequisites

Before starting, ensure you have:

Time to complete: ~20 minutes


How Plugin Settings Work

The Image Details button is a React component registered via registerDetailsViewHeaderAction. Because it is a React component, it can call store.useConfig() to subscribe to config changes. When config is saved, the component re-renders automatically — the button appears or disappears immediately without any page navigation.

text
User flips the toggle in Settings → Plugins → hello-headlamp
         │
         ▼
settings.tsx calls onDataChange({ showImageDetails: true/false })
         │
         ▼
User clicks Save → Headlamp persists the config via ConfigStore
         │
         ▼
ImageDetailsAction re-renders via useConfig() → returns null or the button

The key difference compared to using store.get() in a processor function is that useConfig() subscribes to the config. Any component using it re-renders the instant the config is saved — no navigation needed.


Step 1 — Define the Config Type and Store

Start by creating a dedicated file for your plugin's configuration. This keeps the ConfigStore instance and the config type in one place and avoids circular imports when both settings.tsx and index.tsx need to reference them.

Create the file src/config.ts:

ts
import { ConfigStore } from '@kinvolk/headlamp-plugin/lib';

/**
 * Shape of the hello-headlamp plugin configuration.
 * Add new settings here as the plugin grows.
 */
export interface HelloHeadlampConfig {
  /** Whether to show the Image Details button on Pod detail pages. */
  showImageDetails: boolean;
}

/**
 * Default values applied the first time the plugin loads (before the user
 * visits the settings page).
 */
export const DEFAULT_CONFIG: HelloHeadlampConfig = {
  showImageDetails: true,
};

/**
 * Shared ConfigStore instance for the hello-headlamp plugin.
 * Import this from any file that needs to read or write plugin config.
 *
 * The key ('hello-headlamp') must match the plugin name passed to
 * registerPluginSettings.
 */
export const store = new ConfigStore<HelloHeadlampConfig>('hello-headlamp');

/**
 * Convenience helper — returns the current config, falling back to defaults
 * for any keys that haven't been set yet.
 *
 * Safe to call outside React (e.g. in processor functions).
 */
export function getConfig(): HelloHeadlampConfig {
  return { ...DEFAULT_CONFIG, ...store.get() };
}

Why a separate file?

Both settings.tsx and index.tsx need the same ConfigStore instance. Putting it in its own file means:

  • There is exactly one store instance shared across the whole plugin
  • The config type (HelloHeadlampConfig) is defined in one place
  • The getConfig() helper applies defaults so callers never have to worry about undefined values on first load

Step 2 — Build the Settings UI Component

Now create the settings UI component. Headlamp injects the current saved config as data and a staging callback as onDataChange; the user confirms changes by clicking Save.

Create the file src/settings.tsx:

tsx
import { FormControlLabel, Switch, Typography, Box } from '@mui/material';
import { PluginSettingsDetailsProps } from '@kinvolk/headlamp-plugin/lib';
import { DEFAULT_CONFIG } from './config';

/**
 * Settings component for the hello-headlamp plugin.
 * Rendered by Headlamp inside Settings → Plugins → hello-headlamp.
 * Headlamp injects `data` (current saved config) and `onDataChange` (staging callback).
 */
export default function HelloHeadlampSettings({ data, onDataChange }: PluginSettingsDetailsProps) {
  // Merge saved config with defaults so the toggle always has a defined value
  const config = { ...DEFAULT_CONFIG, ...data };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h6" gutterBottom>
        Pod Detail Page
      </Typography>
      <FormControlLabel
        control={
          <Switch
            checked={config.showImageDetails}
            onChange={(event) =>
              onDataChange?.({ ...config, showImageDetails: event.target.checked })
            }
          />
        }
        label="Show Image Details button"
      />
      <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
        When enabled, an Image Details button appears in the Pod detail page header
        showing each container's image and pull policy.
      </Typography>
    </Box>
  );
}

How it works:

What it does
data prop Current saved config injected by Headlamp — undefined until the user has saved at least once
{ ...DEFAULT_CONFIG, ...data } Merges saved values with defaults so the toggle always has a defined value on first load
onDataChange?.({ ... }) Stages the updated config; Headlamp persists it when the user clicks Save

Step 3 — Register the Settings Page

Now wire the settings component into Headlamp. Open src/index.tsx and add the import and registration call:

tsx
import {
  registerResourceTableColumnsProcessor,
  registerDetailsViewHeaderAction,
  registerDetailsViewSectionsProcessor,
  DefaultDetailsViewSection,
  registerPluginSettings,        // ← add
} from '@kinvolk/headlamp-plugin/lib';

import HelloHeadlampSettings from './settings';  // ← add

Then add the registration at the bottom of the file:

tsx
// Register the settings page for this plugin.
// The first argument must match the plugin name in package.json.
registerPluginSettings('hello-headlamp', HelloHeadlampSettings, true);

The third argument (displaySaveButton) controls how the component is rendered and who is responsible for saving:

Value How component is rendered Who saves
false <Comp /> — no props injected The plugin calls store.set() / store.update() directly
true <Comp data={…} onDataChange={…} /> Headlamp — shows a Save button and persists config when clicked

Because our settings component uses data/onDataChange and we want Headlamp to show a Save button, we pass true.

Test it

  1. Save both files
  2. In Headlamp, go to Settings (gear icon) → Plugins
  3. Find hello-headlamp in the list and click it
  4. You should see your settings page with the toggle switch

Step 4 — Make the Button Respect the Setting

The ImageDetailsAction component from Tutorial 7 is always shown on every Pod detail page. Because it is a React component, we can add store.useConfig() directly inside it. The component will re-render and hide the button the instant the config changes — no navigation or page refresh required.

Open src/index.tsx and replace the ImageDetailsAction function from Tutorial 7 with this updated version:

text
/* Detailed source-code truncated for AI context efficiency. */

The two additions compared to Tutorial 7:

  1. store.useConfig() is called at the top of the function — before any early returns — to follow React's rules of hooks
  2. The config check (if (!config.showImageDetails) return null) hides the button when the setting is off

Because useConfig() is a reactive subscription, flipping the toggle in settings causes every mounted ImageDetailsAction instance to re-render immediately.

Test it

  1. Save the file
  2. Go to Settings → Plugins → hello-headlamp, flip the toggle off, and click Save
  3. Navigate to any Pod detail page — the Image Details button should no longer appear in the header
  4. Go back to settings, flip the toggle on, and click Save
  5. Switch back to the Pod detail page — the Image Details button reappears immediately, without a page refresh

Understanding ConfigStore

ConfigStore<T> is a generic class. The type parameter T is the shape of your config object, which gives you type safety when reading and writing config values.

ts
import { ConfigStore } from '@kinvolk/headlamp-plugin/lib';

interface MyConfig {
  featureEnabled: boolean;
  itemsPerPage: number;
}

const store = new ConfigStore<MyConfig>('my-plugin-name');

The config key passed to the constructor must be unique across all plugins. Using your plugin's npm package name (e.g. 'hello-headlamp') is a safe convention.

Reading config

ts
// Outside React — reads the current value synchronously
const config = store.get();   // returns MyConfig | undefined on first load

// Inside a React component — subscribes to changes
function MyComponent() {
  const useConf = store.useConfig();
  const config = useConf();   // re-renders when config changes
  // ...
}

Always apply defaults when reading, because store.get() returns undefined until the user visits the settings page for the first time:

ts
const config = { featureEnabled: true, itemsPerPage: 20, ...store.get() };

Writing config

ts
// Replace the entire config object
store.set({ featureEnabled: true, itemsPerPage: 50 });

// Merge a partial update — other keys are preserved
store.update({ itemsPerPage: 50 });

set() and update() trigger a re-render in any component that subscribes via useConfig().

Where config is persisted

Config is persisted to the browser's local storage, so values survive page refreshes. Config is scoped to the current browser profile — it is not synced across users or clusters.


Understanding registerPluginSettings

registerPluginSettings tells Headlamp to render your settings component on the plugin's settings page:

ts
registerPluginSettings(pluginName, SettingsComponent, displaySaveButton);
Argument Type Description
pluginName string Must match the name field in the plugin's package.json
SettingsComponent React.ComponentType The component Headlamp renders for settings
displaySaveButton boolean false — component rendered without props, plugin saves itself; true — Headlamp injects data/onDataChange and shows a Save button

The `displaySaveButton` modes

displaySaveButton: false — plugin handles saving

Headlamp renders the component with no props: <Comp />. The plugin is responsible for reading config (via store.useConfig()) and writing it (via store.set() / store.update()). Suitable for auto-save patterns such as toggles.

tsx
import { store } from './config';

function Settings() {
  const useConf = store.useConfig();
  const savedConfig = useConf();
  const config = { myFlag: true, ...savedConfig };

  return (
    <Switch
      checked={config.myFlag}
      onChange={e => store.set({ ...config, myFlag: e.target.checked })}
    />
  );
}

registerPluginSettings('my-plugin', Settings, false);

displaySaveButton: true — Headlamp handles saving (used in this tutorial)

Headlamp renders the component as <Comp data={…} onDataChange={…} /> and shows a Save button. The component reads from data and calls onDataChange to stage changes; Headlamp persists them when the user clicks Save. Suitable for forms where the user should confirm before saving.

tsx
import { PluginSettingsDetailsProps } from '@kinvolk/headlamp-plugin/lib';

function Settings({ data, onDataChange }: PluginSettingsDetailsProps) {
  return (
    <TextField
      value={data?.apiEndpoint || ''}
      onChange={e => onDataChange?.({ ...data, apiEndpoint: e.target.value })}
    />
  );
}

registerPluginSettings('my-plugin', Settings, true);

Complete Example

Below is the full set of files for this tutorial. The code in src/index.tsx shown here is only the additions/changes — keep everything else from Tutorial 7 in place.

src/config.ts *(new file)*

ts
import { ConfigStore } from '@kinvolk/headlamp-plugin/lib';

export interface HelloHeadlampConfig {
  showImageDetails: boolean;
}

export const DEFAULT_CONFIG: HelloHeadlampConfig = {
  showImageDetails: true,
};

export const store = new ConfigStore<HelloHeadlampConfig>('hello-headlamp');

export function getConfig(): HelloHeadlampConfig {
  return { ...DEFAULT_CONFIG, ...store.get() };
}

src/settings.tsx *(new file)*

tsx
import { FormControlLabel, Switch, Typography, Box } from '@mui/material';
import { PluginSettingsDetailsProps } from '@kinvolk/headlamp-plugin/lib';
import { DEFAULT_CONFIG } from './config';

export default function HelloHeadlampSettings({ data, onDataChange }: PluginSettingsDetailsProps) {
  const config = { ...DEFAULT_CONFIG, ...data };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h6" gutterBottom>
        Pod Detail Page
      </Typography>
      <FormControlLabel
        control={
          <Switch
            checked={config.showImageDetails}
            onChange={(event) =>
              onDataChange?.({ ...config, showImageDetails: event.target.checked })
            }
          />
        }
        label="Show Image Details button"
      />
      <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
        When enabled, an Image Details button appears in the Pod detail page header
        showing each container's image and pull policy.
      </Typography>
    </Box>
  );
}

Changes to src/index.tsx

Add these imports at the top:

tsx
import { registerPluginSettings } from '@kinvolk/headlamp-plugin/lib';
import { store, DEFAULT_CONFIG } from './config';
import HelloHeadlampSettings from './settings';

Replace the ImageDetailsAction function from Tutorial 7 with:

text
/* Detailed source-code truncated for AI context efficiency. */

Troubleshooting

Settings page is not appearing for my plugin

  • Confirm the first argument to registerPluginSettings exactly matches the name field in package.json. The name is case-sensitive.
  • Make sure registerPluginSettings is called at module level (outside any component), so it runs when the plugin loads.
  • Reload the Headlamp page — newly registered settings sometimes require a full reload.

Toggle is always shown as "off" even after saving

  • Check that onDataChange is being called when the toggle fires — add a console.log inside the onChange handler to confirm.
  • Make sure the name argument to registerPluginSettings exactly matches the plugin's name field in package.json.

Button does not disappear after toggling

  • Ensure store.useConfig() and useConf() are called at the top level of ImageDetailsAction, before any early returns — React hooks must not be called conditionally.
  • Check for typos in the config key ('showImageDetails') — a mismatch between what settings.tsx writes and what ImageDetailsAction reads means they never see the same value.

`store.get()` returns `undefined` on first load

  • This is expected — the user has never set a value yet. Always apply defaults:
ts
const config = { ...DEFAULT_CONFIG, ...store.get() };

What's Next

You've learned how to make your plugin configurable:

  • ✅ Creating a typed ConfigStore with shared defaults in src/config.ts
  • ✅ Building a settings UI with an explicit Save button using registerPluginSettings
  • ✅ Reading config reactively with store.useConfig() inside a React component
  • ✅ Applying defaults to handle first-load before the user visits settings

Coming up in Tutorial 9: Applying Custom Themes

  • Registering a custom MUI theme for your plugin
  • Supporting light and dark mode
  • Overriding colour tokens and typography

Quick Reference

ConfigStore

ts
import { ConfigStore } from '@kinvolk/headlamp-plugin/lib';

// Create a typed store — key must be unique (use your plugin package name)
const store = new ConfigStore<MyConfig>('my-plugin');

// Write
store.set({ key: 'value' });          // Replace entire config
store.update({ key: 'value' });       // Merge partial update

// Read (outside React)
const config = store.get();           // undefined until first save

// Read (inside React component) — reactive
const useConf = store.useConfig();
const config = useConf();             // re-renders on change

registerPluginSettings

ts
import { registerPluginSettings } from '@kinvolk/headlamp-plugin/lib';

// Self-managed saving (auto-save pattern)
registerPluginSettings('my-plugin', MySettingsComponent, false);

// Headlamp-managed saving (explicit Save button)
registerPluginSettings('my-plugin', MySettingsComponent, true);

PluginSettingsDetailsProps (for displaySaveButton: true)

tsx
import { PluginSettingsDetailsProps } from '@kinvolk/headlamp-plugin/lib';

function MySettings({ data, onDataChange }: PluginSettingsDetailsProps) {
  return (
    <input
      value={data?.myKey || ''}
      onChange={e => onDataChange?.({ myKey: e.target.value })}
    />
  );
}

Suggested src/config.ts structure

ts
import { ConfigStore } from '@kinvolk/headlamp-plugin/lib';

export interface MyPluginConfig {
  featureEnabled: boolean;
  // ... add more settings here
}

export const DEFAULT_CONFIG: MyPluginConfig = { featureEnabled: true };

export const store = new ConfigStore<MyPluginConfig>('my-plugin');

export function getConfig(): MyPluginConfig {
  return { ...DEFAULT_CONFIG, ...store.get() };
}

Tutorials Plugin Development Getting Started Applying Custom Themes Index (`docs/tutorials/plugin-development/getting-started/applying-custom-themes/index.md`)


title: "Tutorial 9: Applying Custom Themes" sidebar_label: "9. Applying Custom Themes" sidebar_position: 10

Applying Custom Themes

In Tutorial 8 we made parts of our plugin configurable through a settings page. In this tutorial we will look at a completely different kind of plugin capability: customising the visual appearance of the entire Headlamp application.

Headlamp provides a theming system that lets any plugin register one or more named themes. Once registered, a theme appears as a selectable option in the Themes section of Settings → General, alongside the built-in Light and Dark choices. The entire application — sidebar, navbar, buttons, backgrounds, text — re-renders in your chosen colours.

We will build this up with a concrete, fun example: a Christmas theme that dresses Headlamp in festive deep greens and reds. Along the way we will also learn something equally important: how to make your own plugin components respond to theme changes, so they always look at home regardless of which theme the user has chosen.


Table of Contents

  1. Introduction
  2. Registering the Christmas Theme
  3. The AppTheme Object
  4. Why Your Plugin Components Should Use Theme Colours
  5. Updating the Container Images Tooltip to Use Theme Colours
  6. Replacing the Application Logo
  7. Building a White-label Headlamp Flavour
  8. What's Next
  9. Quick Reference

Introduction

Headlamp's UI is built on Material UI (MUI). Rather than exposing the raw MUI theme object, Headlamp provides a simpler, flatter AppTheme structure. You set the values you care about; everything else inherits from the chosen base theme ('light' or 'dark').

This keeps theming approachable — you don't need to know MUI internals — while still giving fine-grained control over the parts of the UI that matter most: the sidebar, the navbar, the primary accent colour, backgrounds, and typography.

What You'll Build

By the end of this tutorial your plugin will:

  • Register a custom "Christmas" theme — a light base with a deep green sidebar and Christmas red accent — selectable from the theme options
  • Understand why plugin components must read colours from the active theme rather than hard-coding them
  • Update the Container Images tooltip from Tutorial 7 so its colour adapts automatically when any theme (including Christmas) is active
  • Replace the application logo with a custom component using registerAppLogo
  • Combine a custom theme and logo to produce a white-label Headlamp flavour

Prerequisites

Time to complete: ~20 minutes


Registering the Christmas Theme

Registering a theme takes a single import and a single call in src/index.tsx:

tsx
import { registerAppTheme } from '@kinvolk/headlamp-plugin/lib';

registerAppTheme({
  name: 'Christmas',
  base: 'light',
  primary: '#c0392b',
});

That's it. After saving, go to Settings → General and your theme will appear as one of the selectable options in the Themes section.

The name field is what the user sees in the theme options — make it descriptive. Once selected, Headlamp stores the user's choice in local storage and restores it on the next visit.

Now let's flesh it out into a proper Christmas theme. Replace the minimal call above with the full version:

tsx
import { registerAppTheme } from '@kinvolk/headlamp-plugin/lib';

registerAppTheme({
  name: 'Christmas',
  base: 'light',

  // Christmas red for interactive elements — buttons, links, active states
  primary: '#c0392b',
  secondary: '#f9e79f',

  text: {
    primary: '#212121',
  },
  link: {
    color: '#c0392b',
  },

  background: {
    default: '#fafafa',
    surface: '#ffffff',
    muted: '#fdf6e3',
  },

  // Deep Christmas green sidebar with red active highlight
  sidebar: {
    background: '#1b5e20',
    color: '#c8e6c9',
    selectedBackground: '#c0392b',
    selectedColor: '#ffffff',
    actionBackground: '#145214',
  },

  navbar: {
    background: '#1b5e20',
    color: '#f1f8e9',
  },

  radius: 8,
  buttonTextTransform: 'none',
});

Save the file, go to Settings → General, and choose "Christmas" in the Themes section. The sidebar turns deep festive green, the active navigation item gets a red highlight, and all interactive elements (buttons, focus rings, progress bars) switch to Christmas red.


The AppTheme Object

All fields except name are optional. Anything you omit inherits its value from the base theme.

ts
interface AppTheme {
  name: string;
  base?: 'light' | 'dark';      // which built-in theme to extend (default: 'light')

  primary?: string;              // main accent colour — buttons, links, highlights
  secondary?: string;            // secondary accent colour

  text?: {
    primary?: string;            // body text colour
  };
  link?: {
    color?: string;              // hyperlink colour (defaults to primary if unset)
  };

  background?: {
    default?: string;            // main page background
    surface?: string;            // cards, dialogs, dropdown menus
    muted?: string;              // subtle shaded areas (table row stripes, etc.)
  };

  sidebar?: {
    background?: string;         // sidebar background
    color?: string;              // sidebar icon and text colour
    selectedBackground?: string; // highlight behind the active menu item
    selectedColor?: string;      // text/icon colour for the active menu item
    actionBackground?: string;   // background of the collapse/expand button
  };

  navbar?: {
    background?: string;         // top app bar background
    color?: string;              // top app bar icon and text colour
  };

  radius?: number;               // border radius in px — applied to buttons, chips, dialogs
  buttonTextTransform?: 'uppercase' | 'none'; // button label capitalisation
  fontFamily?: string[];         // font stack, e.g. ['Inter', 'sans-serif']
}

Tips on choosing values

  • base — Start from 'light' if your palette is bright, 'dark' if it is muted or dark. Every field you omit falls back to the base values, so you only need to specify what you want to change.
  • primary — This colour drives the most visible interactive elements (active states, focus rings, progress bars). Choose something with enough contrast against both the background.default and sidebar.background.
  • sidebar vs navbar — These two surface areas are visually dominant. Setting them explicitly gives your theme a strong identity even if you leave the rest at base values.

Why Your Plugin Components Should Use Theme Colours

Here is the key insight for this tutorial: registering a theme only changes how Headlamp's own built-in components look. Any colour you hard-code in your own plugin components using a plain style attribute will not change when the user switches themes.

Consider the Container Images tooltip we built in Tutorial 7. It renders like this:

tsx
// ❌ Hard-coded colour — stays this colour regardless of which theme is active
<Tooltip
  title={images.join('\n')}
  placement="bottom-start"
  componentsProps={{
    tooltip: { sx: { bgcolor: '#c0392b' } },
  }}
>
  ...
</Tooltip>

If the user is running the Christmas theme, this looks fine — the red matches. But if they switch to the built-in Dark theme or the Light theme, the tooltip stays Christmas red. It is out of place; it looks like a bug.

The fix is to read the current primary colour from the active MUI theme at render time, using the useTheme hook:

tsx
import { useTheme } from '@mui/material/styles';

function ContainerImagesCell({ pod }: { pod: Pod }) {
  // ✅ Always reads from whatever theme is currently active
  const theme = useTheme();
  const images = pod.spec.containers.map(c => c.image);

  return (
    <Tooltip
      title={images.join('\n')}
      placement="bottom-start"
      componentsProps={{
        tooltip: {
          sx: {
            bgcolor: theme.palette.primary.main,
            color: theme.palette.primary.contrastText,
          },
        },
      }}
    >
      <Typography noWrap style={{ maxWidth: 240, fontSize: 'inherit' }}>
        {images[0]}{images.length > 1 ? ` (+${images.length - 1} more)` : ''}
      </Typography>
    </Tooltip>
  );
}

Now:

  • Christmas theme active → tooltip is Christmas red (#c0392b)
  • Light theme active → tooltip is black (Headlamp's default primary colour)
  • Dark theme active → tooltip is white (Headlamp's default primary colour)
  • Any future custom theme → tooltip automatically matches its primary colour

This is the right pattern for every colour a plugin component displays. Whenever you would otherwise write a colour literal like '#c0392b' or 'rgba(255,0,0,0.8)', ask: "Should this change when the user switches themes?". If yes, reach for useTheme() and pull the value from theme.palette.

The most useful theme palette values

theme.palette.* What it represents
primary.main The primary accent colour — same as AppTheme.primary
primary.contrastText A text colour guaranteed to be readable on top of primary.main
secondary.main The secondary accent colour
background.default The main page background
background.paper Cards, dialogs, surface areas
text.primary The main body text colour
text.secondary Subdued text, hints, secondary labels

Updating the Container Images Tooltip to Use Theme Colours

Let's apply this pattern to the actual code from Tutorial 7. We need to:

  1. Extract the tooltip cell into a small React component (so we can use the useTheme hook)
  2. Replace the hard-coded colour with theme.palette.primary.main

Step 1: Import `useTheme`

Add useTheme to your existing MUI imports in src/index.tsx:

tsx
import { Tooltip, Typography } from '@mui/material';
import { useTheme } from '@mui/material/styles';

Step 2: Create the `ContainerImagesCell` Component

Add this component before the registerResourceTableColumnsProcessor call:

tsx
function ContainerImagesCell({ pod }: { pod: Pod }) {
  const theme = useTheme();
  const images = pod.spec.containers.map(c => c.image);

  return (
    <Tooltip
      title={images.join('\n')}
      placement="bottom-start"
      componentsProps={{
        tooltip: {
          sx: {
            bgcolor: theme.palette.primary.main,
            color: theme.palette.primary.contrastText,
            fontSize: '0.8rem',
            whiteSpace: 'pre-line',
          },
        },
      }}
    >
      <Typography noWrap style={{ maxWidth: 240, fontSize: 'inherit' }}>
        {images[0]}{images.length > 1 ? ` (+${images.length - 1} more)` : ''}
      </Typography>
    </Tooltip>
  );
}

Step 3: Update the Column Registration

In your existing registerResourceTableColumnsProcessor call, replace the inline render function with the new component:

tsx
registerResourceTableColumnsProcessor(function addContainerImagesColumn({ id, columns }) {
  if (id !== 'headlamp-pods') {
    return columns;
  }

  const podColumns = columns as ResourceTableColumn<Pod>[];

  podColumns.push({
    id: 'hello-headlamp-container-images',
    label: 'Container Images',
    getValue: (pod: Pod) => pod.spec.containers.map(c => c.image).join(', '),
    render: (pod: Pod) => <ContainerImagesCell pod={pod} />,  // ← uses useTheme internally
  });

  return columns;
});

Step 4: Test It

  1. Save the file

  2. Navigate to Workloads → Pods and hover over a cell in the Container Images column

  3. You should see the tooltip appear with a Christmas red background — because the Christmas theme is active and its primary is #c0392b

  4. Now go to Settings → General and choose Light in the Themes section, then hover again

  5. The tooltip is now black — Headlamp's default primary colour for the Light theme

The tooltip automatically follows whichever theme the user has selected, with no extra code on your part. This is what it means for a plugin to be coherent with the app.


registerAppLogo lets you swap out the Headlamp logo that appears in the sidebar and the top bar. It is a natural companion to registerAppTheme — combine them and your users see your branding everywhere.

registerAppLogo accepts either a React element (always renders the same thing) or a React component that receives AppLogoProps and can adapt to context.

For a festive touch, let's swap the Headlamp logo for a Christmas tree. The component receives AppLogoProps and can adapt based on logoType (whether the sidebar is expanded or collapsed):

tsx
import { AppLogoProps, registerAppLogo } from '@kinvolk/headlamp-plugin/lib';

function ChristmasLogo({ logoType }: AppLogoProps) {
  const style = {
    background: 'rgba(255, 255, 255, 0.15)',
    borderRadius: 4,
    padding: '2px 8px',
  };

  if (logoType === 'small') {
    return <span style={{ ...style, fontSize: '1.4rem', padding: '2px 4px' }}>🎄</span>;
  }

  return (
    <span style={{ ...style, fontSize: '1.1rem', fontWeight: 700, letterSpacing: '0.02em' }}>
      🎄 Headlamp
    </span>
  );
}

registerAppLogo(ChristmasLogo);

Only one logo at a time. If multiple plugins call registerAppLogo, the last registration wins. This is intentional — a single logo is always shown.


Building a White-label Headlamp Flavour

Combining a custom theme and a custom logo is the standard pattern for shipping a branded flavour of Headlamp — for example, an internal platform portal, a managed Kubernetes product, or an enterprise console.

A typical white-label src/index.tsx looks like this:

tsx
import { registerAppLogo, registerAppTheme, AppLogoProps } from '@kinvolk/headlamp-plugin/lib';

// ── 1. Register a branded theme ───────────────────────────────────────────────

registerAppTheme({
  name: 'MyPlatform',
  base: 'light',
  primary: '#00796b',
  secondary: '#e0f2f1',
  sidebar: {
    background: '#1a2b3c',
    color: '#b0bec5',
    selectedBackground: '#00796b',
    selectedColor: '#ffffff',
    actionBackground: '#0d1b2a',
  },
  navbar: {
    background: '#1a2b3c',
    color: '#eceff1',
  },
  radius: 8,
  buttonTextTransform: 'none',
});

// ── 2. Replace the logo ────────────────────────────────────────────────────────

function MyPlatformLogo({ logoType, themeName }: AppLogoProps) {
  if (logoType === 'small') {
    return <span style={{ fontWeight: 'bold' }}>MP</span>;
  }
  const color = themeName === 'dark' ? '#4db6ac' : '#00796b';
  return <span style={{ fontWeight: 700, fontSize: '1.2rem', color }}>MyPlatform</span>;
}

registerAppLogo(MyPlatformLogo);

After the user chooses the "MyPlatform" theme in the Themes section of Settings → General, the entire application takes on the branded look — your logo, your colours, your typography.


What's Next

You've learned how to fully customise the look of the whole Headlamp application, and — just as importantly — how to make your plugin's own components respect that customisation:

  • ✅ Using registerAppTheme to register a named theme (the Christmas theme)
  • ✅ Understanding every field in the AppTheme object
  • ✅ Why hard-coding colours in plugin components breaks theme coherence
  • ✅ Using useTheme() to read the active theme's palette at render time
  • ✅ Applying this pattern to the Container Images tooltip from Tutorial 7
  • ✅ Replacing the application logo with registerAppLogo
  • ✅ Combining theme and logo to ship a white-label Headlamp flavour

Coming up in Tutorial 10: Adding Custom Map Nodes

  • Registering custom node types for the Headlamp resource map
  • Controlling how your resources are visualised in the topology view

Quick Reference

registerAppTheme

tsx
import { registerAppTheme } from '@kinvolk/headlamp-plugin/lib';

registerAppTheme({
  name: 'My Theme',          // shown in the Themes section of Settings → General (required)
  base: 'light',             // 'light' | 'dark' — what to inherit from (default: 'light')

  primary: '#hex',           // accent colour
  secondary: '#hex',         // secondary accent

  text: { primary: '#hex' },
  link: { color: '#hex' },

  background: {
    default: '#hex',         // page background
    surface: '#hex',         // cards / dialogs
    muted: '#hex',           // subtle shading
  },

  sidebar: {
    background: '#hex',
    color: '#hex',
    selectedBackground: '#hex',
    selectedColor: '#hex',
    actionBackground: '#hex',
  },

  navbar: {
    background: '#hex',
    color: '#hex',
  },

  radius: 8,                          // border radius in px
  buttonTextTransform: 'none',        // 'none' | 'uppercase'
  fontFamily: ['Inter', 'sans-serif'],
});

Using `useTheme` in plugin components

tsx
import { useTheme } from '@mui/material/styles';

function MyPluginComponent() {
  const theme = useTheme();

  return (
    <div style={{ color: theme.palette.primary.main }}>
      This text colour matches the active theme's primary accent.
    </div>
  );
}

Useful palette tokens:

Token Meaning
theme.palette.primary.main Primary accent (buttons, links, highlights)
theme.palette.primary.contrastText Readable text colour on top of primary.main
theme.palette.secondary.main Secondary accent
theme.palette.background.default Page background
theme.palette.background.paper Card / dialog surface
theme.palette.text.primary Main body text
theme.palette.text.secondary Subdued / secondary text
tsx
import { registerAppLogo, AppLogoProps } from '@kinvolk/headlamp-plugin/lib';

// Simple — a React element (always the same)
registerAppLogo(<img src="/my-logo.svg" alt="My Logo" style={{ height: 32 }} />);

// Adaptive — a React component that receives context props
function MyLogo({ logoType, themeName }: AppLogoProps) {
  // logoType: 'large' (sidebar expanded) | 'small' (sidebar collapsed)
  // themeName: 'light' | 'dark'
  if (logoType === 'small') {
    return <span style={{ fontWeight: 'bold' }}>ML</span>;
  }
  return (
    <span style={{ fontWeight: 700, color: themeName === 'dark' ? '#fff' : '#000' }}>
      MyLogo
    </span>
  );
}

registerAppLogo(MyLogo);

Tutorials Plugin Development Getting Started Building List And Detail Pages Index (`docs/tutorials/plugin-development/getting-started/building-list-and-detail-pages/index.md`)


title: "Tutorial 6: Building List & Detail Pages" sidebar_label: "6. Building List & Detail Pages" sidebar_position: 7

Building List & Detail Pages

This tutorial shows you how to build list and detail pages that match Headlamp's core UI. We'll achieve this by using the Headlamp CommonComponents ResourceListView for powerful, feature-rich list pages and DetailsGrid for comprehensive detail views.


Table of Contents

  1. Introduction
  2. Building a Pod List Page
  3. Understanding ResourceListView
  4. Building a Pod Detail Page
  5. Understanding DetailsGrid
  6. Adding Actions to Detail Page
  7. Navigation Between List and Detail
  8. Customizing Columns and Details
  9. Troubleshooting
  10. What's Next
  11. Quick Reference

Introduction

In Tutorial 5, you created a custom MyPod class and built a simple Pods page using a basic Material UI table. While that works, Headlamp provides powerful components that give you professional list and detail views with minimal code:

Component Purpose Features
ResourceListView Display lists of Kubernetes resources Sorting, filtering, pagination, row actions
DetailsGrid Display detailed information about a single resource Automatic metadata display, extra info sections, event integration

What You'll Build

By the end of this tutorial, you'll have:

  • A professional Pod list page using ResourceListView with:
    • Custom columns (Name, Namespace, Phase, Container Images, Age)
    • Sorting, filtering, and clickable names linking to the detail page
  • A Pod detail page using DetailsGrid with:
    • Standard metadata display
    • Custom info fields (Phase, Node, Pod IP)
    • A custom Containers section using SimpleTable
    • An "Evict Pod" action button in the header
    • A back link to the list page

Prerequisites

Before starting, ensure you have:

Time to complete: ~30 minutes


Building a Pod List Page

Let's replace the simple table from Tutorial 5 with ResourceListView.

Step 1: Update Your Pod List Page

Open your src/index.tsx and update the MyPodsPage component:

tsx
import {
  registerRoute,
  registerSidebarEntry,
} from '@kinvolk/headlamp-plugin/lib';
import { ResourceListView } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { MyPod } from './resources/pod';

function MyPodsPage() {
  return (
    <ResourceListView
      title="My Pods"
      id="my-plugin-pods"
      resourceClass={MyPod}
      columns={[
        'name',
        'namespace',
        {
          id: 'containerImages',
          label: 'Container Images',
          getValue: (pod: MyPod) => pod.containerImages?.join(', ') || '-',
        },
        {
          id: 'age',
          label: 'Age',
          getValue: (pod: MyPod) => pod.age,
        },
      ]}
    />
  );
}

registerRoute({
  path: '/my-plugin/pods',
  sidebar: 'my-plugin-pods',
  component: MyPodsPage,
  exact: true,
});

registerSidebarEntry({
  parent: 'my-plugin',
  name: 'my-plugin-pods',
  label: 'Pods',
  url: '/my-plugin/pods',
});

What changed?

Before (Tutorial 5) After (Tutorial 6)
Manual useList() hook resourceClass prop handles it automatically
Manual loading/error states Automatic handling
Basic `` component Full-featured ResourceListView
Manual pagination Built-in pagination
No filtering Automatic namespace filtering

Step 2: Test It

  1. Save the file
  2. Navigate to My Plugin → Pods in the sidebar
  3. You should see a professional list view with:
    • Sortable columns
    • Namespace filter (top-right)
    • Row selection checkboxes
    • Context menu on each row (three dots)

Notice the improvements:

  • Click column headers to sort
  • Use the namespace filter to show pods from specific namespaces
  • Click the three dots on a row to see actions
  • Select multiple rows with checkboxes

Understanding ResourceListView

Now that you've seen it in action, let's look at what ResourceListView gave you for free. Under the hood it handles:

  • Data fetching — Automatically calls useList() from your resource class — no manual hook needed
  • Loading & error states — Automatic handling, no boilerplate required
  • Sorting — Click any column header to sort
  • Filtering — Namespace filter for namespaced resources; per-column filters when Show/Hide Filters button is clicked
  • Pagination — Large datasets are paginated automatically
  • Row context menu — Three-dot menu on every row (you'll extend this in the Customizing section)
  • Bulk operations — Row checkboxes for selecting multiple resources

The `resourceClass` vs `data` prop

ResourceListView supports two modes:

Prop When to use
resourceClass={MyPod} Let the component fetch data — the standard approach
data={items} Pass pre-fetched or transformed data yourself

The `id` prop

Plugins target tables by id, which is how the column processors in Tutorial 7 find the table they want. Always pass one with your own prefix: without it, ResourceListView derives headlamp- from the resource class — the same ID Headlamp's own table for that resource uses — so processors aimed at the built-in table would hit yours too.

Built-in column shortcuts

'name', 'namespace', 'age', and 'cluster' can be passed as plain strings. They are fully configured columns (including getValue, render, and sorting) — and 'name' renders a link to Headlamp's native detail page for that resource. You can always replace a shortcut with a full column object to override its behaviour.

tsx
// Sorting, labels, and links — all configured:
columns={['name', 'namespace', 'age']}

Custom columns: `getValue` and `render`

Once you outgrow the built-in shortcuts, you define a column as an object. Two props control how the column behaves:

Prop Purpose Required?
getValue Returns a plain string or number — used for sorting, filtering, and CSV export Yes, for custom columns
render Returns a React node — used for what's actually displayed in the cell Optional; falls back to getValue if omitted

The separation matters: the table sorts and filters against getValue (a consistent raw value), while render handles the visual presentation.

tsx
{
  id: 'phase',
  label: 'Phase',
  // Used for sorting A→Z and multi-select filtering:
  getValue: (pod: MyPod) => pod.jsonData.status?.phase || 'Unknown',
  // Used for what the user actually sees in the cell:
  render: (pod: MyPod) => {
    const phase = pod.jsonData.status?.phase;
    const colorMap = { Running: 'success', Failed: 'error', Pending: 'warning' };
    return <Chip label={phase || 'Unknown'} color={colorMap[phase] ?? 'default'} size="small" />;
  },
}

If you only need plain text, you can omit render entirely — getValue covers both:

tsx
{
  id: 'containerImages',
  label: 'Container Images',
  getValue: (pod: MyPod) => pod.containerImages?.join(', ') || '-',
}

Building a Pod Detail Page

Let's create a detail page for individual pods.

Step 1: Create the Detail Page Component

Add a new component to your src/index.tsx:

text
/* Detailed source-code truncated for AI context efficiency. */

Step 2: Register the Detail Route

Add the route registration for the detail page. The :namespace and :name segments in the path are URL parameters: for a URL like /my-plugin/default/pods/nginx-pod, namespace will be "default" and name will be "nginx-pod". These values are injected into MyPodDetailPage via useParams<{ name: string; namespace?: string }>(), which is why we can read const { name, namespace } = params; in the component:

tsx
registerRoute({
  path: '/my-plugin/:namespace/pods/:name',
  sidebar: 'my-plugin-pods',
  component: MyPodDetailPage,
});

Step 3: Test It

Nothing links to your detail page yet, so open it directly in the browser.

  1. Save the file
  2. Append /c/<cluster>/my-plugin/<namespace>/pods/ to your Headlamp URL
  3. You should see the detail page with:
    • Standard metadata (name, namespace, labels, etc.)
    • Your custom fields (Phase, Node, Pod IP)
    • Your custom Containers section

Note: Registering a route only tells Headlamp which component to render for a URL — it doesn't create a link to it. Your list page still uses the 'name' column shortcut, which points at Headlamp's built-in Pod details (shown in a drawer by default), not at your page. You'll point it at your own detail page in Navigation Between List and Detail.


Understanding DetailsGrid

Now that you've seen it working, here's what DetailsGrid handled automatically:

  • Resource fetching — Calls useGet() from your resource class using the name and namespace props
  • Loading & error states — Automatic handling with consistent UI
  • Standard metadata display — Name, namespace, labels, annotations, and creation time are always shown
  • Back navigation — backLink renders a back button in the header
  • extraInfo — A list of name/value pairs rendered as additional rows in the metadata table
  • extraSections — Arbitrary React content rendered as full-width sections below the metadata
  • Events — Pass withEvents to append the Kubernetes event stream for the resource:
tsx
<DetailsGrid
  resourceType={MyPod}
  name={name}
  namespace={namespace}
  withEvents
/>

The `extraInfo` vs `extraSections` choice

Use When
extraInfo Key/value facts that belong alongside the standard metadata (phase, node, pod IP)
extraSections Richer content that needs its own heading and layout (container list, status table)

Basic Usage

tsx
import { DetailsGrid } from '@kinvolk/headlamp-plugin/lib/CommonComponents';

<DetailsGrid
  resourceType={MyPod}
  name={podName}
  namespace={namespace}
/>

With just those three props you get the full standard detail layout — identical to what Headlamp shows for its own built-in resources.


Adding Actions to Detail Page

DetailsGrid already provides default actions for common operations — for example, Pods automatically get Edit and Evict buttons in the header. But you'll often want to add your own custom actions.

The actions prop lets you place action buttons in the detail page header. Each action is rendered using ActionButton, a Headlamp CommonComponent that renders an icon button with a tooltip. It keeps your actions visually consistent with Headlamp's built-in actions.

tsx
<ActionButton
  description="Tooltip text"    // Shown on hover
  icon="mdi:icon-name"          // Iconify icon identifier
  onClick={() => { ... }}        // Click handler
/>

Note: Since DetailsGrid already provides a default evict action for Pods, we'll technically be adding a second one here. That's fine for learning — it lets us reuse the evict logic from Tutorial 5 while focusing on how custom actions work. In a real plugin you'd use this pattern for actions that aren't provided by default.

Step 1: Add a Custom Evict Action to DetailsGrid

Let's integrate the evict functionality from Tutorial 5 into our DetailsGrid header. Update your MyPodDetailPage:

text
/* Detailed source-code truncated for AI context efficiency. */

What's new?

Addition Purpose
actions prop Function that returns an array of action objects for the header
ActionButton component Pre-styled button component for header actions
handleEvict function Reuses the evict logic from Tutorial 5
Confirmation dialog Uses window.confirm to confirm eviction
Navigation after eviction Automatically navigates back to list after successful eviction
Snackbar Shows success/error messages

Step 2: Test the Evict Action

  1. Save the file
  2. Navigate to a pod detail page
  3. Look for the "Evict Pod" button in the header (top-right area)
  4. Click the button
  5. Confirm the eviction in the dialog
  6. Watch the snackbar notification and automatic navigation back to the list

Understanding Action Format

The actions prop accepts a function that receives the resource and returns an array of action objects:

tsx
actions={pod => {
  if (!pod) return [];
  
  return [
    {
      id: 'unique-action-id',  // Unique identifier
      action: <ActionButton ... />,  // React node (typically ActionButton)
    },
  ];
}}

Adding Multiple Actions

You can add multiple action buttons to the header:

tsx
actions={pod => {
  if (!pod) return [];
  
  return [
    {
      id: 'view-logs',
      action: (
        <ActionButton
          description="View Logs"
          icon="mdi:file-document-box-outline"
          onClick={() => {
            // Navigate to logs or open log viewer
            console.log('View logs for', pod.metadata.name);
          }}
        />
      ),
    },
    {
      id: 'evict-pod',
      action: (
        <ActionButton
          description="Evict Pod"
          icon="mdi:delete-outline"
          onClick={() => {
            if (window.confirm(`Evict pod "${pod.metadata.name}"?`)) {
              handleEvict(pod);
            }
          }}
        />
      ),
    },
  ];
}}

Conditional Actions

You can conditionally show actions based on the resource state:

tsx
actions={pod => {
  if (!pod) return [];
  
  const actions = [];
  
  // Only show evict for running pods
  if (pod.jsonData.status?.phase === 'Running') {
    actions.push({
      id: 'evict-pod',
      action: (
        <ActionButton
          description="Evict Pod"
          icon="mdi:delete-outline"
          onClick={() => {
            if (window.confirm(`Evict pod "${pod.metadata.name}"?`)) {
              handleEvict(pod);
            }
          }}
        />
      ),
    });
  }
  
  return actions;
}}

Key Points:

  • Actions are evaluated when the resource loads, so you can customize based on resource state
  • Use ActionButton for consistent styling with Headlamp's design system
  • Always provide user feedback (Snackbar, dialogs) for destructive actions
  • Consider navigating away after successful destructive operations

Now we need to make the list page link to the detail page. ResourceListView automatically makes resource names clickable, but we need to configure the route pattern.

The built-in 'name' column shortcut links to Headlamp's native detail page for a resource. Since we registered our own detail route at /my-plugin/:namespace/pods/:name, we need a custom name column that navigates there instead.

URL structure note: Plugin routes are registered without the /c/<cluster> prefix (e.g. path: '/my-plugin/:namespace/pods/:name'). Headlamp's router adds /c/<cluster-name> in the browser automatically. When you build href values or backLink strings yourself, you must include it — which is why getCluster() is needed.

Replace only the MyPodsPage function in your src/index.tsx (keep MyPodDetailPage and all registerRoute/registerSidebarEntry calls). This version uses Headlamp's Link CommonComponent for navigation.

tsx
import {
  registerRoute,
  registerSidebarEntry,
} from '@kinvolk/headlamp-plugin/lib';
import { getCluster } from '@kinvolk/headlamp-plugin/lib/Utils';
import { ResourceListView, Link } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { MyPod } from './resources/pod';

function MyPodsPage() {
  const cluster = getCluster();

  return (
    <ResourceListView
      title="My Pods"
      id="my-plugin-pods"
      resourceClass={MyPod}
      columns={[
        {
          id: 'name',
          label: 'Name',
          getValue: (pod: MyPod) => pod.metadata.name,
          render: (pod: MyPod) => (
            <Link
              to={`/c/${cluster}/my-plugin/${pod.metadata.namespace}/pods/${pod.metadata.name}`}
            >
              {pod.metadata.name}
            </Link>
          ),
        },
        'namespace',
        {
          id: 'containerImages',
          label: 'Container Images',
          getValue: (pod: MyPod) => pod.containerImages?.join(', ') || '-',
        },
        {
          id: 'age',
          label: 'Age',
          getValue: (pod: MyPod) => pod.age,
        },
      ]}
    />
  );
}

The backLink prop was already added to MyPodDetailPage in the Building a Pod Detail Page section. It accepts a path string (including the /c/<cluster> prefix) and renders a back button in the detail page header.

Step 3: Test Navigation

  1. Save both files
  2. Go to the Pods list page
  3. Click on a pod name → should navigate to detail page
  4. Click "Back" → should return to list page

Customizing Columns and Details

Custom Column Rendering

You can customize how columns are displayed using the render property:

tsx
columns={[
  {
    id: 'phase',
    label: 'Phase',
    getValue: (pod: MyPod) => pod.jsonData.status?.phase || 'Unknown',
    render: (pod: MyPod) => {
      const phase = pod.jsonData.status?.phase;
      const color = phase === 'Running' ? 'green' : phase === 'Failed' ? 'red' : 'orange';
      return (
        <span style={{ color }}>
          {phase || 'Unknown'}
        </span>
      );
    },
  },
]}

Column Filters

Add filtering to columns:

tsx
columns={[
  {
    id: 'phase',
    label: 'Phase',
    getValue: (pod: MyPod) => pod.jsonData.status?.phase || 'Unknown',
    filterVariant: 'multi-select', // or 'text', 'select', etc.
  },
]}

Custom Detail Sections

You can add multiple custom sections:

tsx
extraSections={pod => {
  if (!pod) return [];
  
  return [
    {
      id: 'my-plugin-pod-containers',
      section: (
        <SectionBox title="Containers">
          {/* Your container details */}
        </SectionBox>
      ),
    },
    {
      id: 'my-plugin-pod-status',
      section: (
        <SectionBox title="Status">
          <Typography>
            Phase: {pod.jsonData.status?.phase}
          </Typography>
          <Typography>
            Pod IP: {pod.jsonData.status?.podIP || 'Not assigned'}
          </Typography>
        </SectionBox>
      ),
    },
  ];
}}

Complete Example

Here's the final src/index.tsx for this tutorial. Replace everything in the file with this. It pulls together the list page (with Phase column and clickable names), the detail page (with custom info, sections, and the evict action), and navigation between them.

text
/* Detailed source-code truncated for AI context efficiency. */

Troubleshooting

ResourceListView Not Showing Data

Check your resource class:

  • Ensure MyPod extends KubeObject correctly
  • Verify static properties (apiVersion, apiName, kind, isNamespaced) are set

Check the columns:

  • Ensure getValue functions return valid data
  • Check browser console for errors

DetailsGrid Not Loading

Check route parameters:

  • Ensure name is provided in the URL
  • For namespaced resources, ensure namespace is provided

Check resource class:

  • Verify useGet() works: const [pod, error] = MyPod.useGet(name, namespace);

Check route registration:

  • Ensure the list route has exact: true to prevent it matching detail URLs
  • The detail route (/my-plugin/:namespace/pods/:name) must match the URL pattern used in the href

Check link implementation:

  • Verify the href includes the cluster prefix (/c/${cluster}/...)

Columns Not Sorting/Filtering

Check column configuration:

  • Ensure getValue is provided for sortable columns
  • For filters, ensure filterVariant is set correctly

What's Next

You've learned how to build professional list and detail pages:

  • ✅ Using ResourceListView for feature-rich list pages
  • ✅ Using DetailsGrid for comprehensive detail views
  • ✅ Adding action buttons to DetailsGrid header
  • ✅ Navigation between list and detail pages
  • ✅ Customizing columns and detail sections

Coming up in Tutorial 7: Extending Existing Resource Views

  • Adding custom sections to built-in resource detail pages
  • Customizing existing list views
  • Integrating with Headlamp's default views

Quick Reference

ResourceListView Props

tsx
<ResourceListView
  title="My Resources"              // Page title (required)
  resourceClass={MyResource}        // Resource class — required unless using `data`
  columns={[...]}                   // Column definitions (required)
  id="my-plugin-resources"          // Table ID for plugin processors — use your own prefix (optional)
  hideColumns={['column-id']}       // Columns to hide (optional)
  actions={[...]}                   // Row context-menu actions — plain array, not a function (optional)
  data={items}                      // Pre-fetched data — use instead of resourceClass (optional)
/>

Column Definition

tsx
// Simple string (uses default getValue)
'name'

// Object with custom configuration
{
  id: 'custom-column',              // Unique identifier
  label: 'Display Name',             // Column header
  getValue: (item) => item.field,    // Value getter (for sorting/filtering)
  render: (item) => <Component />,  // Custom render function
  gridTemplate: 1,                  // Column width: number → "fr" (e.g. 1 → "1fr"), or string e.g. "1.5fr", "min-content"
  filterVariant: 'multi-select',     // 'autocomplete' | 'checkbox' | 'date' | 'date-range' | 'datetime' | 'datetime-range' | 'multi-select' | 'range' | 'range-slider' | 'select' | 'text' | 'time' | 'time-range'
  sort: true,                        // Enable/disable sorting
}

DetailsGrid Props

tsx
<DetailsGrid
  resourceType={MyResource}          // Resource class — uses useGet automatically (required)
  name={resourceName}                // Resource name (required)
  namespace={namespace}              // Namespace — required for namespaced resources
  cluster={cluster}                  // Cluster name (optional, defaults to current cluster)
  backLink="/path/to/list"           // Back button destination, must include /c/<cluster> prefix (optional)
  withEvents={true}                  // Append the Kubernetes event stream for this resource (optional)
  actions={item => [...]}            // Header action buttons — function, not an array (optional)
  extraInfo={item => [...]}          // Additional key/value info rows (optional)
  extraSections={item => [...]}      // Additional full-width sections (optional)
/>

Actions Definition for DetailsGrid

tsx
actions={item => {
  if (!item) return [];
  
  return [
    {
      id: 'action-id',               // Unique identifier
      action: <ActionButton          // React node (typically ActionButton)
        description="Action Label"
        icon="mdi:icon-name"
        onClick={() => {
          // Handle action
        }}
      />,
    },
  ];
}}

Extra Info Field

tsx
{
  name: 'Field Name',                 // Label
  value: 'Field Value',              // Value (string or React node)
  hide: (item) => boolean,           // Conditionally hide field
}

Extra Section

tsx
{
  id: 'unique-section-id',          // Unique identifier
  section: <ReactNode />,            // Section content (typically SectionBox)
}

Tutorials Plugin Development Getting Started Creating Your First Plugin Index (`docs/tutorials/plugin-development/getting-started/creating-your-first-plugin/index.md`)


title: "Tutorial 2: Creating Your First Plugin" sidebar_label: "2. Creating Your First Plugin" sidebar_position: 3

Creating Your First Headlamp Plugin

This tutorial guides you through creating your first Headlamp plugin from scratch. By the end, you'll have a working plugin that appears in Headlamp's UI and you'll understand how hot reloading makes plugin development fast and enjoyable.


Table of Contents

  1. Introduction
  2. Understanding the Plugin System
  3. Create Your First Plugin
  4. Explore the Plugin Structure
  5. Run the Plugin in Development Mode
  6. See Your Plugin in Headlamp
  7. Hot Reloading in Action
  8. Understanding What Happened
  9. Troubleshooting
  10. What's Next
  11. Quick Reference

Introduction

In Tutorial 1, you set up Headlamp to run locally from source. Now it's time to extend it!

Plugins let you add new features to Headlamp without modifying its core code. You can:

  • Add buttons, menus, and panels to the UI
  • Create entirely new pages
  • Customize how Kubernetes resources are displayed
  • Change themes and branding
  • And much more!

What You'll Build

In this tutorial, you'll create a simple plugin called hello-headlamp that:

  1. Displays "Hello" in Headlamp's top navigation bar
  2. Appears in the Settings → Plugins list

This gives you the foundation for all future plugin development.

Prerequisites

Before starting, ensure you have:

Verify your setup:

bash
node --version    # Should be v22.0.0 or higher
npm --version     # Should be 11.0.0 or higher

Time to complete: ~15 minutes


Understanding the Plugin System

Before we dive into code, let's understand how plugins work at a high level.

How Plugins Work

text
┌─────────────────────────────────────────────────────────┐
│                      Headlamp                           │
│  ┌─────────────────────────────────────────────────┐    │
│  │                  Plugin Registry                │    │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐          │    │
│  │  │ Plugin A│  │ Plugin B│  │ Plugin C│   ...    │    │
│  │  └─────────┘  └─────────┘  └─────────┘          │    │
│  └─────────────────────────────────────────────────┘    │
│                         ↓                               │
│  ┌─────────────────────────────────────────────────┐    │
│  │               Headlamp UI                       │    │
│  │   (App Bar, Sidebar, Pages, Details Views...)   │    │
│  └─────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────┘
  1. Plugins are JavaScript/TypeScript modules — They export code that Headlamp loads at startup
  2. Plugins register themselves — Using functions like registerAppBarAction() to tell Headlamp where to display their components
  3. Headlamp discovers plugins automatically — During development, plugins make themselves available to Headlamp

Plugin Locations

Headlamp looks for plugins in specific directories depending on how you're running it:

Mode Plugin Location
Development ~/.config/Headlamp/plugins/ (Linux/macOS) or %APPDATA%\Headlamp\Config\plugins\ (Windows) — plugins running npm start automatically copy here
Desktop App ~/.config/Headlamp/plugins/ (Linux/macOS) or %APPDATA%\Headlamp\Config\plugins\ (Windows)
In-Cluster Configured via Headlamp deployment

For this tutorial, we'll use development mode, the easiest way to build and test plugins.


Create Your First Plugin

Let's create your first plugin! We'll use the headlamp-plugin tool which scaffolds a ready-to-use plugin project.

Step 1: Choose a Location

Create your plugin outside the Headlamp repository. This keeps your plugin code separate and organized.

bash
# Go to your projects directory (create one if needed)
mkdir -p ~/projects
cd ~/projects

Why outside the Headlamp repo? Plugins are independent projects with their own dependencies. Keeping them separate makes them easier to manage, version, and share.

Step 2: Create the Plugin

Run the following command to scaffold a new plugin:

bash
npx --yes @kinvolk/headlamp-plugin create hello-headlamp

You'll see output like this:

text
Creating plugin: hello-headlamp...
...
Run `npm audit` for details.
"hello-headlamp" created.
1) Run the Headlamp app (so the plugin can be used).
2) Open hello-headlamp/src/index.tsx in your editor.
3) Start development server of the plugin watching for plugin changes.
  cd "hello-headlamp"
  npm run start
4) See the plugin inside Headlamp.

What just happened?

  • npx downloaded and ran the @kinvolk/headlamp-plugin tool
  • The create command generated a new plugin folder called hello-headlamp
  • Dependencies were automatically installed (you saw npm ci in the output)
  • The folder contains all the files you need to start developing

Explore the Plugin Structure

Let's look at what was created:

text
hello-headlamp/
├── src/
│   └── index.tsx         # 👈 Main entry point - your plugin code goes here
├── package.json          # 👈 Plugin metadata and npm scripts
├── tsconfig.json         # TypeScript configuration
└── README.md             # Plugin documentation

The Entry Point: `src/index.tsx`

Open src/index.tsx in your editor. You'll see:

tsx
import { registerAppBarAction } from '@kinvolk/headlamp-plugin/lib';

// Below are some imports you may want to use.
//   See README.md for links to plugin development documentation.
// import { Headlamp, K8s, useTranslation } from '@kinvolk/headlamp-plugin/lib';
// import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
// import { K8s } from '@kinvolk/headlamp-plugin/lib/K8s';
// import { Typography } from '@mui/material';

registerAppBarAction(<span>Hello</span>);

Let's break this down:

Line What it does
import { registerAppBarAction } Imports a function from the Headlamp plugin SDK
registerAppBarAction(Hello) Registers a React component to display in the app bar

That's it! Just two lines of meaningful code, and you have a working plugin.

The Metadata: `package.json`

Open package.json to see your plugin's configuration:

json
{
  "name": "hello-headlamp",
  "version": "0.1.0",
  "description": "Your Headlamp plugin",
  "scripts": {
    "start": "headlamp-plugin start",
    "build": "headlamp-plugin build",
    "format": "headlamp-plugin format",
    "lint": "headlamp-plugin lint",
    "lint-fix": "headlamp-plugin lint --fix",
    "tsc": "headlamp-plugin tsc",
    "test": "headlamp-plugin test",
    "package": "headlamp-plugin package"
  },
  ...
}

Key scripts you'll use:

Script Purpose
npm start Run plugin in development mode with hot reloading
npm run build Build plugin for production
npm run lint Check code for issues
npm run format Auto-format your code

Run the Plugin in Development Mode

Now let's see your plugin in action! You'll need two terminal windows.

Terminal 1: Start Headlamp

Navigate to your Headlamp repository and start it:

bash
cd ~/git/headlamp  # or wherever you cloned Headlamp
npm start

Wait until you see both backend and frontend are running:

Terminal 2: Start Your Plugin

In a new terminal, navigate to your plugin and start it:

bash
cd ~/projects/hello-headlamp
npm start

You'll see output like:

text
Watching for changes...
Plugin is available for Headlamp

What's happening?

  • The plugin is being compiled from TypeScript to JavaScript
  • It's watching for file changes (for hot reloading)
  • It's announcing itself to Headlamp running on localhost

Keep both terminals running! Headlamp needs to be running for your plugin to appear. The plugin's npm start watches for changes and automatically rebuilds.


See Your Plugin in Headlamp

Open your browser and go to http://localhost:3000.

Step 1: Look for "Hello" in the App Bar

Look at the top-right area of the screen (the app bar). You should see "Hello" appearing among the icons!

Step 2: View Your Plugin in Settings

  1. Click the Settings icon (⚙️) in the app bar
  2. Click on Plugins in the settings menu

You'll see a list of all loaded plugins, including your hello-headlamp plugin!

The plugin entry shows:

  • Name: hello-headlamp
  • Version: 0.1.0 (shown below the name)
  • Description: Your Headlamp plugin (from package.json)
  • Type: Development (indicates this is a development plugin)
  • Enable/Disable toggle (Desktop App only): You can turn plugins on or off in the desktop app

🎉 Congratulations! Your plugin is running in Headlamp!


Hot Reloading in Action

One of the best features of plugin development is hot reloading—changes you make appear instantly without restarting anything.

Make a Change

Open src/index.tsx in your editor and change:

tsx
registerAppBarAction(<span>Hello</span>);

To:

tsx
registerAppBarAction(<span>🚀 Hello Headlamp!</span>);

Save and Watch

  1. Save the file
  2. Look at your plugin terminal—you'll see it rebuilding
  3. Look at your browser—the app bar updates automatically!

No manual refresh needed! This makes development fast and enjoyable.

Try Another Change

Let's make it more interesting. Replace the entire content of src/index.tsx:

tsx
import { registerAppBarAction } from '@kinvolk/headlamp-plugin/lib';
import { Button } from '@mui/material';

function HelloButton() {
  const handleClick = () => {
    alert('Hello from your first Headlamp plugin!');
  };

  return (
    <Button
      variant="outlined"
      size="small"
      onClick={handleClick}
      sx={{ color: 'inherit', borderColor: 'inherit', mx: 1 }}
    >
      Say Hello
    </Button>
  );
}

registerAppBarAction(<HelloButton />);

Save the file and watch the magic:

  1. The text changes to a "Say Hello" button
  2. Click the button to see an alert!

What changed?

  • We imported Button from Material-UI (already available through Headlamp)
  • We created a React component HelloButton with click handling
  • We registered that component instead of a plain ``

This is the foundation of all plugin development—creating React components and registering them with Headlamp.


Understanding What Happened

Let's recap what makes your plugin work:

The Register Function

tsx
registerAppBarAction(<HelloButton />);

This tells Headlamp: "Hey, I have a component. Please display it in the app bar."

Available Register Functions

registerAppBarAction is just one of many registration functions. Here are some others you'll learn about:

Function What it does
registerAppBarAction Add items to the top navigation bar
registerSidebarEntry Add items to the left sidebar menu
registerRoute Create new pages/routes
registerDetailsViewSection Add sections to resource detail pages
registerPluginSettings Add a settings panel for your plugin

Each function lets you extend a different part of Headlamp. We'll explore these in upcoming tutorials!

Shared Dependencies

Notice how we imported Button from @mui/material:

tsx
import { Button } from '@mui/material';

You didn't need to install Material-UI—Headlamp provides it! These shared dependencies are available to all plugins:

  • React — UI framework
  • Material-UI (@mui/material) — Component library
  • React Router — Navigation
  • And more...

This keeps plugins small and ensures consistent styling across Headlamp.


Troubleshooting

Plugin Not Appearing in Headlamp

Check if both are running:

  • Headlamp should be running (npm start in Headlamp folder)
  • Plugin should be running (npm start in plugin folder)

Check the plugin terminal for errors:

bash
# In your plugin folder
npm start

Look for any red error messages.

Try restarting both:

  1. Stop the plugin (Ctrl+C)
  2. Stop Headlamp (Ctrl+C)
  3. Start Headlamp first, wait for it to be ready
  4. Start the plugin

Changes Not Reflecting (Hot Reload Not Working)

Ensure you saved the file — Hot reload only triggers on save.

Check the plugin terminal — You should see "Compiling..." when you save.

Hard refresh the browser:

  • Windows/Linux: Ctrl + Shift + R
  • macOS: Cmd + Shift + R

Clear browser cache:

  1. Open Developer Tools (F12)
  2. Right-click the refresh button
  3. Select "Empty Cache and Hard Reload"

Port Conflicts

If you see errors about ports being in use:

bash
# Find what's using port 3000
lsof -i :3000

# Find what's using port 4466
lsof -i :4466

Kill the conflicting processes or use different ports.

Build Errors

If you see TypeScript or build errors:

bash
# Check for TypeScript issues
npm run tsc

# Check for linting issues
npm run lint

# Auto-fix some issues
npm run lint-fix

What's Next

You've just created your first Headlamp plugin! 🎉

This tutorial covered registerAppBarAction—just one small piece of what plugins can do. Headlamp's plugin system offers many more capabilities:

  • Tutorial 3: Adding Sidebar Navigation — Create menu items that link to your custom pages
  • Working with Kubernetes Data — Fetch and display cluster information
  • Customizing Resource Views — Modify how Kubernetes resources are displayed
  • Adding Custom Themes — Change colors, fonts, and overall appearance
  • Publishing Plugins — Share your creations with the community

We'll cover these in the upcoming tutorials. In the meantime, check out the example plugins in the Headlamp repository for inspiration!


Quick Reference

Plugin Commands

Run these from your plugin directory (hello-headlamp/):

Task Command
Start development mode npm start
Build for production npm run build
Check code for issues npm run lint
Fix linting issues npm run lint-fix
Format code npm run format
Type check npm run tsc
Run tests npm run test
Package for distribution npm run package

Headlamp Commands

Run these from your Headlamp directory:

Task Command
Start Headlamp (backend + frontend) npm start
Start desktop app npm run app:start

Key Files

File Purpose
src/index.tsx Main plugin entry point
package.json Plugin metadata and scripts
tsconfig.json TypeScript configuration

Tutorials Plugin Development Getting Started Extending Existing Resource Views Index (`docs/tutorials/plugin-development/getting-started/extending-existing-resource-views/index.md`)


title: "Tutorial 7: Extending Existing Resource Views" sidebar_label: "7. Extending Existing Resource Views" sidebar_position: 8

Extending Existing Resource Views

In Tutorial 6 we covered how to build entirely new list and detail pages for custom resources. In this tutorial we will cover how to extend and customise existing pages and views that are already built into Headlamp, without replacing them. This is one of the most powerful patterns in Headlamp plugin development: you can enrich Headlamp's built-in Pod, Deployment, Node, and other resource views with your own columns, actions, and sections by registering processors that Headlamp calls when it renders those views.


Table of Contents

  1. Introduction
  2. Adding a Column to the Pods List
  3. Understanding registerResourceTableColumnsProcessor
  4. Adding a Custom Action to the Pod Detail View
  5. Understanding registerDetailsViewHeaderAction
  6. Adding a Custom Section to the Pod Detail View
  7. Understanding registerDetailsViewSectionsProcessor
  8. Complete Example
  9. Troubleshooting
  10. What's Next
  11. Quick Reference

Introduction

In previous tutorials you always built things from scratch — new routes, new pages, new components. The three APIs covered in this tutorial work differently: instead of creating a new page, they inject your content into existing pages that Headlamp already renders.

API What it does
registerResourceTableColumnsProcessor Add, remove, or reorder columns in any resource list table
registerDetailsViewHeaderAction Add action buttons to any resource detail page header
registerDetailsViewSectionsProcessor Add, remove, or reorder sections in any resource detail page

All three follow the same mental model: you register a processor function (or component) once at module load time, and Headlamp calls it automatically every time it renders the relevant UI. This means your additions appear in Headlamp's own built-in views, not just in pages your plugin owns.

What You'll Build

By the end of this tutorial you'll have extended the built-in Pods views with:

  • A Container Images column in Headlamp's Pods list page
  • An Image Details button in every Pod detail header that opens a popup showing each container's image and pull policy
  • A Container Resources section in every Pod detail page showing CPU and memory requests/limits

Prerequisites

Before starting, ensure you have:

Time to complete: ~25 minutes


Adding a Column to the Pods List

Headlamp's built-in Pods list already has columns like Name, Namespace, Restarts, Age etc. We'll add a Container Images column to it using registerResourceTableColumnsProcessor.

Step 1: Import the API and Pod Type

Open src/index.tsx and add the following imports at the top of the file (alongside your existing imports):

tsx
import {
  registerResourceTableColumnsProcessor,
} from '@kinvolk/headlamp-plugin/lib';
import { ResourceTableColumn } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import Pod from '@kinvolk/headlamp-plugin/lib/K8s/pod';

Step 2: Register the Column Processor

Add this code outside any React component, at the module level (for example, at the bottom of src/index.tsx):

tsx
registerResourceTableColumnsProcessor(function addContainerImagesColumn({ id, columns }) {
  // Only modify the built-in Pods list table.
  // The table ID follows the convention: headlamp-<plural-resource-name>
  if (id !== 'headlamp-pods') {
    return columns;
  }

  const podColumns = columns as ResourceTableColumn<Pod>[];

  podColumns.push({
    id: 'hello-headlamp-container-images',
    label: 'Container Images',
    // getValue is used for sorting and filtering — return a plain string
    getValue: (pod: Pod) =>
      pod.spec.containers.map(c => c.image).join(', '),
  });

  return columns;
});

Step 3: Test It

  1. Save the file
  2. Navigate to Workloads → Pods in the Headlamp sidebar
  3. You should see a new Container Images column on the right side of the table

Important: This column appears in Headlamp's own built-in Pods page — you are injecting into Headlamp's view, not the custom MyPodsPage you built in Tutorial 6. That separation depends on the two tables having different IDs. A resourceClass-backed table given no explicit id derives one as headlamp-, and pluralName defaults to the class's apiName — so MyPod (whose apiName must be 'pods' to reach the real endpoint) would land on headlamp-pods too. That is why Tutorial 6 gave the table an explicit id="my-plugin-pods": without it, this processor would push its column onto your own page, where pod.spec is undefined and reading pod.spec.containers would throw.


Understanding registerResourceTableColumnsProcessor

The processor function you pass to registerResourceTableColumnsProcessor is called every time Headlamp renders any resource table. It receives an object with:

Property Type Description
id string Unique table identifier, e.g. 'headlamp-pods'
columns ResourceTableColumn[] The current column array — mutate it or return a new one

And it must return the (modified) columns array.

Finding table IDs

Table IDs follow the convention headlamp-:

Resource Table ID
Pods headlamp-pods
Deployments headlamp-deployments
Nodes headlamp-nodes
Namespaces headlamp-namespaces
Services headlamp-services

For tables that don't directly represent a resource list (like the events table on the cluster overview), the ID will reflect the section's role (e.g. headlamp-cluster.overview.events). During development, you can console.log(id) inside your processor to discover the exact ID of any table.

Column definition

Each column follows the same structure as custom columns in ResourceListView from Tutorial 6:

tsx
{
  id: 'my-unique-column-id',  // Prefix with your plugin name to avoid clashes
  label: 'Column Header',
  getValue: (item) => 'sortable plain value',   // Used for sorting and filtering
  render: (item) => <ReactNode />,              // Optional — falls back to getValue
}

Adding a render function for richer cells

The column above shows images as a plain comma-separated string. You can enrich the display with a render function while keeping getValue for sorting:

tsx
import { Tooltip, Typography } from '@mui/material';

podColumns.push({
  id: 'hello-headlamp-container-images',
  label: 'Container Images',
  getValue: (pod: Pod) =>
    pod.spec.containers.map(c => c.image).join(', '),
  render: (pod: Pod) => {
    const images = pod.spec.containers.map(c => c.image);
    return (
      <Tooltip title={images.join('\n')} placement="bottom-start">
        <Typography noWrap style={{ maxWidth: 240, fontSize: 'inherit' }}>
          {images[0]}{images.length > 1 ? ` (+${images.length - 1} more)` : ''}
        </Typography>
      </Tooltip>
    );
  },
});

In the previous screenshot, the Container Images column is added at the end of the table (after Age). If you prefer to keep the Age column always last, you can use JavaScript array methods to insert your column before it. Find the index of the Age column (columns may be string ids or objects with an id property) and use splice to insert the new column:

tsx
import { Tooltip, Typography } from '@mui/material';

const ageIndex = columns.findIndex(
  col => col === 'age' || (typeof col === 'object' && col !== null && 'id' in col && col.id === 'age')
);
const containerImagesColumn: ResourceTableColumn<Pod> = {
  id: 'hello-headlamp-container-images',
  label: 'Container Images',
  getValue: (pod: Pod) => pod.spec.containers.map(c => c.image).join(', '),
  render: (pod: Pod) => {
    const images = pod.spec.containers.map(c => c.image);
    return (
      <Tooltip title={images.join('\n')} placement="bottom-start">
        <Typography noWrap style={{ maxWidth: 240, fontSize: 'inherit' }}>
          {images[0]}{images.length > 1 ? ` (+${images.length - 1} more)` : ''}
        </Typography>
      </Tooltip>
    );
  },
};
const podColumns = columns as ResourceTableColumn<Pod>[];
if (ageIndex >= 0) {
  podColumns.splice(ageIndex, 0, containerImagesColumn);
} else {
  podColumns.push(containerImagesColumn);
}
return columns;

Adding a Custom Action to the Pod Detail View

Now let's add an Image Details button to the Pod detail page header. Clicking it will open a popup (MUI Dialog) listing every container's image name and pull policy.

Step 1: Import the Dependencies

Add these to your imports:

tsx
import {
  registerResourceTableColumnsProcessor,
  registerDetailsViewHeaderAction,
} from '@kinvolk/headlamp-plugin/lib';
import { ActionButton, SimpleTable } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
} from '@mui/material';

Step 2: Create the Action Component

Create the component that will be rendered as the header action button. The component receives the current resource as an item prop:

tsx
function ImageDetailsAction({ item }: { item: any }) {
  const [open, setOpen] = useState(false);

  // Only show this action on Pod detail pages
  if (!item || item.kind !== 'Pod') {
    return null;
  }

  const containers: Array<{
    name: string;
    image: string;
    imagePullPolicy?: string;
  }> = item.spec?.containers || [];

  return (
    <>
      <ActionButton
        description="Image Details"
        icon="mdi:image-search-outline"
        onClick={() => setOpen(true)}
      />
      <Dialog open={open} onClose={() => setOpen(false)} maxWidth="md" fullWidth>
        <DialogTitle>Container Images — {item.metadata?.name}</DialogTitle>
        <DialogContent>
          <SimpleTable
            data={containers}
            columns={[
              { label: 'Container', getter: c => c.name },
              { label: 'Image', getter: c => c.image },
              {
                label: 'Pull Policy',
                getter: c => c.imagePullPolicy || 'IfNotPresent (default)',
              },
            ]}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpen(false)}>Close</Button>
        </DialogActions>
      </Dialog>
    </>
  );
}

Step 3: Register the Action

Add this at the module level:

tsx
registerDetailsViewHeaderAction(ImageDetailsAction);

Step 4: Test It

  1. Save the file
  2. Navigate to Workloads → Pods → click on any pod
  3. Look for the image search icon in the top-right area of the detail page header (alongside Edit and Delete)
  4. Click it — a dialog should open showing each container's name, image, and pull policy

Understanding registerDetailsViewHeaderAction

registerDetailsViewHeaderAction accepts a React component function. Headlamp calls this component for every detail page it renders, passing the current resource as the item prop.

tsx
function MyAction({ item }: { item: any }) {
  // item is the KubeObject for the resource being viewed
  // Return null to show nothing for this resource type
  if (!item || item.kind !== 'Pod') return null;

  return <ActionButton description="My Action" icon="mdi:icon-name" onClick={...} />;
}

registerDetailsViewHeaderAction(MyAction);

Key points

  • The component is rendered for every detail view across the entire app, so always check item.kind (or any other condition) and return null when it shouldn't appear.
  • Use ActionButton from @kinvolk/headlamp-plugin/lib/CommonComponents for consistent styling with Headlamp's existing action buttons.
  • Because the component is a regular React component, you can use useState, useEffect, and any other hooks inside it — which is how the popup pattern above works.
  • You can register multiple header actions; they all appear side by side in the header.

Registering with a stable ID

If you want to reference or replace your action later (e.g. via registerDetailsViewHeaderActionsProcessor), pass an object with an explicit id:

tsx
registerDetailsViewHeaderAction({
  id: 'hello-headlamp-image-details',
  action: ImageDetailsAction,
});

Adding a Custom Section to the Pod Detail View

Now let's add a Container Resources section to the Pod detail page. This section will show each container's CPU and memory requests and limits — information that is not shown by default in Headlamp's Pod detail view.

Step 1: Import the Section APIs

Add these to your imports:

tsx
import {
  registerResourceTableColumnsProcessor,
  registerDetailsViewHeaderAction,
  registerDetailsViewSectionsProcessor,
} from '@kinvolk/headlamp-plugin/lib';
import { SectionBox, SimpleTable } from '@kinvolk/headlamp-plugin/lib/CommonComponents';

Step 2: Register the Sections Processor

Add this at the module level:

text
/* Detailed source-code truncated for AI context efficiency. */

Step 3: Test It

  1. Save the file
  2. Navigate to any Pod's detail page
  3. Just below the standard metadata header you should see a new Container Resources section with a table showing CPU and memory requests/limits for each container

Understanding registerDetailsViewSectionsProcessor

The processor function you pass to registerDetailsViewSectionsProcessor is called every time Headlamp renders a detail page. It receives:

Parameter Type Description
resource KubeObject | null The resource being viewed (null while loading)
sections DetailsViewSection[] Current ordered array of sections

And it must return the (modified) sections array.

Sections array structure

Each entry in the sections array is an object with an id and section (a React node):

tsx
{
  id: 'my-section-id',
  section: <SectionBox title="...">...</SectionBox>,
}

Headlamp's own built-in sections use IDs from DefaultDetailsViewSection:

Constant What it is
DefaultDetailsViewSection.MAIN_HEADER The standard metadata header (name, namespace, labels, etc.)
DefaultDetailsViewSection.EVENTS The Kubernetes events table
DefaultDetailsViewSection.BACK_LINK The back navigation link

You can use these constants to precisely position your sections relative to Headlamp's built-in ones.

Positioning strategies

Append to the end (simplest):

tsx
return [...sections, newSection];

Insert after a specific section (e.g. pod containers):

tsx
const hasId = (s: (typeof sections)[number]): s is { id: string } =>
  typeof s === 'object' && s !== null && 'id' in s;
const idx = sections.findIndex(s => hasId(s) && s.id === 'headlamp.pod-containers');
if (idx === -1) {
  return [...sections, newSection]; // section not found — append as fallback
}
const updated = [...sections];
updated.splice(idx + 1, 0, newSection);
return updated;

Insert before a specific section (e.g. events):

tsx
const hasId = (s: (typeof sections)[number]): s is { id: string } =>
  typeof s === 'object' && s !== null && 'id' in s;
const eventsIdx = sections.findIndex(s => hasId(s) && s.id === DefaultDetailsViewSection.EVENTS);
if (eventsIdx !== -1) {
  const updated = [...sections];
  updated.splice(eventsIdx, 0, newSection);
  return updated;
}
return [...sections, newSection];

Idempotency guard

Headlamp may call your processor multiple times as the component re-renders. Always check whether your section is already present before adding it, to avoid duplicates:

tsx
const alreadyAdded = sections.some(
  s => typeof s === 'object' && s !== null && 'id' in s && s.id === 'my-section-id'
);
if (alreadyAdded) return sections;

Complete Example

Here is the full set of additions to your src/index.tsx for this tutorial. These lines can be added after all the existing code from Tutorial 6 (the registerRoute and registerSidebarEntry calls at the bottom):

text
/* Detailed source-code truncated for AI context efficiency. */

Troubleshooting

Column not appearing in the Pods list

  • Check that you are navigating to Workloads → Pods (Headlamp's built-in page), not the custom MyPodsPage from Tutorial 6.
  • console.log(id) inside your processor and check the browser DevTools console to confirm the table ID is 'headlamp-pods'.
  • Make sure the processor call is at module level (outside any component or function), so it runs when the plugin loads.

Action button not appearing on Pod detail pages

  • Confirm your component returns null for non-Pod resources and a valid React node for Pods.
  • Check the browser console for errors inside ImageDetailsAction.
  • Verify the useState import is at the top of the file.

Section not appearing or appearing multiple times

  • Check the idempotency guard: the sections.some(...) check must match the exact id string you use when constructing newSection.
  • If headlamp.pod-containers is not found (podContainersIdx === -1), the section falls back to appending at the end — console.log(sections.map(s => s?.id)) inside your processor to inspect the current section IDs and confirm the expected anchor section is present.
  • console.log(sections) inside your processor to inspect the full sections array.

What's Next

You've learned how to extend Headlamp's built-in views without replacing them:

  • ✅ Using registerResourceTableColumnsProcessor to add columns to existing resource tables
  • ✅ Using registerDetailsViewHeaderAction to add action buttons to existing detail pages
  • ✅ Using registerDetailsViewSectionsProcessor to inject sections into existing detail pages

Coming up in Tutorial 8: Adding Plugin Settings

  • Defining a settings schema for your plugin
  • Reading settings values at runtime
  • Making plugin behaviour configurable by users

Quick Reference

registerResourceTableColumnsProcessor

tsx
import { registerResourceTableColumnsProcessor } from '@kinvolk/headlamp-plugin/lib';

registerResourceTableColumnsProcessor(function myProcessor({ id, columns }) {
  if (id !== 'headlamp-pods') return columns;   // target a specific table

  columns.push({
    id: 'my-plugin-column-id',      // prefix with plugin name to avoid clashes
    label: 'Column Header',
    getValue: item => 'plain value', // for sorting and filtering (required)
    render: item => <Node />,        // for cell display (optional)
  });

  return columns;
});

Common table IDs: headlamp-pods, headlamp-deployments, headlamp-nodes, headlamp-namespaces, headlamp-services

Naming your own tables: Give every table you create an explicit id with your plugin's prefix (e.g. id="my-plugin-pods"). If you use resourceClass and omit id, Headlamp derives headlamp-, which can collide with a built-in table. If you pass data={items} instead, processors receive an empty id unless you set one — still use an explicit plugin-scoped id so your table stays identifiable and safe if you change how it loads data.

registerDetailsViewHeaderAction

tsx
import { registerDetailsViewHeaderAction } from '@kinvolk/headlamp-plugin/lib';
import { ActionButton } from '@kinvolk/headlamp-plugin/lib/CommonComponents';

function MyAction({ item }: { item: any }) {
  if (!item || item.kind !== 'Pod') return null; // filter by resource kind

  return (
    <ActionButton
      description="Tooltip text"
      icon="mdi:icon-name"
      onClick={() => { /* ... */ }}
    />
  );
}

registerDetailsViewHeaderAction(MyAction);

// Or with an explicit ID (for later reference/replacement):
registerDetailsViewHeaderAction({ id: 'my-plugin-action', action: MyAction });

registerDetailsViewSectionsProcessor

tsx
import {
  registerDetailsViewSectionsProcessor,
  DefaultDetailsViewSection,
} from '@kinvolk/headlamp-plugin/lib';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';

registerDetailsViewSectionsProcessor(function myProcessor(resource, sections) {
  if (!resource || resource.kind !== 'Pod') return sections;  // filter by kind

  const sectionId = 'my-plugin-section';
  // Idempotency guard
  if (sections.some(s => typeof s === 'object' && s !== null && 'id' in s && s.id === sectionId)) {
    return sections;
  }

  const newSection = {
    id: sectionId,
    section: <SectionBox title="My Section">...</SectionBox>,
  };

  // Insert after the main header
  const idx = sections.findIndex(
    s => typeof s === 'object' && s !== null && 'id' in s && s.id === DefaultDetailsViewSection.MAIN_HEADER
  );
  const updated = [...sections];
  updated.splice(idx + 1, 0, newSection);
  return updated;
});

DefaultDetailsViewSection constants: MAIN_HEADER, EVENTS, BACK_LINK


Tutorials Plugin Development Getting Started Releasing And Publishing Index (`docs/tutorials/plugin-development/getting-started/releasing-and-publishing/index.md`)


title: "Tutorial 11: Releasing & Publishing Your Plugin" sidebar_label: "11. Releasing & Publishing" sidebar_position: 12

Releasing & Publishing Your Plugin

In Tutorial 10 we added custom map nodes to Headlamp's Map view. You now have a fully-featured hello-headlamp plugin with a sidebar, pages, Kubernetes data integration, list and detail views, settings, a custom theme, and map nodes.

This tutorial covers the final step of the plugin lifecycle: getting your plugin ready for release and making it discoverable by other Headlamp users via Artifact Hub.


Table of Contents

  1. Release Readiness Checklist
  2. Your Plugin's Built-in npm Scripts
  3. Formatting Your Code
  4. Linting Your Code
  5. Type-Checking Your Code
  6. Running Tests
  7. Setting Your Version
  8. Building for Production
  9. Packaging the Plugin
  10. Creating a GitHub Release
  11. How Headlamp Uses Artifact Hub
  12. Adding the Artifact Hub Repository File
  13. Adding the Artifact Hub Package File
  14. Pushing to GitHub
  15. Registering on Artifact Hub
  16. Releasing Updates
  17. What's Next
  18. Quick Reference

Release Readiness Checklist

Before packaging and publishing, make sure your plugin passes each of the following checks. Going through these in order catches the most common issues first.

# Check Command Why it matters
1 Code is formatted consistently npm run format Consistent style; required by ESLint
2 No linting errors npm run lint Catches bugs and code-quality issues
3 TypeScript compiles without errors npm run tsc Catches type errors before they reach users
4 All tests pass npm run test Confirms no regressions
5 Version number is correct edit package.json Determines the filename of the tarball
6 Build succeeds npm run build Creates the production dist/main.js
7 Package succeeds npm run package Creates the .tar.gz ready for upload

We will walk through each check in the sections below.


Your Plugin's Built-in npm Scripts

When you created hello-headlamp with npx @kinvolk/headlamp-plugin create hello-headlamp, the template generated a package.json with a set of scripts that wrap the headlamp-plugin CLI:

json
{
  "scripts": {
    "start":          "headlamp-plugin start",
    "build":          "headlamp-plugin build",
    "format":         "headlamp-plugin format",
    "lint":           "headlamp-plugin lint",
    "lint-fix":       "headlamp-plugin lint --fix",
    "package":        "headlamp-plugin package",
    "tsc":            "headlamp-plugin tsc",
    "storybook":      "headlamp-plugin storybook",
    "storybook-build":"headlamp-plugin storybook-build",
    "test":           "headlamp-plugin test",
    "i18n":           "headlamp-plugin i18n"
  }
}

Here is what each script does:

Script What it does
start Watches src/ for changes and rebuilds automatically — used during development
build Compiles TypeScript and bundles everything into dist/main.js — used for production
format Runs Prettier to auto-format all source files
lint Runs ESLint and reports any code-quality issues
lint-fix Runs ESLint and automatically fixes everything it can
package Bundles dist/ into a .tar.gz tarball in the Headlamp-accepted format
tsc Runs the TypeScript compiler in check-only mode to find type errors
storybook Starts a Storybook development server for building component stories
storybook-build Builds a static Storybook site
test Runs unit tests with Jest
i18n Extracts translatable strings for internationalisation

The four scripts you will run every time before a release are: format, lint, tsc, and test — followed by build and package.


Formatting Your Code

Headlamp plugins use Prettier for code formatting, configured via the @headlamp-k8s/eslint-config shared config. Running the formatter first prevents the linter from reporting style-only errors.

bash
cd hello-headlamp
npm run format

Expected output when everything is clean:

text
hello-headlamp/src/index.tsx 52ms

Prettier lists each file it processes. If a file needed changes, Prettier rewrites it in place — you will see a slightly longer time on the first run.

:::tip
Commit your code before formatting so you can clearly see what the formatter changed with git diff.
:::


Linting Your Code

Linting runs ESLint across your source files and checks for:

  • Unused variables and imports
  • Missing React key props in lists
  • Accessibility issues (jsx-a11y plugin)
  • TypeScript-specific code-quality rules
  • Any patterns disallowed by Headlamp's shared ESLint config
bash
npm run lint

If the linter finds fixable issues, you can automatically correct them with:

bash
npm run lint-fix

A clean run looks like this:

text
> [email protected] lint
> headlamp-plugin lint

Any reported problems include the file path, line number, and a description of the rule that was violated:

text
src/index.tsx
  42:7  error  'unusedVar' is defined but never used  @typescript-eslint/no-unused-vars

✖ 1 problem (1 error, 0 warnings)

Fix all errors before proceeding — the build step will still succeed with lint errors present, but shipping known issues to users is bad practice.


Type-Checking Your Code

The tsc script runs the TypeScript compiler in --noEmit mode: it type-checks every file but does not output any JavaScript. This catches type mismatches that ESLint cannot see.

bash
npm run tsc

A clean run produces no output and exits with code 0. Any errors are shown with their file, line, and a clear description:

text
src/index.tsx:78:24 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Fix all TypeScript errors before continuing. Type errors are the most common cause of runtime crashes in plugins.


Running Tests

If you have written unit tests (or plan to), run them now:

bash
npm run test

This runs Jest, discovers all *.test.ts(x) and *.spec.ts(x) files in src/, and reports the results:

text
PASS  src/components/MyPage.test.tsx
  MyPage
    ✓ renders without crashing (23 ms)
    ✓ displays cluster name (18 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total

All tests must pass before you proceed.


Setting Your Version

Plugin versions follow Semantic Versioning (MAJOR.MINOR.PATCH):

Segment When to increment Example
MAJOR Breaking change — removes or changes existing behaviour 1.0.0 → 2.0.0
MINOR New feature added in a backward-compatible way 1.0.0 → 1.1.0
PATCH Bug fix, with no new features or breaking changes 1.0.0 → 1.0.1

For a first public release, 1.0.0 is the conventional starting point. The template starts at 0.1.0 — that version signals "not yet stable" and is fine for early development.

Open package.json and update the version field:

json
{
  "name": "hello-headlamp",
  "version": "1.0.0",
  "description": "A Headlamp plugin tutorial series — sidebar, data, settings, themes, and map nodes.",
  ...
}

The version you set here determines the name of the tarball produced by npm run package (hello-headlamp-1.0.0.tar.gz) and must match the version you put in artifacthub-pkg.yml later.


Building for Production

The build command compiles your TypeScript source and bundles it into dist/main.js — the single JavaScript file that Headlamp loads:

bash
npm run build

You will see Vite output similar to this:

text
> [email protected] build
> headlamp-plugin build

Building "." for production with plugin name: hello-headlamp...
Injecting env var: NODE_ENV = "production"
vite v6.4.1 building for production...
🎯 Plugin name detected: 'hello-headlamp'
✓ 4 modules transformed.
dist/main.js  11.90 kB │ gzip: 4.23 kB
✓ built in 135ms
Successfully copied extra dist files
Finished building "." for production.

The key file produced is dist/main.js. This is what Headlamp actually loads at runtime.

:::note
npm run start (the development watcher) also writes to dist/main.js, but that build is not minified or optimised. Always use npm run build for releases.
:::


Packaging the Plugin

The package command takes the dist/ directory and creates a .tar.gz tarball in the specific format Headlamp expects for installation:

bash
npm run package

The output tells you exactly what was created and — crucially — the SHA256 checksum you will need for Artifact Hub:

text
Created tarball: "hello-headlamp-1.0.0.tar.gz"
Tarball checksum (SHA256): a3b4c5d6e7f8...

:::important
Save the checksum. You will need it in artifacthub-pkg.yml. If you lose it you can recompute it with sha256sum hello-headlamp-1.0.0.tar.gz on Linux/macOS or Get-FileHash on Windows.
:::

What's inside the tarball?

The tarball always contains at minimum:

text
hello-headlamp/
├── main.js          ← compiled plugin bundle
└── package.json     ← plugin metadata (name, version, description)

If your plugin uses internationalisation, npm run package automatically includes the translations too:

text
hello-headlamp/
├── main.js
├── package.json
└── locales/         ← i18n translation files (only if a locales/ folder exists)
    ├── en/
    │   └── translation.json
    └── ...

You can also declare additional files to bundle via the headlamp.extraDist field in your package.json:

json
{
  "headlamp": {
    "extraDist": {
      "assets/logo.png": "src/assets/logo.png"
    }
  }
}

This copies src/assets/logo.png into the tarball as hello-headlamp/assets/logo.png.


Creating a GitHub Release

Headlamp only allows plugins to be downloaded from GitHub, GitLab, or Bitbucket for security reasons. A GitHub Release is the standard way to host the tarball so that Artifact Hub can reference it.

Push your code

If you have not already pushed your plugin to GitHub, do so now:

bash
# Inside hello-headlamp/
git init                            # if not already a git repo
git add .
git commit -m "chore: release v1.0.0"
git remote add origin https://github.com/YOUR_USERNAME/hello-headlamp.git
git push -u origin main

Tag the release

Git tags are how GitHub identifies release versions. By convention, tags for semantic versions are prefixed with v:

bash
git tag v1.0.0
git push origin v1.0.0

Create the release on GitHub

  1. Go to your repository on GitHub.
  2. Click Releases → Draft a new release.
  3. In "Choose a tag", select the v1.0.0 tag you just pushed.
  4. Set the release title to v1.0.0.
  5. Add a description of what changed.
  6. Under Assets, click Attach binaries and upload hello-headlamp-1.0.0.tar.gz.
  7. Click Publish release.

After publishing, click on the .tar.gz asset and copy the download URL. It will look like:

text
https://github.com/YOUR_USERNAME/hello-headlamp/releases/download/v1.0.0/hello-headlamp-1.0.0.tar.gz

You will use this URL in the artifacthub-pkg.yml file below.


How Headlamp Uses Artifact Hub

Artifact Hub is an open-source hub for cloud-native packages. Headlamp's Plugin Catalog (the built-in plugin manager in the Headlamp desktop app) reads plugin metadata directly from Artifact Hub to build its list of available plugins.

The flow looks like this:

text
Your GitHub repository
    │
    │  artifacthub-repo.yml   ← proves you own the repo
    │  artifacthub-pkg.yml    ← describes the plugin
    │
    ▼
Artifact Hub (artifacthub.io)
    │
    │  scans and indexes your plugin
    │
    ▼
Headlamp Plugin Catalog
    │
    │  reads plugin list from Artifact Hub API
    │  downloads tarball from GitHub release
    │
    ▼
User's Headlamp installation

There are two YAML files you need to add to your repository:

File Location Purpose
artifacthub-repo.yml Repository root Declares ownership of the repository
artifacthub-pkg.yml Plugin folder root Describes a single plugin package

Adding the Artifact Hub Repository File

Create artifacthub-repo.yml at the root of your GitHub repository (not inside the plugin folder):

yaml
owners:
  - name: Your Name
    email: [email protected]

Replace Your Name and [email protected] with your actual name and the email address you will use to register on Artifact Hub. This file is how Artifact Hub verifies that you own the repository you are registering.

If your repository contains multiple plugins (one per folder), a single artifacthub-repo.yml at the root covers all of them.


Adding the Artifact Hub Package File

Create artifacthub-pkg.yml in the root of your plugin folder (next to package.json):

yaml
version: 1.0.0
name: hello-headlamp
displayName: Hello Headlamp
createdAt: "2025-01-20T00:00:00Z"
description: >
  A complete Headlamp plugin tutorial: sidebar navigation, Kubernetes data,
  list and detail views, plugin settings, custom themes, and map visualization.
annotations:
  headlamp/plugin/archive-url: "https://github.com/YOUR_USERNAME/hello-headlamp/releases/download/v1.0.0/hello-headlamp-1.0.0.tar.gz"
  headlamp/plugin/archive-checksum: "SHA256:a3b4c5d6e7f8..."
  headlamp/plugin/version-compat: ">=0.22"
  headlamp/plugin/distro-compat: "in-cluster,web,docker-desktop,desktop"

:::tip Real-world example
The KEDA plugin's artifacthub-pkg.yml is a good reference for a production-ready file.
:::

Field reference

Field Required Description
version Yes Must match the version in package.json and the tag on GitHub
name Yes Unique identifier, lowercase with hyphens or underscores; used in the Artifact Hub URL
displayName Yes Human-readable name shown in the Plugin Catalog
createdAt Yes ISO 8601 timestamp of this release
description Yes Short summary shown in the Plugin Catalog search results
logoURL No URL to a square PNG/SVG logo (recommended for visibility)

Annotations reference

The Headlamp-specific metadata goes in the annotations block:

Annotation Required Description
headlamp/plugin/archive-url Yes Direct download URL of the .tar.gz tarball on GitHub (or GitLab/Bitbucket)
headlamp/plugin/archive-checksum Yes SHA256 checksum of the tarball, prefixed with SHA256: (uppercase) — output by npm run package
headlamp/plugin/version-compat No Minimum Headlamp version required, as a semver range (e.g. >=0.22)
headlamp/plugin/distro-compat No Comma-separated list of Headlamp distributions the plugin works with

`distro-compat` values

Value Description
in-cluster Headlamp running inside a Kubernetes cluster (e.g. via Helm)
web Headlamp accessed via browser without a desktop wrapper
docker-desktop Headlamp Docker Desktop extension
desktop Headlamp desktop application (Windows, macOS, Linux)
linux Desktop app on Linux only
windows Desktop app on Windows only
mac Desktop app on macOS only

If your plugin works everywhere, use in-cluster,web,docker-desktop,desktop. If it relies on a feature only available in the desktop app, list just desktop.

`version-compat` guidance

Check the Headlamp release notes for the version that introduced any API you use. If you are unsure, >=0.22 is a safe starting point for plugins built with the APIs covered in this tutorial series.


Pushing to GitHub

Add both files to your repository, commit, and push:

bash
# From the repository root
git add artifacthub-repo.yml hello-headlamp/artifacthub-pkg.yml
git commit -m "chore: add Artifact Hub metadata"
git push origin main

If your repository contains only one plugin (the structure used in this series, where the plugin folder is the repo root), both files live in the same directory:

bash
git add artifacthub-repo.yml artifacthub-pkg.yml
git commit -m "chore: add Artifact Hub metadata"
git push origin main

Registering on Artifact Hub

  1. Go to artifacthub.io and sign in (or create a free account).
  2. Open your Control Panel (top-right user menu → Control Panel).
  3. Click the Add button in the Repositories section.
  4. Fill in the form:
    • Kind: Headlamp plugin
    • Name: A name for the repository entry (e.g. hello-headlamp)
    • Display name: Human-readable name
    • URL: Your GitHub repository URL (e.g. https://github.com/YOUR_USERNAME/hello-headlamp)
  5. Click Add.

Artifact Hub will scan your repository within a few minutes. If it finds a valid artifacthub-repo.yml and artifacthub-pkg.yml, your plugin will be listed under the Headlamp category.

:::info
Official vs community plugins: By default, Headlamp's Plugin Catalog only shows plugins that are marked as official in Artifact Hub or are on Headlamp's allow-list. Community plugins are still on Artifact Hub and fully installable — users simply need to enable "Show all plugins" in Plugin Catalog settings. This is a safety measure, not a quality bar.
:::

Once indexed, your plugin's Artifact Hub URL will look like:

text
https://artifacthub.io/packages/headlamp/YOUR_REPO/hello-headlamp

Releasing Updates

When you make changes and want to publish a new version:

Run the pre-release checks

bash
npm run format
npm run lint
npm run tsc
npm run test

Bump the version

Update version in package.json following SemVer:

bash
# Using npm's built-in version command (updates package.json and creates a git tag)
npm version patch   # 1.0.0 → 1.0.1  (bug fix)
npm version minor   # 1.0.0 → 1.1.0  (new feature)
npm version major   # 1.0.0 → 2.0.0  (breaking change)

Or edit package.json manually.

Build and package

bash
npm run build
npm run package

Note the new checksum in the output.

Create a new GitHub release

Push the new tag and upload the new tarball:

bash
git push origin main
git push origin --tags       # pushes the tag created by `npm version`

Then create a new GitHub release for the new tag and attach the new .tar.gz.

Update `artifacthub-pkg.yml`

Update three fields:

yaml
version: 1.0.1                 # ← new version
createdAt: "2025-03-01T00:00:00Z"  # ← today's date
annotations:
  headlamp/plugin/archive-url: "https://github.com/YOUR_USERNAME/hello-headlamp/releases/download/v1.0.1/hello-headlamp-1.0.1.tar.gz"
  headlamp/plugin/archive-checksum: "SHA256:<new-checksum>"  # ← from npm run package output

Commit and push

bash
git add package.json artifacthub-pkg.yml
git commit -m "chore: release v1.0.1"
git push origin main

Artifact Hub will automatically pick up the new artifacthub-pkg.yml on its next scan and update the listing. Users who installed the previous version will see an update available in the Plugin Catalog.


What's Next

Congratulations — you have completed the entire Getting Started tutorial series! Your hello-headlamp plugin now:

  • ✅ Adds a button to the app bar
  • ✅ Has a sidebar entry and custom pages
  • ✅ Fetches and displays Kubernetes data
  • ✅ Provides list and detail views with custom columns
  • ✅ Extends existing resource detail pages
  • ✅ Has a configurable settings page
  • ✅ Registers a custom theme
  • ✅ Contributes nodes to the Map view
  • ✅ Is built, packaged, and published on Artifact Hub

Quick Reference

Pre-release commands

bash
npm run format      # auto-format with Prettier
npm run lint        # check for code issues with ESLint
npm run lint-fix    # auto-fix what ESLint can
npm run tsc         # type-check with TypeScript (no output on success)
npm run test        # run Jest unit tests

Release commands

bash
npm run build       # compile TypeScript → dist/main.js
npm run package     # bundle dist/ → hello-headlamp-X.Y.Z.tar.gz + print checksum

`artifacthub-repo.yml` (repository root)

yaml
owners:
  - name: Your Name
    email: [email protected]

`artifacthub-pkg.yml` (plugin root)

yaml
version: 1.0.0
name: hello-headlamp
displayName: Hello Headlamp
createdAt: "2025-01-20T00:00:00Z"
description: My Headlamp plugin description.
logoURL: https://raw.githubusercontent.com/YOUR_USERNAME/hello-headlamp/main/logo.png
annotations:
  headlamp/plugin/archive-url: "https://github.com/YOUR_USERNAME/hello-headlamp/releases/download/v1.0.0/hello-headlamp-1.0.0.tar.gz"
  headlamp/plugin/archive-checksum: "SHA256:<checksum from npm run package>"
  headlamp/plugin/version-compat: ">=0.22"
  headlamp/plugin/distro-compat: "in-cluster,web,docker-desktop,desktop"

Tutorials Plugin Development Getting Started Running From Source Index (`docs/tutorials/plugin-development/getting-started/running-from-source/index.md`)


title: "Tutorial 1: Running Headlamp from Source" sidebar_label: "1. Running from Source" sidebar_position: 2

Running Headlamp from Source

This tutorial guides you through building and running Headlamp from source code. By the end, you'll have Headlamp running locally in development mode—ready for plugin development or contributing to the project.


Table of Contents

  1. Introduction
  2. Prerequisites
  3. Clone the Repository
  4. Repository Structure
  5. Install Dependencies
  6. Build the Code
  7. Run in Development Mode
  8. Run the Desktop App
  9. Connect to a Kubernetes Cluster
  10. Troubleshooting
  11. Next Steps

Introduction

Headlamp is an open-source, extensible Kubernetes web UI. It provides:

  • A clean, modern interface for managing Kubernetes clusters
  • Multi-cluster support
  • A powerful plugin system for customization
  • Desktop and in-cluster deployment options

Headlamp has three main components:

Component Technology Purpose
Frontend TypeScript, React The web UI you interact with
Backend Go API server that proxies requests to Kubernetes
Desktop App Electron Native app wrapper for macOS, Windows, Linux

Building from source lets you modify Headlamp, develop plugins with live reload, and contribute to the project.


Prerequisites

Install these tools before proceeding:

Required

Tool Version Installation
Git Latest git-scm.com
Node.js ≥22.0.0 LTS nodejs.org or use nvm
npm ≥11.0.0 Included with Node.js
Go ≥1.25.9 go.dev/doc/install

Optional (for testing with a cluster)

Tool Purpose Installation
minikube Local Kubernetes cluster minikube.sigs.k8s.io
kubectl Kubernetes CLI kubernetes.io/docs/tasks/tools

Verify Installation

bash
# Check versions
node --version    # Should be v22.0.0 or higher
npm --version     # Should be 11.0.0 or higher
go version        # Should be go1.25.9 or higher
git --version     # Any recent version

Clone the Repository

Option A: Fork First (for contributors)

  1. Fork the repo at github.com/kubernetes-sigs/headlamp
  2. Clone your fork:
bash
git clone https://github.com/YOUR_USERNAME/headlamp.git
cd headlamp

Option B: Clone Directly

bash
git clone https://github.com/kubernetes-sigs/headlamp.git
cd headlamp

Repository Structure

Headlamp is organized as a monorepo with three main components: a React frontend for the UI, a Go backend that proxies requests to Kubernetes, and an Electron app for the desktop version. All build commands are orchestrated from the root package.json.

text
headlamp/
├── frontend/          # React/TypeScript web UI
│   ├── src/           # Source code, components, and tests
│   └── package.json   # Frontend dependencies
│
├── backend/           # Go server
│   ├── cmd/           # Main application entry point
│   ├── pkg/           # Reusable packages (auth, cache, helm, etc.)
│   └── go.mod         # Go dependencies
│
├── app/               # Electron desktop application
│   ├── electron/      # Main process code
│   └── package.json   # App dependencies
│
├── plugins/           # Plugin system
│   ├── examples/      # Example plugins to learn from
│   └── headlamp-plugin/  # Plugin development tools
│
├── docs/              # Documentation (markdown)
├── package.json       # Root scripts for building/running
└── README.md          # Project overview

Key insight: The root package.json contains npm scripts that orchestrate building and running all components. You'll use commands like npm run backend:build and npm run frontend:start from the root directory.


Install Dependencies

From the repository root, install all dependencies:

bash
# Install root dependencies
npm install

# Install frontend dependencies
npm run frontend:install

# Install app dependencies (only needed if running desktop app)
npm run app:install

Note: Go dependencies are fetched automatically during the build step. No separate install is needed for the backend.

Quick install everything:

bash
npm run install:all

Build the Code

Build Everything

bash
npm run build

This runs backend:build and frontend:build sequentially.

Build Individually

bash
# Build backend only (compiles Go → backend/headlamp-server binary)
npm run backend:build

# Build frontend only (compiles TypeScript → frontend/build/)
npm run frontend:build

Note: Building creates the artifacts but doesn't run them. See the next section to start Headlamp.


Run in Development Mode

bash
npm start

This starts both backend and frontend with live reload. You'll see color-coded output:

  • 🔵 Blue: Backend logs
  • 🟢 Green: Frontend logs

Access points:

Open http://localhost:3000 in your browser. You should see Headlamp's welcome screen:

Option 2: Run Separately (Two Terminals)

Terminal 1 - Backend:

bash
npm run backend:build   # Build first (required)
npm run backend:start

Terminal 2 - Frontend:

bash
npm run frontend:start

Tip: Running separately is useful when you only want to restart one component.


Run the Desktop App

The desktop app wraps the frontend and backend into a native application.

Option 1: Full App Mode

Builds frontend and runs the complete Electron app:

bash
npm run app:start

Option 2: App-Only Mode (Development)

If you already have npm start running (backend + frontend), you can run just the Electron shell:

bash
npm run app:start:client

This connects to your running dev servers—useful for faster iteration on app-specific code.

Option 3: Everything Together

Run backend, frontend, and desktop app all at once:

bash
npm run start:with-app

Connect to a Kubernetes Cluster

Headlamp automatically detects Kubernetes clusters from your kubeconfig file. By default, it looks for the file at ~/.kube/config on macOS/Linux or %USERPROFILE%\.kube\config on Windows. If you have multiple clusters configured, Headlamp will show all of them and let you switch between them.

Already have a cluster? If you already have kubectl working with a cluster (try kubectl get nodes), you can skip to the next section—Headlamp will pick it up automatically.

Quick Setup with minikube

bash
# Start a local cluster
minikube start

# Verify it's running
kubectl get nodes

Now refresh Headlamp, it should detect your cluster automatically.


Troubleshooting

Port Already in Use

bash
# Find and kill process on port 3000 (frontend)
lsof -i :3000  # macOS/Linux
netstat -ano | findstr :3000  # Windows

# Find and kill process on port 4466 (backend)
lsof -i :4466  # macOS/Linux

Backend Won't Start

Ensure the binary exists:

bash
ls backend/headlamp-server  # macOS/Linux
dir backend\headlamp-server.exe  # Windows

If missing, rebuild:

bash
npm run backend:build

Node/Go Version Mismatch

bash
# Check versions match requirements
node --version  # Need ≥22.0.0
npm --version   # Need ≥11.0.0
go version      # Need ≥1.25.9

kubeconfig Not Found

Headlamp looks for ~/.kube/config by default. Verify it exists:

bash
cat ~/.kube/config  # macOS/Linux
type %USERPROFILE%\.kube\config  # Windows

Clean Rebuild

When in doubt, clean and rebuild:

bash
npm run clean
npm run install:all
npm run build

Next Steps

🎉 Congratulations! You now have Headlamp running from source!

Here's where to go next:

Get Help


Quick Reference

Task Command
Install all dependencies npm run install:all
Build everything npm run build
Run dev mode (backend + frontend) npm start
Run desktop app npm run app:start
Run desktop app (dev, connects to running servers) npm run app:start:client
Run everything including app npm run start:with-app
Build backend only npm run backend:build
Build frontend only npm run frontend:build
Run tests npm test
Lint code npm run lint
Clean build artifacts npm run clean

Tutorials Plugin Development Getting Started Working With Kubernetes Data Advanced Index (`docs/tutorials/plugin-development/getting-started/working-with-kubernetes-data-advanced/index.md`)


title: "Tutorial 5: Advanced Kubernetes Interactions" sidebar_label: "5. Advanced Kubernetes Interactions" sidebar_position: 6

Advanced Kubernetes Interactions

This tutorial covers advanced patterns for working with Kubernetes data: creating custom resource classes for type-safe access and using the API to modify resources.


Table of Contents

  1. Introduction
  2. Creating Custom Resource Classes
  3. Using Your Custom Resource Class
  4. Modifying Kubernetes Resources
  5. Troubleshooting
  6. What's Next
  7. Quick Reference

Introduction

In Tutorial 4, you learned to fetch data using built-in resource classes and ApiProxy. This tutorial takes you further:

Topic What You'll Learn
Custom Resource Classes Create type-safe classes for any Kubernetes resource
Resource Mutations Update, patch, and modify resources via API

What You'll Build

By the end of this tutorial, you'll have:

  • A custom MyPod resource class with helper methods
  • A Pods page that allows you to evict pods (building on your custom class)

Prerequisites

Before starting, ensure you have:

Time to complete: ~30 minutes


Creating Custom Resource Classes

While K8s.ResourceClasses provides built-in classes for standard Kubernetes resources, you might need custom classes to:

  1. Add helper methods — Compute derived values (e.g., container images, age)
  2. Work with CRDs — Custom Resource Definitions don't have built-in classes

Understanding the Building Blocks

Headlamp provides these base types for creating resource classes:

tsx
import {
  KubeObject,
  KubeObjectInterface,
  KubeMetadata,
} from '@kinvolk/headlamp-plugin/lib/k8s/cluster';
Type Purpose
KubeMetadata Interface for .metadata (name, namespace, labels, etc.)
KubeObjectInterface Base interface all Kubernetes objects extend
KubeObject<T> Base class with built-in hooks (useList, useGet)

Step 1: Create a Custom Pod Class

Let's create a custom Pod class with helper methods. First, create a new file src/resources/pod.ts:

text
/* Detailed source-code truncated for AI context efficiency. */

Key Points:

Property Purpose
static apiVersion API version (e.g., v1, apps/v1, custom.io/v1alpha1)
static apiName API resource name (plural, e.g., pods, deployments)
static kind Kubernetes resource kind
static isNamespaced Whether resource is namespace-scoped
this.jsonData Access to the raw Kubernetes object

Step 2: Use the Custom Class

Now let's create a page that uses our custom MyPod class. We'll add a new Pods page to display pods using our custom class.

First, add the sidebar entry for the new Pods page. Then create the page component. Update your src/index.tsx:

text
/* Detailed source-code truncated for AI context efficiency. */

Test Your Custom Class

  1. Save both files (src/resources/pod.ts and src/index.tsx)
  2. Navigate to My Plugin → Pods in the sidebar
  3. You should see a table with pod information showing Name, Namespace, Container Images, and Age

Notice how we use our helper methods:

tsx
// These are our custom helpers from MyPod class
pod.containerImages  // string[] - array of container image names
pod.age              // string - formatted age like "5h 30m"

Using Your Custom Resource Class

The KubeObject base class provides many built-in methods and hooks. While we focus on useList and useGet below, you can refer to the KubeObject API documentation for the full list of capabilities, including:

useList() Hook

tsx
// List all pods across all namespaces
const [pods, error] = MyPod.useList();

// List pods in a specific namespace
const [pods, error] = MyPod.useList({ namespace: 'default' });

useGet() Hook

tsx
// Get a specific pod by name and namespace
const [pod, error] = MyPod.useGet('nginx-pod', 'default');

Accessing Raw Data

tsx
// Your custom class extends the raw data
const pod = pods[0];

// Access via helpers
console.log(pod.containerImages);  // string[]
console.log(pod.age);               // string like "5h 30m"

// Access via metadata (inherited)
console.log(pod.metadata.name);
console.log(pod.metadata.namespace);
console.log(pod.metadata.labels);

// Access raw JSON data
console.log(pod.jsonData.spec.containers);

The same pattern works for Custom Resource Definitions (CRDs)! Since CRDs don't have built-in resource classes in K8s.ResourceClasses, you can create your own:

tsx
// Example: Custom class for a CRD
export class MyCustomResource extends KubeObject<MyCustomResourceInterface> {
  static apiVersion = 'custom.io/v1alpha1';
  static apiName = 'mycustomresources';
  static kind = 'MyCustomResource';
  static isNamespaced = true;

  // Add your custom helper methods
  get customHelper(): string {
    return this.jsonData.spec.someField;
  }
}

Modifying Kubernetes Resources

Now let's learn how to modify Kubernetes resources. We'll start by adding functionality to our MyPod example.

Understanding Kubernetes Mutations

There are several ways to modify resources:

Method Use Case HTTP Verb Example
Replace Replace entire resource PUT Update entire pod spec
Patch Update specific fields PATCH Add/update labels, annotations
Delete Remove resource DELETE Delete a pod
Subresource Special operations POST Evict pod, scale deployment

Pod Eviction (Subresource POST)

Building on our MyPod example, let's add a "one-click" eviction feature. This demonstrates how to use subresources (like /eviction) and shows off Headlamp's automatic UI updates.

Step 1: Add Evict Method to MyPod Class

Update your src/resources/pod.ts to include an evict helper. This method uses ApiProxy (which we touched upon in the previous tutorial) to send a POST request:

tsx
import {
  KubeObject,
  KubeObjectInterface,
} from '@kinvolk/headlamp-plugin/lib/k8s/cluster';
import { ApiProxy } from '@kinvolk/headlamp-plugin/lib';

// ... (keep your existing interfaces)

export class MyPod extends KubeObject<MyPodInterface> {
  // ... (keep static properties and getters)

  // Method to evict a pod
  async evict(cluster: string): Promise<void> {
    if (!this.metadata.namespace) {
      throw new Error('Pod must have a namespace to evict');
    }
    await ApiProxy.request(
      `/api/v1/namespaces/${this.metadata.namespace}/pods/${this.metadata.name}/eviction`,
      {
        cluster: cluster,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          apiVersion: 'policy/v1',
          kind: 'Eviction',
          metadata: {
            name: this.metadata.name,
            namespace: this.metadata.namespace,
          },
        }),
      }
    );
  }
}

Step 2: Add Evict Button to MyPodsPage

Now, let's update MyPodsPage in src/index.tsx to use this new method. When a pod is evicted, it will gracefully terminate and eventually be removed from the list.

text
/* Detailed source-code truncated for AI context efficiency. */

Try it out: Click "Evict" and watch the pod disappear from the table. This happens because the useList() hook automatically refreshes when it detects the resource is gone!


Troubleshooting

Custom Class Not Working

If you encounter errors when using your custom class (e.g. methods not working or API calls failing), ensure your class has all required static properties configured correctly:

tsx
export class MyPod extends KubeObject<MyPodInterface> {
  static apiVersion = 'v1';      // Required (API version)
  static apiName = 'pods';       // Required (plural resource name)
  static kind = 'Pod';           // Required
  static isNamespaced = true;    // Required
}

[!NOTE]
Summary: In this tutorial, we learned how to create custom resource classes and how to use the ApiProxy for advanced uses like eviction. This and the previous example together cover Kubernetes data access and changes clearly.


What's Next

You've mastered advanced Kubernetes data patterns:

  • ✅ Creating custom resource classes with helper methods
  • ✅ Using useList() and useGet() on custom classes
  • ✅ Modifying resources with Subresources (Eviction POST)
  • ✅ Handling errors and understanding automatic UI updates

Next: Tutorial 6 – Building List & Detail Pages

  • Using ResourceListView component for professional list pages
  • Creating detail pages with DetailsGrid
  • Navigation between list and detail views
  • Custom columns and formatting

Quick Reference

Creating a Custom Resource Class

tsx
import {
  KubeObject,
  KubeObjectInterface,
} from '@kinvolk/headlamp-plugin/lib/k8s/cluster';

interface MyResourceInterface extends KubeObjectInterface {
  spec: { /* your spec fields */ };
  status?: { /* your status fields */ };
}

export class MyResource extends KubeObject<MyResourceInterface> {
  static apiVersion = 'v1';           // API version (e.g., 'apps/v1', 'custom.io/v1alpha1')
  static apiName = 'myresources';     // Plural resource name
  static kind = 'MyResource';
  static isNamespaced = true;         // or false for cluster-scoped

  // Add helper methods
  get myHelper(): string {
    return this.jsonData.spec.someField;
  }
}

Using Custom Classes

tsx
// List all resources
const [items, error] = MyResource.useList();

// List in specific namespace
const [items, error] = MyResource.useList({ namespace: 'default' });

// Get single resource
const [item, error] = MyResource.useGet('name', 'namespace');

Tutorials Plugin Development Getting Started Working With Kubernetes Data Index (`docs/tutorials/plugin-development/getting-started/working-with-kubernetes-data/index.md`)


title: "Tutorial 4: Working with Kubernetes Data" sidebar_label: "4. Working with Kubernetes Data" sidebar_position: 5

Working with Kubernetes Data

This tutorial teaches you how to fetch and display Kubernetes data in your plugin. You'll learn three different approaches: using cluster context, built-in resource classes, and direct API calls.


Table of Contents

  1. Introduction
  2. Understanding Cluster Context
  3. Using Built-in Resource Classes
  4. Fetching Single Resources
  5. Direct API Calls with ApiProxy
  6. Troubleshooting
  7. What's Next
  8. Quick Reference

Introduction

In Tutorial 3, you created pages with static content. Real plugins need to display live Kubernetes data like pods, deployments, nodes, etc.

This tutorial covers three ways to fetch Kubernetes data:

Approach Best For Example
getCluster() Getting current cluster context Display cluster name
K8s.ResourceClasses Standard Kubernetes resources List namespaces, nodes
ApiProxy.request() Custom endpoints, raw API calls Fetch API server version

What You'll Build

By the end of this tutorial, your plugin will:

  • Display the current cluster name
  • Show a list of namespaces
  • List namespaces as clickable buttons
  • Display namespace details when clicked
  • Fetch and display API server version information

Prerequisites

Before starting, ensure you have:

Time to complete: ~25 minutes


Understanding Cluster Context

When a user navigates to a cluster-specific page, your plugin needs to know which cluster they're viewing. Headlamp provides the getCluster() utility for this.

Display the Current Cluster

Let's update your Overview page to show the current cluster name.

Open src/index.tsx and update it:

tsx
import {
  registerRoute,
  registerSidebarEntry,
} from '@kinvolk/headlamp-plugin/lib';
import { getCluster } from '@kinvolk/headlamp-plugin/lib/Utils';
import { SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Typography, Box } from '@mui/material';

function OverviewPage() {
  const cluster = getCluster();

  return (
    <SectionBox title="Plugin Overview">
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
        <Typography>Current cluster:</Typography>
        {cluster ? <>{cluster}</> : <>{'N/A'}</>}
      </Box>
    </SectionBox>
  );
}

// Register the route (cluster view)
registerRoute({
  path: '/my-plugin',
  sidebar: 'my-plugin-overview',
  component: OverviewPage,
  exact: true,
});

// Register sidebar entries
registerSidebarEntry({
  name: 'my-plugin',
  label: 'My Plugin',
  icon: 'mdi:new-box',
  url: '/my-plugin',
});

registerSidebarEntry({
  parent: 'my-plugin',
  name: 'my-plugin-overview',
  label: 'Overview',
  url: '/my-plugin',
});

Test It

  1. Save the file
  2. Navigate to a cluster in Headlamp
  3. Click My Plugin → Overview in the sidebar
  4. You should see the cluster name displayed!

What's happening?

Code Purpose
getCluster() Returns the current cluster name from the URL (e.g., minikube)
Returns null When not in a cluster context (home view)

Note: getCluster() reads the cluster from the URL path (/c/:cluster/...). It only works on cluster-specific pages where useClusterURL: true (the default).


Using Built-in Resource Classes

Now let's fetch actual Kubernetes resources. Headlamp provides K8s.ResourceClasses with built-in hooks for all standard Kubernetes resources including Pod, Namespace, Node, Deployment, Service, ConfigMap, Secret, and many more.

📚 Full list: See ResourceClasses API Reference for all available resource classes.

Each class provides two hooks:

  • useList() — Fetch multiple resources
  • useGet(name, namespace?) — Fetch a single resource

List Namespaces

Let's display all namespaces in the cluster. Update your src/index.tsx:

text
/* Detailed source-code truncated for AI context efficiency. */

Test It

Save and navigate to your plugin page. You should see:

  • The cluster name
  • A count of namespaces
  • The first 5 namespaces listed

Understanding the useList Hook

tsx
const [namespaces, error] = K8s.ResourceClasses.Namespace.useList();
Return Value Type Description
namespaces Namespace[] | null Array of namespace objects, or null while loading
error Error | null Error object if the request failed

The Three States:

tsx
// Loading: data is null, no error
if (!namespaces && !namespacesError) {
  return <Loading />;
}

// Error: request failed
if (namespacesError) {
  return <Error message={namespacesError.message} />;
}

// Success: data is available
return <DisplayData namespaces={namespaces} />;

Fetching Single Resources

Sometimes you need to fetch a specific resource by name. Use useGet() for this.

Add Namespace Details

Let's enhance our OverviewPage to show details when a namespace is clicked. Update your src/index.tsx:

text
/* Detailed source-code truncated for AI context efficiency. */

What changed from the previous example:

Addition Purpose
useState for selectedNamespace Track which namespace is selected
NamespaceDetail component Uses useGet() to fetch single namespace
Button instead of List Clickable namespace selection
Conditional render Only show details when a namespace is selected

useGet Signature:

Resource Type Signature Example
Cluster-scoped useGet(name) Node.useGet('node-1')
Namespaced useGet(name, namespace) Pod.useGet('nginx', 'default')

Direct API Calls with ApiProxy

Sometimes you need to call Kubernetes APIs that don't have a built-in resource class, or you want more control over the request. ApiProxy provides direct access to the Kubernetes API server.

Example: Add API Server Version to Overview Page

Let's enhance our OverviewPage to also display the Kubernetes API server version using ApiProxy.request(). This builds on the previous example:

text
/* Detailed source-code truncated for AI context efficiency. */

What's new:

  • Added ApiProxy import and useEffect hook
  • Added versionInfo state to store API server version
  • Added useEffect to fetch version when cluster changes
  • Display version info below cluster name

Explore the Network Requests

To better understand how these API calls work, let's inspect the network traffic:

  1. Open your browser's Developer Tools (F12 or right-click → Inspect)
  2. Go to the Network tab
  3. Refresh your plugin page or navigate to it
  4. Look for the API requests:

You should see requests like:

  • /api/v1/namespaces - This is the useList() call fetching all namespaces
  • /version - This is the ApiProxy.request() call fetching API server version
  • /api/v1/namespaces/{name} - This appears when you click a namespace (the useGet() call)

Understanding ApiProxy.request

tsx
const response = await ApiProxy.request('/version', {
  cluster: cluster,
});
Parameter Description
First arg: /version The API endpoint path (relative to cluster API server)
cluster option Which cluster to send the request to

Recommendations:

  • Use K8s.ResourceClasses for standard Kubernetes resources—it handles caching, error handling, and real-time updates automatically
  • Use ApiProxy.request() for custom endpoints or when you need full control
  • Always handle loading and error states for a good user experience

Troubleshooting

"No cluster selected" Error

Problem: getCluster() returns null

Solution: Make sure you're on a cluster-specific page:

  • URL should be /c/:cluster/your-path
  • Route should have useClusterURL: true (default)

Data Not Loading

Check the console for errors:

  1. Open browser DevTools (F12)
  2. Look at the Console tab for error messages
  3. Check the Network tab for failed API requests

Common issues:

  • RBAC permissions — User may not have permission to list resources
  • Cluster connectivity — Check if Headlamp can reach the cluster

useList Returns Empty Array

Possible causes:

  • The resource type doesn't exist in the cluster
  • No resources of that type exist
  • Filtered by namespace (for namespaced resources)

For namespaced resources, you can filter by namespace:

tsx
// List pods only in the 'default' namespace
const [pods, error] = K8s.ResourceClasses.Pod.useList({
  namespace: 'default'
});

ApiProxy.request Fails

Check the endpoint path:

  • Ensure the path starts with /
  • Use the correct API group (/api/v1/ vs /apis/apps/v1/)

Check cluster parameter:

tsx
const cluster = getCluster();
if (!cluster) {
  // Handle no cluster case
  return;
}

const response = await ApiProxy.request('/version', {
  cluster: cluster, // Must be provided
});

What's Next

You've learned three ways to fetch Kubernetes data:

  • ✅ getCluster() for cluster context
  • ✅ K8s.ResourceClasses.useList() for listing resources
  • ✅ K8s.ResourceClasses.useGet() for single resources
  • ✅ ApiProxy.request() for direct API calls
  • ✅ Handling loading and error states

In the next tutorial, you'll learn advanced techniques:

Coming up in Tutorial 5: Advanced Kubernetes Interactions

  • Creating custom resource classes for type-safe data access
  • Using ApiProxy to modify resources (add labels, update resources)
  • Error handling for write operations

Quick Reference

getCluster

tsx
import { getCluster } from '@kinvolk/headlamp-plugin/lib/Utils';

const cluster = getCluster(); // Returns cluster name or null

K8s.ResourceClasses

tsx
import { K8s } from '@kinvolk/headlamp-plugin/lib';

// List all resources
const [items, error] = K8s.ResourceClasses.Namespace.useList();

// List with filters
const [pods, error] = K8s.ResourceClasses.Pod.useList({
  namespace: 'default',
});

// Get single resource (cluster-scoped)
const [node, error] = K8s.ResourceClasses.Node.useGet('node-name');

// Get single resource (namespaced)
const [pod, error] = K8s.ResourceClasses.Pod.useGet('pod-name', 'namespace');

ApiProxy.request

tsx
import { ApiProxy } from '@kinvolk/headlamp-plugin/lib';

// GET request
const response = await ApiProxy.request('/api/v1/namespaces', {
  cluster: 'my-cluster',
});

// With error handling
try {
  const data = await ApiProxy.request('/version', { cluster });
} catch (error) {
  console.error('Request failed:', error);
}

Contributing (`docs/contributing.md`)


title: Contribution Guidelines sidebar_label: Contributing sidebar_position: 4

This section has information on how to contribute to Headlamp. It assumes you have cloned
this repository (or your own GitHub fork).
Any contributions to the project are accepted under the terms of the project's
license (Apache 2.0).

Code of Conduct

Please refer to the Kubernetes Community Code of Conduct.

Development practices

The Headlamp project follows the Kinvolk Contribution Guidelines,
which promotes good and consistent contribution practices across Kinvolk's
projects. Before starting to contribute, and in addition to this section, please
read those guidelines.

Community Monthly Call

We hold a monthly call to discuss the project, the roadmap, and the community.

You can find Headlamp's Community Call event in its CNCF calendar.

Filing an issue or feature request

Please use the project's issue tracker for filing any bugs you find or features
you think are useful.

Guidelines for Submitting an Issue

When submitting an issue, follow these guidelines to help maintainers address it efficiently:

Search for Existing Issues:

  • Use the issue tracker to see if your issue already exists. If it does, consider adding your input to the existing issue instead of opening a new one.
  • If the issue doesn't exist, please create a new issue using one of the templates available:

Security issues

For filing security issues that are sensitive and should not be public, please see our SECURITY.md.

Submitting a Pull Request (PR)

Follow these steps when submitting a PR to ensure it meets the project’s standards.

1. Run Tests and Format Your Code

Run the following commands from your project directory:

  • npm run frontend:test - Run the test suite
  • npm run frontend:lint - Check code for lint and formatting issues
  • npm run frontend:lint:fix - Automatically fix lint and formatting issues where possible

These steps ensure your code is functional, well-typed, and formatted consistently.


2. Follow Commit Guidelines

Use atomic commits to keep each commit focused on a single change. Follow this structure for your commit messages:

<area>: <description of changes>

  • Both the title and the body of the commit message should not exceed
    72 characters in length.
    i.e. Please keep the title length under 72
    characters, and wrap the body of the message at 72 characters.

  • Commits should be atomic and self-contained. Divide logically separate changes
    to separate commits. This principle is best explained in the Linux Kernel
    submitting patches guide.

  • Commit messages should explain the intention, why something is done. This,
    too, is best explained in this section from the Linux
    Kernel patch submission guide.

  • Commit titles (the first line in a commit) should be meaningful and describe
    what the commit does.

  • Don't add code you will change in a later commit (it makes it pointless to
    review that commit), nor create a commit to add code an earlier commit should
    have added. Consider squashing the relevant commits instead.

  • It's not important to retain your development history when contributing a
    change. Use git rebase to squash and order commits in a way that makes them easy to
    review. Keep the final, well-structured commits and not your development history
    that led to the final state.

  • Consider reviewing the changes yourself before opening a PR. It is likely
    you will catch errors when looking at your code critically and thus save the
    reviewers (and yourself) time.

  • Use the PR's description as a "cover letter" and give the context you think
    reviewers might need. Use the PR's description to explain why you are
    proposing the change, give an overview, raise questions about yet-unresolved
    issues in your PR, list TODO items etc.

Examples:

Good

  • frontend: HomeButton: Fix so it navigates to home
  • backend: config: Add enable-dynamic-clusters flag

Bad

  • updates the manifest
  • Init feature added.
  • this adds new colors to the dashboard

For more detailed commit practices, see Kinvolk's Git contribution guidelines.


3. Write a Descriptive PR Description

When opening a PR, make sure to:

  • Summarize your changes and why they are needed.
  • Link to the related issue via fixes #ISSUE_NUMBER, if applicable.
  • Provide steps to test the changes.

Example:

This PR fixes the home button bug where the button did not navigate back to the homepage.

Steps to Test:

  1. Click on the 'Home' button in the sidebar.
  2. Verify that it navigates to the main screen.

4. Use Labels for Organization

Add relevant labels to your PR to help with triaging and prioritization:

Example:

  • enhancement
  • documentation

Coding style

The coding style for the backend and frontend should be consistent.
For helping and verifying that, we have go and js linters.

For linting the backend and frontend, use the following commands
(respectively):

bash
npm run backend:lint
bash
npm run frontend:lint

The linters are also run in the CI system, so any PRs you create will be
tested for compliance with the coding style.

To speed up a review from the project's maintainers, please make sure that
the CI checks are passing for your PR.

Complex contributions

If you have a complex contribution in mind (meaning changes in the architecture
or a lot of LOC changed), it is advisable to first file a GitHub issue and
discuss the implementation with the project's maintainers via #headlamp Slack channel.

Translations

If you want to contribute to the internationalization of Headlamp, please refer to the
dedicated i18n docs.

Commit guidelines

For general guidelines on making PRs/commits easier to review, please check
out Kinvolk's
contribution guidelines on git.

Testing

Major new functionality must include automated tests that exercise the new
behavior. These tests must be part of the project's automated test suite, and
reviewers must verify that they are included before approving the pull request.

The frontend test suite includes Storybook-related tests. New components should
have an associated story when possible.

For running the frontend tests, use the following command:

bash
npm run frontend:test

The backend uses go's testing and can be run by using the following command:

bash
npm run backend:test

Tests will run as part of the CI after a Pull Request is open.

Code review standards

Pull requests are merged through Prow/Tide only after receiving both lgtm
from a reviewers member (headlamp-reviewers or headlamp-maintainers in
OWNERS) and
approved from an approvers member (headlamp-maintainers in OWNERS).
Because a PR author cannot apply lgtm to their own PR, every merged change
requires review by at least one other person in addition to the author.

Before applying lgtm or approve, reviewers verify that:

  • Correctness and regressions: The change solves the stated problem, handles
    edge cases, and does not introduce regressions.
  • Security and sensitive paths: Untrusted inputs, authentication/RBAC,
    credentials, and manual-review-only files (such as .github/workflows/*,
    Dockerfile*, charts/, kubernetes-*.yaml, SECURITY.md,
    SECURITY_CONTACTS, OWNERS, OWNERS_ALIASES, LICENSE, NOTICE, and
    code-of-conduct.md) are reviewed carefully.
  • Tests and CI: Major new behavior and bug fixes include automated tests
    (see Testing), and required CI, lint, and formatting checks pass.
  • Scope and commit hygiene: Changes stay focused on a single purpose without
    unrelated refactors, and commits follow the commit guidelines
    with a linear history.

Faq (`docs/faq.md`)


title: Frequently Asked Questions sidebar_position: 5

General Questions

What is Headlamp and who is it for?

Headlamp is a graphical user interface specifically tailored to simplify the management of Kubernetes clusters.

What Kubernetes flavors or vendors does Headlamp support?

Headlamp is designed to be vendor-agnostic, supporting a variety of Kubernetes flavors. For a full list of compatible platforms, please refer to our platforms section in the documentation.

Is Headlamp a desktop or web application?

Headlamp is available both as a desktop application and a web application. The desktop version can be installed on your local machine and the web version can be accessed through a browser.

Is there any cost involved in using Headlamp?

Headlamp is a 100% open source project, under the Apache 2.0 License. It is thus available at no charge, and users are encouraged to modify and redistribute it in accordance with the license terms.

Can I use Headlamp for commercial purposes?

Yes, and it's encouraged. Headlamp is developed under the permissive Apache 2.0 License making it ideal for personal and commercial use.

Where can I find the source code for Headlamp?

The source code for Headlamp is publicly available on GitHub. You are welcome to explore, fork, and contribute to the codebase.

Who maintains Headlamp?

You can find the list of Headlamp's maintainers in its OWNERS_ALIASES file in the repository. As a 100% open source project and a CNCF Sandbox project, Headlamp encourages any users/developers to participate in it.

What capabilities / credentials does Headlamp require to access my Kubernetes cluster?

Headlamp doesn't require access to the cluster itself; it instead relies on RBAC to connect to the Kubernetes API server. This means that it's the user(s) who must have the required credentials to access the cluster (via a service token or client certificate). Headlamp may store the token in the browser's local storage, but never in its backend/server.

Is Headlamp customizable?

Yes, Headlamp is highly customizable, thanks to its robust plugin system. This system extends Headlamp's core functionalities, catering to specific use cases and workflows. For more information on creating and managing plugins, visit our plugins page.

How often is Headlamp updated?

Headlamp tries to have a new feature version released every month. Sometimes, there may be delays of a couple of weeks. Bug fix versions can also be released between feature versions, whenever appropriate. These are often released quickly after a fix is added.


Installation and Setup

How can I install and access Headlamp?

To install Headlamp, follow the detailed instructions provided in the official installation guide. The process will guide you through downloading the application, setting up your Kubernetes cluster access, and launching Headlamp to connect to your cluster. For desktop applications, you can find additional information in the desktop installation guide.

Can I install Headlamp in my Kubernetes cluster?

Absolutely! Headlamp can be deployed directly within your Kubernetes cluster. Detailed instructions for in-cluster installation can be found in the in-cluster installation guide.


Usage and Features

Can I monitor multiple clusters with Headlamp?

Yes, Headlamp allows you to monitor multiple clusters. You can switch between different clusters using the cluster switcher in the Headlamp interface.

How can I organize a long list of clusters on the Home page?

You can organize clusters with tags such as environment=production or team=platform using Edit tags from a cluster's Home page menu or from its settings. Tags are Headlamp metadata, not Kubernetes resource labels. For writable kubeconfig contexts, they are saved in the headlamp_info.tags context extension alongside the custom cluster name and survive renaming and reimporting that kubeconfig. Sources without a writable kubeconfig context use browser-local tags instead; the editor explains where they will be saved.

Tag editing is disabled while a save is in progress. If saving fails, the editor retains the submitted draft so you can retry. If the context is removed, replaced or becomes ambiguous while saving, Headlamp reports an error rather than applying the saved snapshot to a different context.

In All Clusters, click a tag to filter by its exact key and value, or type free text in the Tags column filter. Only one tag filter is active at a time: clicking another tag replaces it, and clicking the same tag again clears it. While a tag filter is active, the Tags column stays visible, including on narrow screens, so you can clear it using the table filters. Use the Group by tag button beside the search and filter buttons to choose a grouping key. The button is highlighted while grouping is active; choose None in its menu to turn grouping off.

For example, the kubeconfig context extension looks like this:

yaml
contexts:
  - name: my-context
    context:
      cluster: my-cluster
      user: my-user
      extensions:
        - name: headlamp_info
          extension:
            customName: production
            tags:
              environment: production
              team: platform

Can I manage my Kubernetes resources directly through Headlamp?

Yes, Headlamp enables direct management of Kubernetes resources through its user interface as allowed by the user's role and permissions.

Headlamp is not showing delete/edit/scale buttons in a resource, why is that?

Headlamp shows controls based on the user's role (RBAC), so if the user has, e.g., no permissions to delete a resource, the delete button is not shown.

I cannot access any section in my cluster, it keeps saying Access Denied.

By default, Headlamp assumes users can list all namespaces. If you only have the permissions to list resources in certain namespaces, please access the cluster settings and set up the accessible namespaces.

How do I add or remove plugins in Headlamp?

To add or remove plugins in Headlamp, you can follow the plugin management instructions provided in the Headlamp plugin documentation.

Is there a way to contribute to the development of Headlamp features?

Absolutely! As an open source project, Headlamp thrives on community contributions. You can contribute in various ways, including submitting pull requests, creating plugins, reporting issues, and suggesting new features. For more details on how to get involved, visit our contribution section.

How can I get help or assistance for Headlamp?

For support, refer to the Headlamp documentation. For further assistance, join the Headlamp community on Slack or file an issue on the GitHub issues page.

Join our monthly community meeting if you want to chat in a zoom call.


Platforms (`docs/platforms.md`)


title: Platforms sidebar_position: 3

Tested Kubernetes Platforms

This section shows the platforms where Headlamp has been tested (in-cluster) or is to be tested, and useful observations about it.
If you have tested Headlamp on a different flavor or Kubernetes, please file a PR or issue to add your remarks to the list.

The "works" column refers to the overall Kubernetes-related functionality when running on the respective platform; it may have 3 different values:

  • ✔️ : Has been tried and works well to the extent of what has been tested
  • ❌ : Has been tried and didn't work or had issues that prevented a regular use of it
  • ❔: Hasn't been tried/reported yet
Platform Works Comments
Amazon EKS ✔️ - As reported here.
DigitalOcean Kubernetes ✔️ - Works correctly as reported in #4317.
Google Kubernetes Engine (GKE) ✔️ - As reported here.
K3s ✔️ - Simple to install / expose with the regular in-cluster instructions.
Kind ✔️ - Simple to install / expose with the regular in-cluster instructions.
Microsoft AKS ✔️ - Working fine in-cluster and with the desktop application.
Minikube ✔️ - For exposing with an ingress, enable ingresses with minikube addons enable ingress: - There are docs about the development with Minikube.
Vultr Kubernetes Engine ✔️ - Simple to install / expose with the regular in-cluster instructions.
Red Hat OpenShift ✔️ - Simple to install / expose with the regular in-cluster instructions.
K0s ✔️ - Simple to install / expose with the regular in-cluster instructions.
vSphere Kubernetes Service (VKS) ✔️ - Simple to install / expose with the regular in-cluster instructions.
Talos Linux ✔️ - Simple to install / expose with the regular in-cluster instructions.
Oracle Kubernetes Engine (OKE) ✔️ - As reported here.
Linode Kubernetes Engine (LKE) ✔️ - Simple to install / expose with the regular in-cluster instructions.
Nutanix Kubernetes Platform (NKP) ✔️ - Simple to install / expose with the regular in-cluster instructions.

Tested Browsers

We mostly test with 'modern browsers' defined as the latest version and two older versions. But we try to make Headlamp work with web standards, so it's quite likely other standards-conforming browsers will also work.

Platform Works Comments
Edge ✔️
Safari ✔️
Firefox ✔️
Chrome ✔️
Internet Explorer 11 ❌

Tested Desktop OS, for App version

We test on MacOS, various flavours of Linux, and Windows. Headlamp runs in the browser, but also as an App.

Platform Works Comments
Windows 10, 11 (including in WSL2) ✔️
MacOS (arm, x86) ✔️
Ubuntu 20.04, 22.04, 22.10 ✔️
Fedora ✔️
Flatpak ✔️ See running external tools from Headlamp if you need to use az, aws, gcloud, etc. in your kubeconfig

CNCF and Kubernetes Integrations

See these two links for up-to-date lists of plugins which integrate with our cloud native projects:

Here is a list of CNCF project integrations at time of writing:

Project
Backstage
Flux
Inspektor Gadget
Kompose
KubeScape
KubeVirt
OpenCost
Prometheus
Trivy

Development App (`docs/development/app.md`)


title: Desktop App sidebar_position: 3

Headlamp's desktop application is built using Electron. It packages the frontend UI and backend server into a standalone desktop application for Windows, macOS, and Linux.

The desktop app is written in TypeScript and uses Babel to transpile the Electron code. It provides a native desktop experience with features like system tray integration, window management, and plugin support.

Building and running

First, install the required dependencies by running:

bash
npm run frontend:install
npm run app:install

The desktop app can be quickly built using:

bash
npm run app:build

This command builds the frontend, sets up plugins, and compiles the Electron app into a distributable package.

Makefile packaging targets also rebuild the frontend before preparing the app,
even when frontend/build already exists.

Backend compiler/linker settings are inherited by desktop packaging. For an
unstripped backend, set GOFLAGS='-ldflags=' when running the packaging command. See
backend compiler flags and debugging information.

To build without creating installers (faster for development):

bash
npm run app:build:dir

Once built, it can be run in development mode using:

bash
npm run app:start

For development with live-reload (requires the backend and frontend to be running separately):

bash
npm run app:start:client

Or run everything together:

bash
npm run start:with-app

Lint

The app code uses the frontend linting configuration. To lint the app/ code:

bash
npm run app:lint

This command can fix some lint issues:

bash
npm run app:lint:fix

Format

To format the app code:

bash
npm run app:format

Test

On Linux or macOS, run build dependency regression tests from the repository
root with node --test tools/build-dependencies.test.js. These tests require
Bash, GNU Make, Node.js, Go, and a C compiler on PATH. The dash-specific
interrupted-build cleanup regression is skipped when /bin/dash is unavailable
and runs on Linux CI; native Windows is not
supported by the full suite. The portable entrypoint and artifact-verification
subset also runs on native Windows:

bash
node --test --test-name-pattern="native build entrypoints" tools/build-dependencies.test.js

Run unit tests:

bash
npm run app:test:unit

Run end-to-end tests:

bash
npm run app:test:e2e

Run all tests (unit + e2e):

bash
npm run app:test

Type checking

To check TypeScript types:

bash
npm run app:tsc

Translations (i18n)

The app uses i18next for translations. Translation keys are extracted from app/electron/main.ts using i18next-parser.

To regenerate translation files after changing translatable strings:

bash
cd app && npm run i18n

To check that translation files are up to date (exits with an error if any file would change):

bash
npm run app:i18n-check

This check runs automatically in CI to prevent translation regressions when code or dependencies change.

Packaging

To package the app for all platforms:

bash
npm run app:package

Platform-specific packaging:

bash
npm run app:package:win      # Windows
npm run app:package:linux    # Linux
npm run app:package:mac      # macOS
npm run app:package:win:msi  # Windows MSI installer

Custom product builds

Product builds can select an alternative app build manifest and record the
source revision used to assemble the package:

Environment variable Default Description
HEADLAMP_BUILD_MANIFEST app/app-build-manifest.json Path to the JSON build manifest. The checked-in default configures both Electron packaging and generated frontend metadata.
HEADLAMP_SOURCE_COMMIT Current Git revision or unknown Source revision written to REACT_APP_HEADLAMP_GIT_VERSION. Set this when building from packaged source without its Git repository.

The manifest's product.productName and product.version fields configure the
identity displayed by the frontend as well as the packaged desktop app.
product.companyName configures the packaged app's Windows company metadata,
macOS copyright attribution, and Linux vendor. Set platforms.linux.maintainer
separately to a package contact in Name form. Missing or empty fields
retain the values from app/package.json.

product.trayIcon optionally selects a system tray icon using a path relative
to the packaged resources directory. Declare the same file in resources so
Electron Builder copies it into the package.

product.errorReporting optionally configures the generic error page's crash
report action. Set githubIssueUrl to the full GitHub issue creation URL;
existing query parameters such as labels or template are preserved when
Headlamp adds the crash title and diagnostic body. Set buttonLabel to replace
the translated Open Issue on GitHub label with product-owned text.

For example:

json
{
  "product": {
    "name": "example-desktop",
    "productName": "Example Desktop",
    "companyName": "Example Company",
    "version": "1.2.3",
    "trayIcon": "assets/example-tray.png",
    "errorReporting": {
      "githubIssueUrl": "https://github.com/example/product/issues/new?labels=bug",
      "buttonLabel": "Contact support"
    }
  },
  "resources": {
    "common": [{ "from": "./example-tray.png", "to": "assets/example-tray.png" }]
  },
  "platforms": {
    "linux": {
      "maintainer": "Example Company <[email protected]>"
    }
  }
}

Build the app with the selected manifest and source revision:

bash
HEADLAMP_BUILD_MANIFEST=./product/app-build-manifest.json \
HEADLAMP_SOURCE_COMMIT=0123456789abcdef \
npm run app:build

Frontend environment generation resolves a relative manifest path from the
app/ directory. Electron packaging resolves it from the process working
directory. The root app scripts run Electron packaging from app/, so the
example above selects app/product/app-build-manifest.json for both consumers.
Use an absolute manifest path when invoking either consumer directly from a
different working directory.

The standard make image and npm run image:build commands pass the current
Git revision to container builds. Direct Docker callers selecting a custom
product manifest should pass both the manifest path and source revision:

bash
docker buildx build \
  --build-arg HEADLAMP_BUILD_MANIFEST=./product/app-build-manifest.json \
  --build-arg HEADLAMP_SOURCE_COMMIT=0123456789abcdef \
  -f Dockerfile .

The manifest must remain available throughout the frontend and app packaging
steps. An unreadable manifest, a non-object product, non-string
productName/version fields, invalid errorReporting fields, or values
containing newlines stop the frontend build rather than silently using
inconsistent product metadata. Electron packaging additionally rejects a
non-string companyName. The frontend environment generator also rejects values
containing both a single quote and a backtick when they additionally contain
either a double quote or a literal backslash-n/backslash-r sequence, because
no dotenv quote delimiter can represent them without changing the value.

Build manifest resources

The resources field appends common or platform-specific files and directories
to Electron Builder's existing extraResources. Resource from paths resolve
from the directory containing the selected manifest:

json
{
  "resources": {
    "common": [{ "from": "./shared", "to": "shared" }],
    "linux": [{ "from": "./tools/linux", "to": "tools" }],
    "mac": [{ "from": "./tools/mac", "to": "tools", "filter": ["**/*"] }],
    "win": [{ "from": "./tools/windows.exe", "to": "tools/tool.exe" }]
  }
}

Only common, linux, mac, and win resource groups are supported. Each
group must be an array of objects with a from string and optional to string
or filter string array. Invalid resource configuration stops packaging before
Electron Builder runs.

For example, from the repository root:

bash
HEADLAMP_BUILD_MANIFEST=./product/app-build-manifest.json npm run app:package

Packaged resource verification

The verify field checks selected files after Electron Builder copies them into
the package. Each entry declares a path relative to the packaged resources
directory and its expected SHA-256 digest:

json
{
  "verify": [
    {
      "path": "tools/helper",
      "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
      "platforms": ["linux", "mac"]
    }
  ]
}

The optional platforms array accepts linux, mac, and win. An entry without
platforms applies to every package. Verification stops packaging when a file
is missing, escapes the resources directory, is a directory or symbolic link,
or does not match its declared digest.

Development workflow

The typical development workflow for the desktop app:

  1. Make changes to the app code in app/electron/
  2. Run linting and formatting: npm run app:lint:fix && npm run app:format
  3. Run type checking: npm run app:tsc
  4. If you added or changed translatable strings, regenerate translations: cd app && npm run i18n
  5. Test your changes: npm run app:test
  6. Build and run: npm run app:start

Notes

  • The app code in app/electron/ is written in TypeScript (.ts files)
  • Babel compiles TypeScript to JavaScript during the build process
  • Compiled .js files in app/electron/ are git-ignored
  • The app uses the frontend's ESLint and Prettier configuration
  • For linting/formatting, the app scripts delegate to the frontend scripts
  • MCP child processes inherit the MCP SDK's platform-specific default environment
    rather than the full desktop environment. Grant additional variables explicitly
    in the MCP server's env configuration. Values must be strings; malformed
    entries are reported and ignored. Windows variable names are normalized to
    uppercase so explicit overrides replace the SDK defaults.
  • Active cluster-dependent MCP servers restart when selected cluster membership
    or the first/current cluster changes. Reordering only secondary selected
    clusters does not restart them. The caller's cluster order is preserved when
    expanding HEADLAMP_CURRENT_CLUSTER, and cluster updates do not start dormant
    servers.

Development Architecture (`docs/development/architecture.md`)


title: Architecture sidebar_position: 0

Introduction

This document explains how Headlamp is built. It covers the main parts of the system, how you can run it, how to customize it, and the ideas behind its design.

Headlamp is a user-friendly and extensible Kubernetes UI. It is designed to provide a seamless experience for managing Kubernetes clusters. It can connect to one or multiple Kubernetes clusters and can be deployed as a web app in-cluster or as a desktop app. You can customize Headlamp using plugins, which let you change how it looks and works to fit your needs.

High-Level Architecture and Request Lifecycle

The diagrams below show how Headlamp works and the different ways you can run it.

Data Flow / Request Lifecycle

How does a typical user request flow through Headlamp?

Headlamp running as a Desktop App (on MacOS, Windows, Linux etc)

mermaid
graph TD
    A[User] -->|Interacts with| B[Headlamp App]
    B -->|Runs| C[Frontend, React]
    B -->|Runs| D[Backend headlamp-server, Go]
    D -->|Proxies| E[Kubernetes API]
    C -->|Loads| F[Plugins]
    D -->|Serves static web files and provides services to| C

Headlamp Web App running inside a Kubernetes Cluster

mermaid
graph TD
    A[User] -->|Interacts with| G[Ingress/Gateway API]
    G -->|Routes to| B[Frontend, React]
    B -->|Sends requests to| C[Backend headlamp-server, Go]
    C -->|Proxies| D[Kubernetes API]
    C -->|Interacts with| E[Cluster Services]
    B -->|Loads| F[Plugins]
    C -->|Serves static web files and provides services to| B
    subgraph Kubernetes Cluster
        B
        C
        E
    end

Notes:

  • Frontend handles user interactions and displays data.
  • Backend acts as a proxy and service layer. Handling authentication, RBAC, and API aggregation.
  • Kubernetes API is the source of truth for cluster state.
  • WebSocket connections follow a similar path. However, they maintain persistent connections for real-time updates.

WebSocket Lifecycle and Real-Time Updates

How does Headlamp get real-time updates from Kubernetes clusters?

  • WebSockets are used for real-time updates from Kubernetes.
  • Browsers support a limited number of connections: six usually.
  • How is the browser's WebSocket limit overcome? Headlamp uses one WebSocket from the browser to the headlamp-server. That server then opens many WebSockets to different Kubernetes API servers.
mermaid
graph LR
    A[Browser] <-->|WebSocket| B[headlamp_server]
    B <-->|WebSocket| C[Kubernetes API Server]
    B <-->|WebSocket| C
    B <-->|WebSocket| D[Kubernetes API Server]
    B <-->|WebSocket| E[Kubernetes API Server]

Plugins

Plugin Hosting Options

Where can plugins be hosted? It's possible to host plugins in many places both publicly and privately.

See:

mermaid
graph TD
    F[Plugins] -->|Can be| I[Private and Self Hosted]
    F -->|Or| J[Publicly Hosted, for example on GitHub, Gitlab, Bitbucket]
    J -->|May be optionally| K[Indexed by Artifact Hub]

Plugin Using and Bundling Options

How can plugins be enabled?

  • Operators can configure which plugins they enable for their deployed version of Headlamp.
  • Users of the Headlamp Desktop app can install and enable their own plugins.
  • The Headlamp Desktop App can browse and install Headlamp Plugins indexed on Artifact Hub.
  • Some plugins are bundled with the Headlamp app.
  • Some plugins are bundled with the container image.
mermaid
graph TD
    F[Plugins] -->|Bundled with| K[Headlamp Container Image]
    F -->|Bundled with| L[Headlamp Desktop App]
    F -->|Installed by| M[Users in Desktop App ~/.config/Headlamp/plugins]
    F -->|Installed from| N[Artifact Hub]
    O[Operators] -->|Configure enabled plugins in| P[Deployed Headlamp Instance]
    M -->|Can browse| N
    N -->|Install plugin to| M

Source Map for Components

Headlamp consists of the following major components:

  • frontend/: A React-based UI that interacts with the backend to manage clusters.
  • backend/: A Go-based server that communicates with the Kubernetes API and the frontend.
  • app/: A native Electron-based application for running Headlamp as a desktop app.
  • plugins/examples: Example plugins demonstrating how to extend Headlamp.
  • plugins/headlamp-plugin: A component to manage plugins in development and in deployment.
  • docs/: Documentation that is in Markdown, and gets put on the Headlamp Website.

The following components are in separate GitHub repos:

  • Plugins: Extensible modules that add custom functionality to the UI. The Headlamp team maintains their plugins in the headlamp-k8s/plugins repo. These include plugins for projects like Flux, Backstage and Inspektor Gadget.
  • Headlamp Website: Maintained in the headlamp-k8s/headlamp-website repo. This contains things like the blog and the documentation. The website can be found at https://headlamp.dev/

npm scripts entry point

The headlamp/ repo root package.json contains scripts for building and testing different components.

Here are some examples:

shell
npm run backend:build
npm run backend:lint
npm run backend:test
npm run backend:start
npm run frontend:build
npm run frontend:lint
npm run frontend:test
npm run frontend:start
npm run app:test
npm run start:app

Frontend

A few key dependencies:

  • TypeScript: Written in TypeScript.
  • React Components: Modular and reusable components that form the UI.
  • MUI: For UI components, it uses MUI, a Material UI component library.
  • State Management: Uses Redux for managing application state.
  • Routing: Utilizes React Router for navigation within the app.
  • Npm: Uses npm for package management.

Each component has a matching .stories.tsx file. For example, Tables.stories.tsx is the story file for the Table.tsx component.

Backend (headlamp-server)

  • The backend/ folder contains the source code for the headlamp-server binary.
  • Entry point is backend/cmd/headlamp.go
  • See the Backend Documentation for more information including a Quickstart.
  • Golang: Written in the Go programming language.
  • Gorilla: Uses the Gorilla web toolkit for HTTP routing and middleware.
  • Kubernetes and Helm: Integrates with Kubernetes and Helm Go packages.

Packages are stored in the backend/pkg folder. The packages available are cache, config, helm, kubeconfig, logger, plugins, portforward, and utils. Future code should be organized in packages. Some code in the cmd/ folder should move into separate packages.

For each module we have a test file. For example config.go comes with config_test.go.

Desktop App

A few key dependencies:

  • TypeScript: Language in which the app's code is written.
  • Electron: Used to create a native desktop application for Headlamp.
  • Yargs: Used for command line argument processing.

Plugins

What plugin-related resources are available, and where are they located?

A key dependency:

  • headlamp-plugin: provides commands for running builds, linting, formatting, and testing. Provides shared config for tools like TypeScript, linting and formatting. Also provides tools for upgrading plugins between releases of Headlamp.

Design Principles and Core Behaviors

This section outlines the key ideas that guide how Headlamp is built and what must always be true about how it works.

  • Extensibility: Headlamp supports plugins, so users can customize how it looks and works.
  • Multi-Cluster Support: It can connect to and manage more than one Kubernetes cluster at the same time.
  • Security: All actions must be secure and follow Kubernetes RBAC rules.
  • Accessibility: The interface should be easy and comfortable for everyone to use.
  • Realtime: It updates automatically when something changes in the cluster.
  • Consistency: The UI should always show the current state of the cluster.
  • Adaptive UI: The interface should adjust based on what the user is allowed to do. For example, if a user can’t edit something, they’ll only see a “view” button.

If you're planning a big change to Headlamp, please open an issue first. See the contribution guide for more info.

Deployment Options

See the Installation Documentation for more information, including a Quickstart.

As mentioned above, Headlamp can be deployed as a container inside a Kubernetes cluster or as a Desktop app.

Future Work

To see planned or in progress features, check the Release Plan / Roadmap. It’s regularly updated, but it's a tentative plan.

Note: Since Headlamp is open source, people contribute things that aren’t listed there. You can also explore:

  • Open issues — for bugs, feature requests, and discussions.
  • Pull requests — to see what changes are being proposed or reviewed.
  • Milestones — to track progress toward upcoming releases.

Releases

We aim to release Headlamp monthly, with bug fix releases as needed. Please see the releases on GitHub for information about released artifacts:

See the Release Guide for more information on how releases are done.


Development Backend (`docs/development/backend.md`)


title: Backend sidebar_position: 1

Headlamp's backend is written in Go. It is in charge of redirecting
client requests to the right clusters and returning any available
plugins for the client to use.

The backend's most essential function is to read the cluster information
from the given configuration and set up proxies to the defined clusters as
well as endpoints to them. This means that instead of having a set of
endpoints related to the functionality available to the client, it simply
redirects the requests to the defined proxies.

Building and running

The backend (Headlamp's server) can be quickly built using:

bash
npm run backend:build

Once built, it can be run in development mode (insecure / don't use in production) using:

bash
npm run backend:start

The development launcher forwards SIGINT, SIGTERM, SIGHUP, and SIGBREAK
to the backend, matching cross-env's signal handling.

Compiler flags and debugging information

The npm and Makefile backend builds use a shared Go driver with no external
dependencies. Make backend builds do not require Node.js. The npm path uses a
small Node.js launcher, which does not add a requirement beyond npm itself.
The stdlib-only bootstrap ignores surrounding module requirements; the actual
backend build retains the caller's module and automatic toolchain settings.
With no linker overrides, both retain the existing -trimpath, -s, and -w
defaults.

GOFLAGS settings, including those saved with go env -w, are honored.
Use Go's -ldflags setting in GOFLAGS to replace the default stripping flags.
Makefile builds retain the application version and name, and embedded builds add
the required embed tag without discarding caller-supplied build tags.
Package-specific -ldflags settings keep Go's matching and precedence rules.

To retain symbol tables and DWARF debugging information:

bash
GOFLAGS='-ldflags=' npm run backend:build
GOFLAGS='-ldflags=' make backend

For easier stepping through unoptimized code with local source paths, use Go's
quoting syntax for settings containing spaces:

bash
GOFLAGS="-trimpath=false -ldflags= '-gcflags=all=-N -l'" make backend

These variables are inherited by desktop packaging hooks and embedded
cross-compilation targets. CC, CXX, CGO_CFLAGS, CGO_CXXFLAGS, and
CGO_LDFLAGS are passed through to Go unchanged when cgo is enabled; embedded
cross-compilation targets continue to disable cgo.
Generic C/C++ CFLAGS and LDFLAGS are not reinterpreted as Go options; use the
Go and cgo variables above.
The container build accepts --build-arg GOFLAGS=... and continues to use Go's
unstripped defaults unless stripping is explicitly requested.

CI exercises native Make/npm entrypoints on Linux, macOS, and Windows. Desktop
packaging and a backend-only container build request
GOFLAGS='-trimpath=false -ldflags=-compressdwarf=false'; the artifact verifier
then checks the recorded flags and uncompressed DWARF entries in the resulting
backend binaries, including packaged desktop resources.

Backend token protection

HEADLAMP_BACKEND_TOKEN enables a local trust boundary around protected backend
routes. The desktop app generates a random token for each launch and sends it to
its backend and renderer. Development commands such as npm run backend:start
set a predictable token for local use.

When HEADLAMP_BACKEND_TOKEN is unset or empty, backend-token enforcement is
disabled. This opt-in behavior preserves standalone development and test setups
that start the backend directly. Do not expose a non-in-cluster server with an
empty token: protected cluster, plugin, Helm, and proxy routes are then available
without this additional credential check.

When the variable is non-empty, clients must send the same value in the
X-HEADLAMP_BACKEND-TOKEN header. WebSocket clients use Headlamp's private
backend-token subprotocol instead. In-cluster mode does not use this desktop
token boundary and continues to rely on its configured authentication and
authorization mechanisms.

Multiplexed WebSocket ownership

Each /wsMultiplexer client socket owns its upstream subscriptions. Routing
userId values are not authenticated identities: a second socket using identical
cluster/path/user fields must establish its own upstream connection with its own
credentials. Its CLOSE messages and disconnect cannot stop another client's
subscription.

Watches (watch=true or watch=1) also include the exact original subscription
query in that ownership key. Different selectors or resource versions on the same
path are independent, and CLOSE targets only its own query. STATUS, data,
retry errors, and ACKs preserve the original query and userId even when an
upstream resume handshake uses a newer cursor. Explicit reopen replaces only
that exact watch subscription, never another query's connection.

Concurrent initial requests for the same client-owned route share one upstream
dial and its result. Other clients and routes dial independently. A waiting
request can cancel without cancelling the owner; CLOSE still invalidates the
reservation so a retired dial cannot install or remove a newer subscription.

An upstream connection retains the credential used for its handshake. Changing
credentials requires a new subscription/client connection; replacing a stored
token cannot reauthenticate an existing socket. Explicit unsafe service-account
mode still uses its configured service-account credential, with separate
subscriptions per client.

Finite stream completion closes the upstream socket and leaves the subscription
available to its client. Watches retain the main branch's exponential
backoff and resume from the last resource version successfully forwarded to the
client; expired watches ask the client to list again instead of resuming.
Routine upstream watch timeouts (close code 1000) and going-away closes (1001)
resume in the same way. An ErrCloseSent ping waits for the reader's close
classification; it does not stop the sole monitor. A pending explicit reopen
also leaves that monitor alive so a failed watch replacement can retry.
Non-watch streams, including exec and logs, never redial automatically after a
failed ping or reader exit. Only a new explicit REQUEST can reopen them.
CLOSE and client disconnect cancel a pending replacement.
Requests received during a replacement get a retry error. The multiplexer also
reports upstream write failures to the requesting client.

Opted-in list and single-object watch subscriptions recognize the
subscription_reconnecting error code. Open watch transports in the error state
return the same coded error during backoff even when no dial is currently reserved.
Once the pending replacement finishes, they explicitly send REQUEST with
reopen: true and their own query and original routing identity. This watch-only
operation checks the existing handshake credential before replacing the socket.
Both explicit replacements and heartbeat recovery resume from the last forwarded
resource version and seed the replacement's cursor, even before its first event.
Status and data keep the exact original query for routing. Multiplexed browser
watches share the opening cursor per cached query and pin it until a relist/refetch;
cache updates do not change their subscription identity. Normal object watches
open with an empty cursor rather than an object's possibly expired last-write
version. Once the watch is connected, a named GET reconciles an object that was
deleted before the handshake; this does not add LIST permissions to normal
GET/watch use. A shared event revision prevents successful reads from replacing
newer watch updates or restoring a deleted object. Accepting a changed GET
snapshot renews the watch generation, so a reconnect cannot replay older events
over it. Until that generation receives its first event, renewal preserves the
empty cursor instead of using an object's potentially compacted last-write
version. A named GET newly returning 404 retires the previous generation and
starts a fresh empty-cursor watch for recreation; repeated absence does not renew
it again. Remounting a cached deletion starts an empty-cursor watch and named GET,
not a collection LIST.
Renewed object-watch generations use a query-cache-owner-scoped multiplexer
session. The existing protocol routes frames by query, not stream generation, so
replacing callbacks on the same session cannot fence queued frames when the
cursor remains empty. Observers of the same owner/generation share that session;
other owners and healthy sibling sessions are unaffected. Retired sessions close
after their last observer leaves, and the owner's recovery budget survives
generation changes. Existing list and finite-stream callers retain their shared
multiplexer session and wire format.
Legacy watches resume from their latest observed cursor. Since browsers hide an
HTTP 410 handshake rejection as a generic socket failure, repeated failed legacy
handshakes trigger a fresh snapshot before reopening. Recovery is scoped to the
query-cache owner, not just the watch URL: lists with different cache keys, such
as different limits, cannot advance each other's shared transport cursor.
There are at most three snapshot recoveries per owner between successful socket
opens. Cursor changes and successful LIST responses do not reset this budget.
Exhaustion stops automatic recovery and reports an error; a successful open
resets it. Legacy transport errors remain visible with cached items until
readiness, even when LIST continues to succeed.
An explicit 410 suspends that list's watch and rejects retired callbacks until
a network snapshot succeeds. Failed snapshots leave it suspended with the error
visible; ordinary cache updates cannot resume it. Unsubscribing prevents pending
recovery from opening another socket, and paginated snapshots stay unwatched.
Reconciliation preserves unchanged per-entry sockets: recovery in one namespace
does not reopen healthy watches for other namespaces.
After a single-object watch expires, a name-filtered collection LIST supplies a
fresh snapshot and collection cursor: a named GET can keep returning an expired
object version. This recovery requires LIST permission, and failures are surfaced
through the query error. If a snapshot fails, the last successfully loaded object
remains visible with a warning in the details view; its expired watch stays
disabled until a snapshot succeeds. All observers adopt the fresh cursor,
including when the fetching observer unmounts. Deleted objects report 404 while
the watch remains active to observe recreation. Failed post-connect checks also
retain the last object with an error until reconciliation succeeds. Joining
seeded observers cannot overwrite the shared object or clear its error while a
post-connect check is pending or failed. Loaded CRD
pages, loaded custom-resource detail pages, and resolved environment values retain
usable resources alongside a warning instead of replacing them with a recovery
error. Custom-resource instance lists identify loaded snapshots from cluster
results, not the combined items array: an initial failed LIST can also return an
empty array. Successfully loaded empty snapshots remain usable during recovery;
initial failures remain blocking, and other pending lists retain their loader.
The outer definition LIST also keeps its loader while no snapshot exists, even
when aggregation returns an empty array; cached empty definitions remain visible
during their own refetches.
Transport-only failures do not change a successfully loaded object's status,
isError, or isSuccess; its error still exposes the live-update warning until
readiness returns. Actual read failures and authoritative deletions remain errors
and take precedence over transport warnings. Manually composed list views and
related-resource tables must forward watchErrors separately from fetch errors
to ResourceListView, ResourceTable, or ClusterGroupErrorMessage, including
when the last successful snapshot was empty.
New browser multiplexer sessions reconcile watches that have already applied
events before resubscribing, rather than replaying their pinned opening queries
into newer cached objects. This uses the same snapshot/error path on both v2
and legacy servers, without changing routing identities or the wire protocol.
Observers joining a route already waiting for reconciliation receive the same
snapshot-required notification. Upstream error statuses reach that route's error
listeners; connected status clears its warning through readiness.
The error's retryReady acknowledgement handles errors delivered after the
connected status or normal completion without retrying against a stale
pre-reconnect status. This retries only an outstanding rejected watch request.
Unsubscribed watches cancel the pending retry; generic and exec subscriptions do
not opt in.

Each client retains at most 64 unreserved completed subscriptions for explicit
reopening. Older completed entries are removed without affecting other clients
or reserved replacements. Retained entries still reject changed credentials;
an evicted route needs a fresh authenticated handshake. Retention indexes completed
entries per client and examines at most 65 entries when evicting, without scanning
active subscriptions or other clients. Successful replacements skip retention
entirely. Cleanup uses no additional timers or workers.

Client reads remain responsive while initial or replacement handshakes are
pending. CLOSE and disconnect invalidate the subscription and cancel the dial,
including a blocked HTTP upgrade; a canceled request cannot install a socket or
send its payload. Requests are processed by one bounded worker per client.
REQUEST queue exhaustion closes the client socket with a retry-later reason rather than
creating unbounded dial goroutines. Requests arriving during a pending dial are
not saved for automatic replay. CLOSE cancellation and transport cleanup are
immediate; their status notifications have a separate bounded queue, so they cannot
exhaust REQUEST capacity. Notifications are best effort and may be dropped when
that queue is full or the same route has already reopened.

Clients offer headlamp.multiplexer.v2.k8s.io before the original
headlamp.multiplexer.k8s.io protocol, alongside the existing private desktop
backend-token protocol when needed. The backend prefers v2 when offered and
continues to accept the original protocol or no selected protocol.
V2 advertises explicit ACK support. Independently of the selected protocol, the
backend honors every REQUEST carrying an optional requestId with a matching
ACK after the worker settles it, including a request canceled by CLOSE.
Parsed REQUESTs with missing routing fields receive ERROR followed by ACK without
executing upstream work.
This preserves older ACK-waiting clients that offer only the original protocol
or no protocol during rolling upgrades. ACK is flow-control credit, not an
upstream success result; requests without a requestId do not receive ACKs.
Only negotiated v2 enables browser request pacing and requestId fields. Legacy
connections send requests unpaced without request IDs or waiting for ACKs; STATUS,
ERROR, DATA, and COMPLETE are never processing credits. COMPLETE is a watch-batch
boundary, not subscription termination.
For v2, one per-socket 60-second missing-ACK deadline reports an explicit error
and closes the socket with private code 4000, triggering bounded watch-only
recovery and notifying finite-stream listeners. This does not create a timer
per subscription. The browser sends at most one unacknowledged
list-watch request per socket and keeps at most one queued request per active watch,
so distinct-subscription bursts do not exhaust the backend's 32-slot queue.
Concurrent socket opens share one promise rather than per-subscriber polling timers.
If a legacy burst nevertheless closes the socket with code 1013, the browser
reconnects and restores only opted-in active list watches with the same queries
and fresh handshake credentials. Automatic watch recovery is capped at three
attempts without ACK progress, including across snapshot-driven route changes;
failures are surfaced to subscription listeners. Original/no-protocol sessions
reset this budget after 60 seconds of healthy connected watch operation instead
of waiting for ACKs they never receive. An error or socket close cancels that
health window. Ordinary browser/backend socket closes also notify watch listeners
and trigger this bounded watch-only recovery without an explicit reconnect call.
The internal connection reset without a close event does not start recovery.
Generic/exec subscriptions are not automatically replayed by
recovery; interrupted finite operations receive an explicit error on ordinary
socket closes as well as overload and missing-ACK closes.

Multiplexer credentials use the same bounded chunk budget as login cookies
(up to 32 chunks of 3.8 KiB). Reverse proxies must
still allow the combined WebSocket Cookie request header for the number of
simultaneously authenticated clusters; deployments with smaller header limits
should reauthenticate before opening another cluster rather than increasing the
proxy limit.

Replacement reservations exclude upstream payload writes before the error status
is published. Status delivery never holds subscription lifecycle or global map
locks, so a stalled client cannot block other clients' lookups or cleanup.
Cleanup closes transports before sending statuses, and retiring transports are
detached before the replacement publishes its connected status.

A request queued during a heartbeat reservation gets an explicit retry even if
another client worker operation delays its processing until after installation.
A superseded watch reader retires its transport without closing the subscription,
so a failed replacement can retry with backoff from the last forwarded cursor.
Finite-stream completion, explicit close, disconnect, and watch expiry still
terminate their lifecycles as described above.

Protocol-level end-to-end tests use real client WebSockets, the production
multiplexer handler, and a local TLS upstream that rejects forged credentials:

bash
cd backend
go test -race ./cmd -run 'Test(Multiplexer|Reconnect|MonitorConnection)' -count=20

These tests do not require a live Kubernetes cluster or enable multiplexing in
the frontend. Ordinary logs/terminal streams use their direct cluster endpoints.

Service proxy content isolation

Service proxy responses set Content-Security-Policy: sandbox and
X-Content-Type-Options: nosniff to isolate service content from Headlamp's
origin. JSON and streaming are unchanged; interactive applications need a
separate origin.

Persistent cluster deletion

removeKubeConfig=true requires --allow-kubeconfig-changes and a registered
file-backed cluster. The backend uses its loaded file and original context key,
not client-supplied identifiers; configured external files and symlinks work.
Runtime imports and renames retain this origin.
Imports and deletions lock the same recorded path, including symlinks.
File updates precede in-memory removal, so failures keep the stored cluster.
Memory-only deletion does not require file-mutation permission.

JSON request body limits

Cluster add and rename, node drain, token-setting, and kubeconfig-parsing
endpoints accept one JSON value with a maximum body size of 1 MiB, including
trailing whitespace. Larger bodies return 413 Request Entity Too Large;
malformed JSON or additional JSON values return 400 Bad Request.
Unknown fields remain accepted for compatibility.

The limit is local to these endpoints, not global middleware. Kubernetes
API proxy requests are unchanged and can still forward larger manifests.

Node drain authentication

The frontend submits node drains and polls their status through
/clusters/<cluster>/drain-node and /clusters/<cluster>/drain-node-status.
These paths receive the existing cluster-scoped authentication cookie and OIDC
refresh middleware; the current drain uses the refreshed user credential.
Kubernetes RBAC and audit events therefore use the caller's identity.

In-cluster requests without a user credential are rejected unless the existing
unsafe service-account mode was explicitly enabled. Drain does not implicitly
fall back to the pod's service account or forward that credential to an external
context. Legacy unscoped routes remain available for existing callers, but
cookie-only browser clients should use the cluster-scoped routes.

Helm release history

GET /clusters/<cluster>/helm/release/history requires non-empty name and
namespace query parameters. Missing or empty values return 400 Bad Request
before Helm accesses the cluster. Valid requests retain the existing
{"releases": [...]} response and release-lookup error handling.

Helm chart sources

Helm install (POST /clusters/<cluster>/helm/release/install) and
upgrade (PUT /clusters/<cluster>/helm/releases/upgrade) requests
accept only a chart of the form
<repository>/<chart>, where <repository> is a Helm repository
registered with the backend through the repository routes. Other values
are rejected with 400: http(s) and oci:// URLs, absolute and
relative paths, and references that also exist as a path on the
backend's filesystem. This only checks the chart value in the request,
so a client cannot pass a chart URL or a local path. It does not limit
which repository URLs can be registered, or the chart URLs listed in a
repository's index; those are not covered by this check. Clients that
installed charts from a direct URL must add the repository first and
install from it.

Kubernetes response cache

With --cache-enabled, users share resource responses within the same cluster
connection. Each GET still checks the caller's permissions through a Kubernetes
SelfSubjectAccessReview. Keys distinguish API versions, resources, namespaces,
names, query parameters and the Accept representation. For example,
/api/v1/namespaces/team/pods/shared and
/api/v1/namespaces/team/secrets/shared never share an entry.

A shared metadata list/watch invalidates each resource scope. It uses the
connection's credentials when available, or a requesting user's token for a
connection without stored credentials. Tokens are not saved to the context
store. Until the watch is synchronized, and whenever it disconnects, requests go
directly to Kubernetes. Authorization-check errors also bypass the cache.
Watch events and writes invalidate both existing responses and pending fills;
idle watches stop after ten minutes. Streaming, paginated, conditional, range,
impersonated and subresource requests bypass the response cache, as do requests
for a specific resource version or with Cache-Control: no-cache. Only successful
Kubernetes objects are stored, and never responses that set cookies, send
Cache-Control: no-store or vary on anything but Accept and Accept-Encoding.

Port-forward authentication and ownership

Port-forwarding requires Kubernetes 1.28+: every create/list/get/stop/delete
request authenticates using authentication.k8s.io/v1 SelfSubjectReview,
stable since Kubernetes 1.28.
The API server must permit the authenticated user to create self-subject reviews.
On older clusters, the unsupported v1 endpoint causes port-forward requests to
return HTTP 503 (Service Unavailable), rather than forwarding without verified
ownership. An unavailable review endpoint also fails closed; unverified JWT
claims or arbitrary nonempty bearer text are never trusted.

An Authorization bearer token takes precedence over the cluster cookie. Supplied
user tokens replace stored authentication methods for the request, so invalid
tokens cannot fall back to a configured certificate or token file. Static
kubeconfig credentials still work when no user token is supplied.
Cluster and effective API-proxy URLs containing credentials are rejected when a
request token is supplied: HTTP URL Basic authentication must not replace the caller's bearer
identity. Trusted configured URL credentials still work without a request token.
This check uses client-go's server normalization, including scheme-less
user:password@host:port credentials, while preserving valid IP:port servers.
When proxy authentication is enabled, its configured token header takes
precedence and is subject to the same Kubernetes identity verification.
Using Authorization itself as that proxy header is supported case-insensitively;
an existing Bearer prefix is normalized only once. An explicitly supplied empty
credential is rejected, never replaced by a cookie or stored identity. Static
contexts with names that cannot form cookie names can still use their configured
credentials when no Authorization header was supplied.
The outer cluster OIDC middleware validates supplied Authorization before
refresh: an expiring cookie cannot replace an invalid header or collapse multiple
headers into an accepted credential. Legitimate cookie-only refresh still works.

Sessions are scoped by the exact context key, effective API server or
gateway/TLS/proxy authority, and the Kubernetes-returned username and UID.
Another user cannot list, inspect,
stop, delete, or overwrite them by
supplying the same forwarding ID. Refreshed tokens for the same principal retain
access; a different UID does not. Public cluster names and response shapes remain
unchanged. Existing unowned cache entries are not adopted by the next caller.
The store is in memory; no persistent session migration is required.

Stateless requests resolve their supplied KUBECONFIG afresh and use that same
context snapshot for authentication and forward creation. A cached routing key
cannot supply another caller's credentials. X-HEADLAMP-USER-ID is a routing
label, not authentication. Requests addressing a cached internal context without
their own token or request kubeconfig cannot borrow its stored credentials.
Cached internal contexts and in-cluster request-supplied contexts cannot read backend-local CA
files, even with an independent request token. They must embed the CA data or
use default system trust. An embedded CA takes precedence over a filename
without reading it. Trusted server-configured contexts retain file-backed CAs.
In-cluster request-supplied kubeconfigs cannot read backend-local token/certificate/key
files or run exec/auth-provider credential plugins. These methods require an
independent request token that replaces the configured credentials; otherwise
the request is rejected before authentication. Embedded credentials remain
supported, and trusted server-configured kubeconfigs keep their existing
credential methods.
The same in-cluster restrictions apply to contexts registered through
POST /cluster, including after persistence reload. Stored dynamic uploads and
contexts without recorded provenance require a caller-supplied token in-cluster;
they cannot supply another uploader's embedded identity. File-backed CAs remain
restricted even with that token. Trust follows the recorded source, not the
internal routing flag.
Desktop/development uploads retain local exec/OIDC providers, token and
certificate/key files, and file-backed CAs after the backend-token middleware.
Configure a nonempty HEADLAMP_BACKEND_TOKEN to protect that local trust boundary.
OIDC contexts without stored credentials return HTTP 401 before provider lookup.
API-proxy settings are resolved before credentials are replaced and retained for
identity verification and forwarding. Gateway CA data and skip-verification
settings replace the API server's TLS trust; unused API-server CA files are not read.
Recreating a context with a different endpoint or TLS/proxy trust configuration
does not grant access to existing sessions even if that endpoint claims the same
username and UID. Restoring the original authority with valid credentials retains
access across context-cache expiry.
File-backed certificate authorities are read into the copied request context
before authentication. The effective CA bytes determine session ownership and
are reused for forward creation, without rereading the filename. Replacing a CA
file at the same path cannot inherit surviving sessions; unreadable or empty
configured CA files fail closed. Embedded CA data takes precedence over a file.

In-cluster service-account credentials are not used in place of a missing user
token unless unsafe service-account mode was explicitly enabled. That unsafe
mode deliberately shares the service-account identity, not individual user
ownership. Desktop backend-token protection remains an additional boundary.

Run the local HTTP end-to-end and ownership regressions without a Kubernetes cluster:

bash
cd backend
go test -race ./pkg/portforward ./cmd -run 'TestPortForward(AuthenticatedOwnershipEndToEnd|AuthenticationFailsClosed|CreationKeepsOwnerScope|CookieOwnership|RoutesRejectForgedCredentials)$' -count=20

Header, Unicode-name, authority-replacement and stateless-cache regressions:

bash
cd backend
go test -race ./pkg/portforward ./cmd -run '^TestPortForward(ProxyAuthorizationNormalization|RejectsEmptySuppliedCredentials|UnicodeStaticContext|ContextReplacementPinsAuthority|Stateless.*)$' -count=20

The fully wrapped refresh-order regression is
go test -race ./cmd -run '^TestPortForwardValidatesAuthorizationBeforeRefresh$' -count=20.

These tests use the production request handler and real HTTP/TLS connections to a
local mock of the Kubernetes authentication API. Session-control tests use
synthetic channels and do not establish live Kubernetes port-forwards.

CI also enables the live Minikube lifecycle test. With a running minikube
context and a Headlamp pod exposing its backend port in the headlamp namespace:

bash
cd backend
HEADLAMP_RUN_INTEGRATION_TESTS=true go test -race ./pkg/portforward -run '^TestStartPortForward$' -count=1

This test creates a real forward and uses the authenticated request handler to
stop, list, inspect, and delete it. Cleanup also deletes the forward if a later
assertion fails; the test does not access owner-scoped cache records through
legacy unscoped keys.

Telemetry

Headlamp's backend supports OpenTelemetry for distributed tracing and Prometheus metrics. See the Telemetry guide for configuration, local setup with Jaeger and Prometheus, and in-cluster deployment.

Logging configuration

Headlamp’s backend supports configurable log levels to control verbosity.

Log level can be configured using either a flag or an environment variable:

  • the log level: --log-level or env var HEADLAMP_CONFIG_LOG_LEVEL

Supported Values:

  • debug
  • info (default)
  • warn
  • error

Note: Headlamp uses zerolog defaults.
Zerolog’s default log level is info, and Headlamp follows this behavior.

Examples

Run with warning level:

bash
./headlamp-server --log-level warn

Lint

To lint the backend/ code.

bash
npm run backend:lint

This command can fix some lint issues.

bash
npm run backend:lint:fix

Format

To format the backend code.

bash
npm run backend:format

Test

bash
npm run backend:test

The development launcher's signal forwarding is tested by the app unit tests
(app/electron/run-backend.test.ts):

bash
npm run app:test:unit

Test coverage with a html report in the browser.

bash
npm run backend:coverage:html

To just print a simpler coverage report to the console.

bash
npm run backend:coverage

Memory profiling

Use representative kubeconfigs, clusters, and requests when comparing profiles. Run each
measurement several times and compare medians.

bash
# GC activity and heap goals for a running development server.
GODEBUG=gctrace=1 npm run backend:start 2>gc.log

# Heap retained by a test or benchmark.
cd backend
go test -run TestName -memprofile=/tmp/heap.pprof ./pkg/package
go tool pprof -inuse_space /tmp/heap.pprof

# Total allocations, including objects that have already been collected.
go test -run '^$' -bench BenchmarkName -benchmem \
  -memprofile=/tmp/allocs.pprof ./pkg/package
go tool pprof -alloc_space /tmp/allocs.pprof

# Allocation/free events, GC pauses, and goroutine scheduling.
GODEBUG=traceallocfree=1 go test -run TestName -trace=/tmp/trace.out ./pkg/package
go tool trace /tmp/trace.out

On Unix, GOTRACEBACK=all followed by kill -QUIT prints all goroutine
stacks. This terminates the process, so only use it on a development instance.
Repeated dumps reveal goroutines whose count or blocked stacks keep growing.

In pprof, start with top, top -cum, list <function>, and web.
inuse_space identifies long-lived allocations; alloc_space identifies allocation
churn. Compare profiles with go tool pprof -base before.pprof after.pprof.
In traces and GC logs, look for a growing live heap after GC, frequent collections
with little heap reduction, and increasing goroutine counts. Map growth appears as
retained runtime.mapassign call paths and should be checked for missing bounds or
expiration.

Ranked optimization opportunities

Rank Change Expected memory effect Trade-off
1 Share cache-invalidation watchers for equivalent cluster connections Avoids duplicated informer stores and goroutines for stateless users Requires careful authentication and watcher lifecycle isolation
2 Add byte and entry limits to the Kubernetes response cache Prevents unbounded retained response growth and avoids caching oversized responses Lower cache hit rate
3 Cache only the Kubernetes authorization client instead of a full clientset Removes unused typed clients from each token cache entry Narrows the internal cache API
4 Initialize proxy transports only when a context is first used Saves per-context TLS and transport state for unused contexts Adds synchronization to the first request
5 Lower GOGC for the desktop backend About 2–4.5 MiB in measured idle/request workloads More frequent GC and modestly higher CPU use

The desktop launcher defaults its bundled backend to GOGC=25, while preserving
an explicitly configured GOGC. In isolated measurements, GOGC=50 reduced
median startup RSS from 82,384 KiB to 80,492 KiB. Lowering it to GOGC=25
saved another 2.1 MiB of private dirty memory after 20,000 /config requests,
with about 11% more backend CPU than GOGC=50.

GOMEMLIMIT is a soft runtime limit rather than a live-heap target. Set it to
roughly 85–90% of a container's memory limit, leaving room for the executable,
stacks, and non-Go allocations. Limits between 20 MiB and 64 MiB did not
consistently reduce the small desktop startup workload, so the app does not force
a fixed value. Re-profile under production load before setting either variable.

Evaluated compiler and runtime options

The following medians are from three Linux amd64 runs of 20,000 local /config
requests with Go 1.26.5. Private dirty memory is reported instead of total RSS
because demand-paged executable mappings varied substantially with link layout.
These are directional results from a small workload.

Runtime configuration Private dirty after requests Backend CPU Result
GOGC=100 17.2 MiB 3.26 s Go default and comparison baseline
GOGC=50 14.8 MiB 3.37 s Saves 2.4 MiB over the Go default
GOGC=25 12.7 MiB 3.73 s Current desktop default; saves another 2.1 MiB with about 11% more CPU than GOGC=50
GOGC=50 GOMEMLIMIT=64MiB 14.8 MiB 3.43 s No measurable saving in this workload
GOGC=50 GODEBUG=disablethp=1 11.7 MiB 3.44 s Linux-only saving on this host; not used because the compatibility setting is scheduled for removal
GOGC=50 GOMAXPROCS=1 13.2 MiB 2.32 s Not used because serializing execution can hurt concurrent workloads

Compiler experiments used the same workload with GOGC=50:

Build option Binary size Private dirty Backend CPU Result
Default 114.4 MiB 14.8 MiB 3.37 s Baseline
-trimpath -ldflags="-s -w" 81.4 MiB 14.5 MiB 3.38 s Current backend build default; saves 28.8% on disk, but no meaningful runtime memory
-gcflags=all=-l 103.5 MiB 12.8 MiB 4.21 s About 2 MiB less memory at roughly 25% more CPU; not selected
GOAMD64=v3 114.4 MiB 14.9 MiB 3.41 s No memory saving and reduces CPU compatibility
-buildmode=pie 120.9 MiB 19.1 MiB 3.45 s Increased private memory
GOEXPERIMENT=greenteagc 114.4 MiB 14.7 MiB 3.47 s No meaningful saving in this workload

Go plugins are not a portable memory-saving mechanism for the backend. They are
unsupported on Windows, must match the main binary's toolchain and dependencies,
cannot be unloaded, and therefore retain their memory after first use. Splitting
optional features into helper processes would also add another Go runtime and IPC
complexity.

Fuzz Testing

Some backend functions include fuzz tests using Go's native fuzzing support. For example, the SanitizeClusterName function in backend/pkg/auth has a fuzz test.

To run fuzz tests:

bash
npm run backend:fuzz

This will run fuzz tests in the backend/pkg/auth package for 30 seconds. The fuzz corpus (interesting test cases discovered during fuzzing) is stored in testdata/fuzz/ directories and committed to the repository for regression testing.

For more information about Go fuzzing, see the official Go fuzzing documentation.


Development Cluster Api Discovery (`docs/development/cluster-api-discovery.md`)


title: Cluster API discovery

Cluster API discovery

Headlamp operators can enable automatic discovery of cluster.x-k8s.io/v1beta2
Clusters. Connections use the same discovery engine as
Cluster Inventory and authenticate each signed-in user through OIDC.

Backend option Environment variable Behavior
--enable-cluster-api HEADLAMP_CONFIG_ENABLE_CLUSTER_API Enables discovery; disabled by default
--cluster-api-namespaces=workload-team-a HEADLAMP_CONFIG_CLUSTER_API_NAMESPACES Selects management namespaces; empty uses each root's default namespace and * selects all
--cluster-api-label-selector='!headlamp.dev/ignore' HEADLAMP_CONFIG_CLUSTER_API_LABEL_SELECTOR Filters Cluster resources; this selector is the Helm default
--cluster-api-root-reconcile-interval=10s HEADLAMP_CONFIG_CLUSTER_API_ROOT_RECONCILE_INTERVAL Overrides the five-minute root reconciliation interval
--cluster-api-no-crd-cache-ttl=30s HEADLAMP_CONFIG_CLUSTER_API_NO_CRD_CACHE_TTL Overrides the two-hour cache for roots without the v1beta2 Cluster API

Global OIDC client ID, issuer URL, and non-empty scopes are required. Each workload
API server must trust that issuer and client. By default, root configurations are
checked every five minutes; management servers without the v1beta2 Cluster API are
retried after two hours. There is no v1beta1 fallback.

For a Cluster named spoke-a in workload-team-a, Headlamp reads the Secret
workload-team-a/spoke-a-kubeconfig. It must have:

  • Type cluster.x-k8s.io/secret.
  • Label cluster.x-k8s.io/cluster-name: spoke-a.
  • A data.value containing the workload kubeconfig.

The kubeconfig's current-context selects the connection. If it is absent, the
kubeconfig must contain exactly one context. Headlamp copies the HTTPS endpoint,
inline CA, TLS server name, TLS verification setting, proxy URL, compression
setting, and default namespace. It ignores local file paths, exec extensions,
and all user credentials in the Secret. Those credentials do not authenticate
workload requests and are never returned in discovery metadata. A Secret whose
CA is not valid PEM, or is combined with the insecure TLS setting, produces no
connection.

The management identity needs get, list, and watch on Cluster API clusters
and core secrets in the selected namespaces. Restrict write access to these
resources to trusted operators. Someone who can modify a discovered kubeconfig
Secret can redirect workload requests to an endpoint they control. Headlamp sends
the signed-in user's OIDC bearer token to that endpoint. The recipient can reuse
a still-valid token against other clusters that trust the same issuer and client
ID, subject to the user's permissions in those clusters.

Select namespaces whose discovery resource writers you trust with those tokens,
for example --cluster-api-namespaces=workload-team-a. Avoid
--cluster-api-namespaces=* if namespaces have differently trusted writers,
because this option includes discovery resource writers in every namespace.

One Cluster creates one connection named cluster-api-<root-and-cluster-key>--<hash>,
with ID cluster-api/<root>/<namespace>/<cluster-name>. The name and ID are stable
across Secret updates. Deleting the Cluster or Secret, invalidating its connection,
or excluding the Cluster with the selector removes its connection. Restoring the
resources restores it. Generated kubeconfigs are held in memory and cannot be
renamed in Headlamp.


Development Cluster Discovery Architecture (`docs/development/cluster-discovery-architecture.md`)


title: Cluster discovery architecture

Cluster discovery architecture

Headlamp operators can discover connections from Cluster Inventory API ClusterProfiles
and Cluster API workload Clusters. Both sources produce in-memory kubeconfigs and
use the same OIDC login, kubeconfig loader, proxy, context store, and response cache
as other OIDC connections. Generated connections have no persistent kubeconfig
origin, so their names cannot be edited.

Source Resources read on the management cluster Workload authentication
Cluster Inventory API multicluster.x-k8s.io/v1alpha1 ClusterProfiles Each user's OIDC token
Cluster API cluster.x-k8s.io/v1beta2 Clusters and their standard kubeconfig Secrets Each user's OIDC token

A management cluster's credentials are used for discovery only. In-cluster
Headlamp uses its service account and pod namespace. Outside a cluster it uses
non-internal, non-discovered kubeconfig contexts and their namespaces. Connections
created by any discovery source never become discovery roots.

Each source has independent watches and CRD availability tracking. A management
cluster can provide either API or both; one missing API does not disable the
other. Transient watch failures retry without discarding previously discovered
connections. Once caches synchronize, removed owners and invalid connections are
pruned. Names and IDs remain stable when connection settings change. Entries from
different sources remain separate even when their API server URLs match.

Design

Sources only describe what to watch and how to turn a resource into a connection.
Everything else is shared: informer lifecycle, pruning, OIDC, the kubeconfig
loader, the context store, the proxy, the response cache, and the home page
views. A discovered connection is therefore an ordinary OIDC kubeconfig context
and follows the same path as one loaded from a kubeconfig file.

text
/* Detailed source-code truncated for AI context efficiency. */

The extension contract is the Source interface. The engine calls it and owns
everything the interface does not mention.

mermaid
classDiagram
    class Registry {
        +Register(Source) error
        +Sources() []Source
    }
    class Source {
        <<interface>>
        +Descriptor() Descriptor
        +Watches(config, namespace, selector) []ResourceWatch
        +OwnersForChange(resource, obj) []NamespacedName
        +Build(root, owner, snapshot) []GeneratedKubeconfig
    }
    class Descriptor {
        +string ID
        +string DisplayName
        +GroupVersionResource Resource
        +SourceView View
    }
    class SourceView {
        +string NameLabel
        +[]SourceColumn Columns
        +[]SourceColumn DetailFields
        +[]string SummaryFields
    }
    class ResourceWatch {
        +GroupVersionResource Resource
        +InformerFactory Factory
        +SharedIndexInformer Informer
    }
    class Snapshot {
        <<interface>>
        +Get(resource, owner) object
    }
    class GeneratedKubeconfig {
        +string Key
        +string Name
        +string ClusterID
        +Config Config
        +map Metadata
        +ConnectionPresentation Presentation
    }
    class Runner {
        +Run(ctx)
    }
    Registry o-- Source
    Source <|.. clusterProfileSource
    Source <|.. clusterAPISource
    Source ..> Descriptor
    Descriptor *-- SourceView
    Source ..> ResourceWatch
    Source ..> Snapshot
    Source ..> GeneratedKubeconfig
    Runner --> Source : drives one source
    Runner ..> GeneratedKubeconfig : validates and publishes

Flows

Discovery

Each enabled source gets its own Runner. Roots are the in-cluster hub and, outside
a cluster, the non-internal, non-discovered contexts in the store. A root is
reconciled at start-up and then every root reconcile interval.

text
/* Detailed source-code truncated for AI context efficiency. */

A root moves through these states. A missing CRD never affects other sources
because each Runner keeps its own cache.

mermaid
stateDiagram-v2
    [*] --> Desired : hub or store context is a root
    Desired --> Active : watches built and started
    Active --> Active : same server and fingerprint, nothing to do
    Active --> Active : server or credentials changed, replace the root
    Active --> NoCRD : watch error says the CRD is missing
    NoCRD --> Desired : TTL expired, next reconcile retries
    Active --> Stopped : root is no longer desired
    Stopped --> [*] : connections pruned

Signing in and using a discovered connection

Discovery never stores workload credentials. Each user signs in through the
configured OIDC provider, and every request reaches the workload API server with
that user's own token. Kubernetes validates the token and applies the user's RBAC.

mermaid
sequenceDiagram
    autonumber
    actor U as User (browser)
    participant H as Headlamp backend
    participant IdP as OIDC provider
    participant W as Workload API server

    U->>H: GET /config
    H-->>U: clusters with meta_data and clusterSources
    Note over U: the home page builds one tab per source from clusterSources

    U->>H: GET /oidc?cluster=NAME
    H-->>U: redirect to the provider (state, optional PKCE)
    U->>IdP: authenticate
    IdP-->>U: redirect to /oidc-callback with code and state
    U->>H: GET /oidc-callback
    H->>IdP: exchange the code and verify the ID token
    H-->>U: per-cluster token cookie and redirect to /auth?cluster=NAME

    U->>H: GET /clusters/NAME/api/v1/pods with the cookie
    H->>H: requireUserAuthentication, cookie becomes a bearer token and no token is a 401
    opt response cache enabled and the request is cacheable
        H->>W: SelfSubjectAccessReview with the user's token
        W-->>H: allowed or denied
        Note over H: denied returns an authorization error, allowed is served from the shared watch cache when it is current
    end
    H->>W: proxy the request with the user's bearer token
    W-->>H: response after OIDC validation and the user's RBAC
    H-->>U: response

Adding a Go source

Implement clusterdiscovery.Source and register it in BuiltinSources. Registration
also exposes enable-, -namespaces, -label-selector,
-root-reconcile-interval, and -no-crd-cache-ttl flags, with
underscores in the source ID replaced by hyphens:

  • Descriptor supplies a stable source ID, display name, primary resource, and
    View with the name-column label, text columns, additional connection-detail
    fields, and compact summary fields.
  • Watches creates unstarted informer factories and caches for a namespace.
  • OwnersForChange maps primary or dependency events to an owner name.
  • Build reads the cache snapshot and returns one GeneratedKubeconfig per
    connection, including its stable key, name, ID, public metadata, and optional
    Presentation display name and string fields.

Each output contains exactly one context and connection information, without
cluster credentials. The engine supplies the configured OIDC user, copies only
supported connection fields, and invokes LoadContextsFromAPIConfig. Sources do
not create proxies or write directly to the context store.

The engine owns informer startup, initial synchronization, shutdown, root
replacement, and connection publication and removal. Adapters can use typed or
dynamic client-go informers. Source-specific metadata is JSON; it must not contain
credentials. The source display name is returned as meta_data.sourceLabel. Its View is
returned in /config.clusterSources; enabled sources remain available as tabs
even when they have no connections. The frontend renders those column definitions
without source-specific components.

What a new source touches

backend/pkg/clusterdiscovery/extensibility_test.go defines a source that exists only
in that file and runs it through the unmodified engine. It checks registration,
the home page view, the OIDC connection, credential removal, update and delete,
rejection of invalid output, and coexistence with the built-in sources.

Layer Change for a new source
Source adapter One new Go file that implements Source
Registration One line in BuiltinSources
Flags, settings and validation None. They are generated from the descriptor for every registered source
Engine: roots, informers, pruning, OIDC, loader, store None
Proxy, user authentication, response cache None. They only see an OIDC kubeconfig context
Home page tabs, columns and details None. They come from Descriptor.View
Translations Optional. Labels missing from labelTranslations in frontend/src/helpers/clusterPresentation.ts are shown untranslated
Helm values and e2e manifests Optional, only to expose the source there

New sources put their public data in GeneratedKubeconfig.Metadata. Cluster Inventory
additionally keeps a typed Context.ClusterInventory field for compatibility.

Cluster names and source views

The home page has an All tab and a tab for each available source. All shows common
status, warning, version, origin, and action columns. Source tabs add their own
fields. Column visibility, sorting, and filters are saved separately for each tab.

Source Display name Source columns
Kubeconfig Custom name or context name Cluster, context namespace, kubeconfig file
Cluster Inventory API ClusterProfile resource name Resource namespace, access provider
Cluster API Cluster resource name Resource namespace, management context

Cluster.name remains the connection key for routes, authentication, saved
appearance, and recent selections. meta_data.presentation.displayName supplies
the human-readable name; an existing custom name takes precedence. The engine
adds the owner's namespace and management context name to presentation.fields; adapters
supply fields such as provider or secret. These fields contain no credentials.
A workload context's default namespace remains separate from the resource namespace.

Cluster selectors show the same display name and source summary. Identical labels
are distinguished by management context, then by connection ID. The Connection
details action shows the raw connection ID and provides a copy button. A source's
detailFields adds fields to this dialog without adding table columns or summary
text. Cluster API shows the kubeconfig Secret reference here. Older
servers without these definitions retain the context names and common columns.

This is a compiled Go extension point. It does not load executables or dynamically
installed Headlamp UI plugins.


Development Cluster Inventory (`docs/development/cluster-inventory.md`)


title: Cluster Inventory development

Cluster Inventory development

Headlamp's experimental Cluster Inventory API integration watches
sigs.k8s.io/cluster-inventory-api v0.1.3 ClusterProfiles and creates in-memory
contexts. It is disabled by default. Enabling it requires Headlamp's global
OIDC configuration, including a client ID, issuer URL, and non-empty scopes.
See the installation configuration.

Discovery runs through the shared source engine,
alongside Cluster API discovery.

Discovery and user access

Operation Connection and credentials
Watch ClusterProfiles in-cluster Pod service account and pod namespace
Watch ClusterProfiles outside a cluster Existing non-internal kubeconfig contexts and their default namespaces
Access a discovered Kubernetes API Connection metadata from ClusterProfile, authenticated with the requesting user's OIDC token

Root credentials are used for discovery only. Each access provider is converted
to an in-memory OIDC kubeconfig and loaded through the same context loader as
file-backed kubeconfigs. Generated users contain login settings, without stored
cluster credentials. Each connection has its own copy of Headlamp's OIDC settings
and source cluster_inventory, and cannot become a discovery root.

Headlamp trusts the connection and TLS settings published in watched
ClusterProfiles; use Kubernetes RBAC to restrict updates to ClusterProfile
status to trusted cluster managers.

Each access-provider entry with valid connection metadata appears separately in
the cluster list. Its context name ends in -<access-provider-name>, so a profile
with providers named direct and fleet-gateway offers two selectable connections.
The Cluster Inventory API tab shows the ClusterProfile name, resource namespace,
and access provider in separate columns. The generated context name is available
in Connection details.

Names and cluster IDs stay stable when providers are reordered or their connection
settings change. Removing a provider removes only its connection; renaming a
provider replaces that connection. There is no automatic failover between them.

For example, this connection has the suffix -fleet-gateway and reaches a gateway
while validating the certificate for kubernetes.internal:

yaml
apiVersion: multicluster.x-k8s.io/v1alpha1
kind: ClusterProfile
metadata:
  name: spoke-a
  namespace: inventory-team-a
spec:
  clusterManager:
    name: fleet-controller
status:
  accessProviders:
    - name: fleet-gateway
      cluster:
        server: https://gateway.example.com/clusters/spoke-a/kubernetes
        tls-server-name: kubernetes.internal

Headlamp copies inline CA data, TLS server name, TLS verification settings,
proxy URL, and compression settings. It ignores local certificate file paths
and exec extensions. The server must use HTTPS without embedded credentials,
query parameters, or a fragment. The CA data must be valid PEM and cannot be
combined with the insecure TLS setting. Invalid TLS settings fail proxy setup.
Invalid connection metadata removes that
provider's existing connection without affecting other valid providers. Removing
a profile or excluding it with the label selector removes all its connections.

Generated kubeconfigs are held in memory. Their names are managed by the profile
and provider names, so Headlamp does not offer renaming for these connections.
File-backed and IndexedDB-backed connections retain their existing name editing.

Configuration

Flag Behavior
--enable-cluster-inventory Enables discovery and requires user OIDC authentication for discovered clusters
--cluster-inventory-namespaces=inventory-team-a,inventory-team-b Watches the listed namespaces instead of each root's default namespace
--cluster-inventory-namespaces='*' Watches all namespaces; cannot be combined with namespace names
--cluster-inventory-label-selector='!headlamp.dev/ignore' Excludes labelled profiles; this is the Helm default
--cluster-inventory-root-reconcile-interval=10s Overrides the five-minute root reconciliation interval
--cluster-inventory-no-crd-cache-ttl=30s Overrides the two-hour cache for roots without the ClusterProfile CRD

Provider files and exec authentication are unsupported. User requests without a
token are rejected before cache access or cluster proxying. The regular OIDC
login and refresh flow is shared with other OIDC contexts, and each discovered
API server must trust the configured issuer and client.

Tests

npm run backend:test covers discovery, namespace and label selection,
connection validation, updates, deletion, and user authentication. The
existing multi-cluster E2E fixture
uses Dex and verifies user-specific RBAC through HTTP and WebSocket requests.


Development Frontend (`docs/development/frontend.md`)


title: Frontend sidebar_position: 2

The frontend is written in Typescript and React, as well as a few other important modules like:

  • Material UI
  • React Router
  • Redux
  • Redux Sagas

Building and running

First, install the required dependencies by running:

bash
npm run frontend:install

The frontend can be quickly built using:

bash
npm run frontend:build

Once built, it can be run in development mode (auto-refresh) using:

bash
npm run frontend:start

This command starts the Rsbuild development server for the frontend
(by default at localhost:3000). To use the Vite fallback, run
npm --prefix frontend run start:vite.

We use react-query
for network requests. If you need the devtools for react-query, you can simply set REACT_APP_ENABLE_REACT_QUERY_DEVTOOLS=true in the .env file.

Packaged products can generate the frontend version, product name, and source
revision from app build inputs. See Custom product builds
for the HEADLAMP_BUILD_MANIFEST and HEADLAMP_SOURCE_COMMIT configuration.

Product error content

Products that build Headlamp can customize the generic error and not-found
pages with these build-time environment variables:

Environment variable Default Description
REACT_APP_HEADLAMP_ERROR_PAGE_TITLE Uh-oh! Something went wrong. Title for the generic error page.
REACT_APP_HEADLAMP_ERROR_PAGE_GRAPHIC Headlamp broken illustration URL or public path of the generic error page graphic.
REACT_APP_HEADLAMP_ERROR_REPORT_GITHUB_URL Headlamp GitHub issue form Full GitHub issue creation URL for crash reports.
REACT_APP_HEADLAMP_ERROR_REPORT_BUTTON_LABEL Open Issue on GitHub Product-owned crash-report button label.
REACT_APP_HEADLAMP_NOT_FOUND_PAGE_TITLE Whoops! This page doesn't exist Title for the not-found page.
REACT_APP_HEADLAMP_NOT_FOUND_PAGE_GRAPHIC Headlamp 404 illustration URL or public path of the not-found page graphic.

Set the variables in frontend/.env or in the environment used to start or
build the frontend. Restart the development server or rebuild the frontend
after changing them. Product-provided titles are not translated by Headlamp;
products are responsible for localizing their text and graphics.

Linting

For local development, run:

bash
npm run frontend:lint

This runs ESLint with the expensive compiler-based react-hooks/* rules turned off so it stays fast.

CI uses a stricter check that re-enables all react-hooks/* rules and treats every warning as an error (--max-warnings 0):

bash
cd frontend && npm run ci-lint

You can run ci-lint locally before pushing to catch any react-hooks violations that CI would flag.

Welcome accessibility checks

The welcome experience has keyboard, narrow-screen reflow, and WCAG A/AA
regression checks. With the frontend running at localhost:3000, run them with:

bash
cd e2e-tests && npx playwright test tests/welcome.spec.ts --project=chromium

Unit test reliability

Sidebar hook tests mock CRD listing and resource availability rather than
contacting a backend. They assert that no fetch requests escape, unmount hook
consumers, and cancel and clear React Query work before restoring mocks. Keep
these boundaries when adding sidebar cases so pending requests cannot log after
the Vitest worker starts shutting down.

For large dropdowns, scope option assertions to the listbox and inspect its
option nodes directly. Role queries compute visibility for every option, which
can exceed the test timeout for thousand-item menus in jsdom under CI load.

API documentation

API documentation for TypeScript is done with typedoc and typedoc-plugin-markdown, and is configured in tsconfig.json.

bash
npm run docs

The API output markdown is generated in docs/development/api/, committed to
Git, and shown on the website at
headlamp/latest/development/api.
When API changes affect the generated output, run npm run docs and include
the resulting docs/development/api/ updates in the same change for review.

Storybook

Components can be discovered, developed, and tested inside the 'storybook'.

From within the Headlamp repo run:

bash
npm run frontend:storybook

If you are adding new stories, please wrap your story components with the TestContext helper
component. This sets up the store, memory router, and other utilities that may be needed for
current or future stories:

jsx
<TestContext>
  <YourComponentTheStoryIsAbout />
</TestContext>

Accessibility (a11y)

Developer console warnings and errors

axe-core is used to detect some a11y issues at runtime when running
Headlamp in developer mode. This detects more issues than testing
components via eslint or via unit tests.

Any issues found are reported in the developer console.

To enable the alert message during development, use the following:

bash
REACT_APP_SKIP_A11Y=false npm run frontend:start

This shows an alert when an a11y issue is detected.

Storybook accessibility testing

Accessibility testing can be performed on all Storybook stories using axe-storybook-testing.
This runs automated accessibility checks against all components in the Storybook.

To run the accessibility tests:

bash
npm run frontend:test:a11y

Or from within the frontend directory:

bash
npm run test:a11y

This command will:

  1. Build the Storybook
  2. Run axe accessibility tests on all stories
  3. Report any accessibility violations found

The tests will fail if any accessibility issues are detected, making it useful for CI/CD pipelines.

Listboxes must expose selectable items as options. Keep decorative dividers
presentation-only so they do not appear as unsupported separator children.
When changing component markup, update the affected Storybook snapshots as well.

Baseline Storybook a11y Configuration

Known failures are tracked in frontend/.axe-storybook-baseline.test-a11y.json. This file is
used by the test suite to allow known failures while catching new violations.

Property testing (fuzzing)

We are using fast-check for property testing.
This is especially useful for parsers, validators, race conditions and such.


Development Gateway (`docs/development/gateway.md`)

Gateway API Development Guide

This guide documents the usage of Gateway API manifests for testing and development. These manifests are configured to work with the Envoy Gateway controller (gateway.envoyproxy.io/gatewayclass-controller), and are useful for validating Gateway API features like HTTP routing, gRPC, backend TLS, traffic policies, and cross-namespace permissions.

Manifest Files

File Description
gatewayclass.yaml Defines the GatewayClass used by Gateway.
gateway.yaml Configures the Gateway resource.
httproute.yaml Configures HTTP route rules.
grpcroute.yaml Configures gRPC route rules.
referencegrant.yaml Grants cross-namespace access.
backendtls.yaml Configures TLS for backends.
backendtraffic.yaml Configures traffic policies to backends.

These files are located in:
frontend/src/components/gateway/manifests/

How to Apply the Manifests

bash
kubectl apply -f frontend/src/components/gateway/manifests/gatewayclass.yaml
kubectl apply -f frontend/src/components/gateway/manifests/gateway.yaml
kubectl apply -f frontend/src/components/gateway/manifests/referencegrant.yaml
kubectl apply -f frontend/src/components/gateway/manifests/httproute.yaml
kubectl apply -f frontend/src/components/gateway/manifests/grpcroute.yaml
kubectl apply -f frontend/src/components/gateway/manifests/backendtls.yaml
kubectl apply -f frontend/src/components/gateway/manifests/backendtraffic.yaml

Alternative: Apply All Manifests at Once

bash
kubectl apply -R -f frontend/src/components/gateway/manifests/

This recursively applies all YAML files in the directory.

Verifying the Setup

After applying the manifests, verify that the Gateway and Routes are accepted and functioning:

bash
kubectl get gateway
kubectl get gatewayclass
kubectl get httproute
kubectl get grpcroute
kubectl describe gateway envoy-gateway
kubectl get backendtlspolicies.gateway.networking.k8s.io
kubectl get xbackendtrafficpolicies.gateway.networking.x-k8s.io

You can also inspect events or logs for the Envoy Gateway controller if routes are not becoming Accepted.

Testing Locally with Minikube

Start a fresh Minikube cluster with a dedicated profile:

bash
minikube start --profile=gateway-checkup

Install the Gateway API CRDs and the Envoy Gateway controller, then apply the manifests as shown above.

Resources


Development Oidc (`docs/development/oidc.md`)


title: Testing OIDC sidebar_position: 4

OIDC (OpenID Connect) is a protocol that allows web applications to authenticate users through an identity provider. It also obtains basic profile information about the user.

Testing OIDC with Kubernetes API Server

This guide will walk you through the process of testing OIDC on a Minikube cluster using an Azure App Registration. OIDC allows you to authenticate and interact with the cluster using kubectl.

Create an Application on Azure

  • Create an application on Azure and specify the redirect URL as http://localhost:8000.
  • Generate a secret for the application under "Certificates and Secrets" and make note of its value.

Start Minikube

  • Start Minikube without enabling OIDC: minikube start. This is done to avoid RBAC (Role-Based Access Control) issues during startup. But, we can enable OIDC once the cluster is running.

SSH into Minikube

  • Once the Minikube cluster is started, SSH into it: minikube ssh.
  • Install the Vim text editor: sudo apt-get update && sudo apt-get install vim.

Edit the kube-apiserver Configuration

  • Edit the kube-apiserver configuration file using Vim: sudo vi /etc/kubernetes/manifests/kube-apiserver.yaml.
  • Add the following lines to the configuration file:
bash
- --oidc-issuer-url=https://sts.windows.net/<tenantID from application>/
    - --oidc-client-id=<Application Client ID>
    - --oidc-username-claim=email
  • Save the changes to the configuration file and exit Vim.

Wait for API Server Restart

  • Wait for approximately 1 minute for the API server to restart and apply the new configuration.

Install kubelogin

  • Install kubelogin, which is a tool for testing Kubernetes authentication:
bash
# Here's how to do it with Homebrew as an example:
brew install int128/kubelogin/kubelogin

Create a Kubernetes User

  • Create a Kubernetes user using the following command:
bash
kubectl config set-credentials oidc-user \
--exec-api-version=client.authentication.k8s.io/v1beta1 \
--exec-command=kubectl \
--exec-arg=oidc-login \
--exec-arg=get-token \
--exec-arg=--oidc-issuer-url=https://sts.windows.net/<tenantID from application>/ \
--exec-arg=--oidc-client-id=<Application Client ID> \
--exec-arg=--oidc-client-secret=<Secret that you created in step 1> \
--exec-arg=--oidc-extra-scope="email offline_access profile openid"

Set the Context for the OIDC User

  • Set the context of the OIDC user as the default context using the following command:
bash
kubectl config set-context --current --user=oidc-user

Test Access to Pods

  • Now you can test access to pods using the OIDC user. Try running the following command to get a list of pods:
bash
kubectl get po -A

By following these steps, you can test OIDC with the Kubernetes API Server and authenticate using the OIDC user you created. Refer to this doc to access Headlamp using OIDC.

Using self-signed CA certificates for OIDC

When working with OIDC providers that use self-signed certificates or custom Certificate Authorities (CAs), Headlamp provides several options to handle TLS verification issues.

Command Line Options

Skip TLS Verification

To skip TLS verification entirely (not recommended for production):

bash
headlamp --oidc-skip-tls-verify

Warning: This option disables TLS certificate validation and is not safe for production environments.

Custom CA Certificate

To specify a custom CA certificate file:

bash
headlamp --oidc-ca-file=/path/to/ca-certificate.pem

The CA file must be a valid PEM-encoded certificate file.

Kubeconfig Configuration

You can also configure OIDC with custom CA certificates directly in your kubeconfig file.

Using CA Certificate File Path

Add the idp-certificate-authority field to your OIDC auth provider configuration:

yaml
apiVersion: v1
kind: Config
users:
- name: oidc-user
  user:
    auth-provider:
      name: oidc
      config:
        client-id: "your-client-id"
        client-secret: "your-client-secret"
        idp-issuer-url: "https://your-oidc-provider.com"
        scope: "profile,email"
        idp-certificate-authority: "/path/to/ca-certificate.pem"

Using Base64-encoded CA Certificate Data

Alternatively, you can embed the CA certificate directly in the kubeconfig using base64-encoded data:

yaml
apiVersion: v1
kind: Config
users:
- name: oidc-user
  user:
    auth-provider:
      name: oidc
      config:
        client-id: "your-client-id"
        client-secret: "your-client-secret"
        idp-issuer-url: "https://your-oidc-provider.com"
        scope: "profile,email"
        idp-certificate-authority-data: "LS0tLS1CRUdJTiBD...=="

Security Considerations

  1. Skip TLS Verification: Only use --oidc-skip-tls-verify in development or testing environments. This option disables all TLS certificate validation and makes your connection vulnerable to man-in-the-middle attacks.

  2. Custom CA Certificates: When using self-signed certificates, ensure that:

    • The CA certificate is valid and not expired
    • The certificate is properly formatted (PEM encoding)
    • The certificate is stored securely and has appropriate file permissions
  3. Production Use: For production environments, consider:

    • Using certificates from a trusted Certificate Authority
    • Implementing proper certificate rotation procedures
    • Monitoring certificate expiration dates

Development Release Guide (`docs/development/release-guide.md`)


title: Release Guide sidebar_position: 6

This document describes how to perform a Headlamp release.

The idea is that we list the steps here as a guide and automate it along the way, so the number of steps is reduced as much as possible in the future.

Version bumping

We follow the semantic versioning guide.

Steps to perform a Headlamp release

When ready to perform a release (changes worth releasing since last time is done, QA is done), then:

1. Create a new branch

Create a new branch called "rc-X.Y.Z" where X.Y.Z is the new release version.

2. Bump the app “version”

If using the automated Headlamp Releaser tool (recommended), run the start command to automate version bumping, dependency installations, Helm template regeneration, and committing:

shell
# Navigate to the releaser directory, install deps, build/link it, and start the release
cd tools/releaser
npm install
npm run build && npm link
releaser start X.Y.Z

This will automatically commit the changes with the message:
releaser: bump version to X.Y.Z

If performing the version bump manually instead:
On the release branch, bump the “version” field in app/package.json, run npm install inside app/ (and update Helm Chart version/templates if applicable), then stage and commit the changes with:

shell
git add app/package.json app/package-lock.json charts/headlamp/Chart.yaml charts/headlamp/tests/expected_templates
git commit --signoff -m "releaser: bump version to X.Y.Z"

Bug fix: make a branch off the tag, and cherry pick everything in. Or make a branch off main and remove merge commits compared to previous tag (On the branch to remove merge commits, do: "git rebase main").

shell
git log v0.25.0.. --oneline

3. Start a release draft

Start a release draft by manually running the "Create release draft" action (it's important to give it the right release name as it creates links with that number in the draft):

4. Check the list of changes since the last release

Check the list of changes since the last release:

text
git log \`git describe \--abbrev=0\`..

Then go to the release draft created in the previous step and fill it accordingly.

Look at previous releases. Write for humans: no context part, like "frontend:". Put github user name in "(thanks @XXX )" at end of line for external contributors.

5. App signing

The build scripts handle app signing.

6. Generate Apps

Generate the apps for each the Linux, Windows, and Mac platforms by running the "Build and upload PLATFORM artifact" actions against the "rc-X.Y.Z".
Use releaser ci app --build rc-X.Y.Z, or select rc-X.Y.Z both under Use
workflow from
and as the build branch. The workflows only generate the build
provenance for the apps when they run from the branch they build, and the
assets can't be uploaded to the release without it (see step 8).

7. Download and test Artifacts

Download the artifacts, test them and, if everything goes well, upload them to the new release's assets area.

8. Push Assets

Upload the assets to the release by running the Upload Release Assets
workflow (.github/workflows/push-release-assets.yml) from the GitHub Actions
UI. Run it from the main branch, not the release branch: users verify the
signature against the workflow on main, so the workflow refuses to run from
any other branch. Give it the release name (e.g. 0.42.0) and the comma-separated run IDs of
the "Build and upload PLATFORM artifact" workflows from step 6. You can list
those runs with releaser ci app --list.

The workflow uploads the assets, updates checksums.txt, and signs it with
cosign keyless signing. It uploads the signature as checksums.txt.sigstore.json.
It also combines the build provenance from the app build runs into
headlamp-X.Y.Z.intoto.jsonl and uploads it. Uploads to the same release are
serialized so partial uploads preserve each other's provenance. Before uploading,
the workflow checks retained assets against their actual bytes and fails if any
are missing from checksums.txt or have a different digest. To repair an
incomplete manifest after a failed upload, rerun with the build run IDs for all
affected assets so they are replaced and their checksums restored.
Release API or retained-asset download failures stop the workflow before uploading.
The workflow also fails if an asset in checksums.txt has no verified build
provenance, or if the signature or provenance is not attached to the release. Users rely on these to
verify downloads (see Verifying Releases),
so always use the workflow, and make sure it succeeded before publishing the
release. releaser check X.Y.Z also reports a missing signature or provenance
(see step 9).

Do not upload assets manually with app/scripts/push-release-assets/push-release-assets.js,
because that skips signing. If you need to add or replace an asset, re-run the
workflow with the run ID of the build that produced it (set force if the
release is no longer a draft), so that checksums.txt is signed again.

The workflow uses GitHub's short-lived automatic token with contents: write
permission to update the release. It does not require a long-lived personal
access token or repository secret. A branch run can test a real upload to the
requested draft release by enabling Allow non-main; force uploads remain
blocked outside main. Always rerun the workflow from main before publishing
so checksums.txt receives the trusted Sigstore identity.

9. Push the new tag

Go to the main branch and merge the rc-X.Y.Z in, then create a signed tag
(notice the v before the version number). Use releaser tag, which signs
the tag by default, or:

shell
git tag -s vX.Y.Z -m "Release X.Y.Z"

Make sure your GPG or SSH signing key is
added to your GitHub account
as a signing key, so that the tag shows as Verified. releaser publish
refuses to push an unsigned tag, and doesn't publish the release if GitHub
reports the pushed tag's signature as invalid. It only warns if GitHub can't
match the signing key to your GitHub account. You can also check the tag
yourself: look for the Verified label on the
tags page, or run
git tag -v vX.Y.Z (see Verifying Releases).

:::warning
Push the signed tag before publishing the release draft, either with
releaser publish or with the commands below. If the draft is published while
the tag doesn't exist yet, GitHub creates an unsigned, lightweight tag from the
latest commit on main. That commit may not be the release commit (this
happened with v0.44.0).
:::

Push the new release commit and tags:

Note: DO NOT RUN THIS BELOW EXCEPT ON NEW FEATURE RELEASES.

shell
git checkout main

git merge rc-X.Y.X \# (this should NOT create a merge commit since the bump commit is the only difference)

git push origin main

git push \--tags

Then publish the release with releaser publish X.Y.Z, which checks that the
tag is signed, attaches it to the draft, and publishes the draft. If you publish
the draft from the GitHub UI instead, select the existing vX.Y.Z tag.

However you uploaded the assets, created the tag, or published the release, run
releaser check X.Y.Z before publishing and again afterwards. It fails if the
checksums.txt signature or the provenance is missing, or if the tag is not
signed or its signature is invalid, e.g. because it was made with an expired
key. It warns if GitHub can't match the signing key to the tagger's GitHub
account, or couldn't check the signature at the moment.

10. Container images and distribution channels (flathub, homebrew)

Container images are built automatically on every tag creation, pushed to the GitHub Container Registry (ghcr.io), and signed with cosign.

Other distribution channels like flathub, homebrew, minikube, will be done by automatically opened PRs.

11. Announce on social media

Ask someone in the social team (Joaquim or Chris) to toot/tweet/post about it from the social media accounts.

Releasing `@kinvolk/headlamp-plugin`

When releasing a new version (X.Y.Z) of @kinvolk/headlamp-plugin from plugins/headlamp-plugin:

  1. Bump plugins/headlamp-plugin/package.json and package-lock.json, regenerate plugins/headlamp-plugin/template/package-lock.json with npm run copy-package-lock, and merge the release commit to main.

  2. Switch to an up-to-date main and build the package:

    shell
    git checkout main
    git pull --ff-only
    cd plugins/headlamp-plugin
    npm ci
    npm run build
  3. Create, verify, and push a signed Git tag before publishing to npm or creating a GitHub release (making sure your GPG or SSH signing key is added to your GitHub account):

    shell
    git tag -s headlamp-plugin-X.Y.Z -m "Release headlamp-plugin X.Y.Z"
    git tag -v headlamp-plugin-X.Y.Z
    git push origin refs/tags/headlamp-plugin-X.Y.Z
  4. Publish the package (npm publish) and, if creating a GitHub release, select the existing signed headlamp-plugin-X.Y.Z tag rather than letting the UI create an unsigned lightweight tag.


Development Telemetry (`docs/development/telemetry.md`)


title: Telemetry sidebar_position: 1.5

Headlamp's backend supports OpenTelemetry for distributed tracing and Prometheus-compatible metrics. This lets operators monitor Headlamp health, debug issues, and observe request patterns in production.

Telemetry is backend-only today. Both tracing and metrics are disabled by default.

What is collected

Metrics

When metrics are enabled, Headlamp exposes a Prometheus scrape endpoint at /metrics on the main HTTP port (default 4466).

Metric Description
http.server.request_count Total HTTP requests (by method, path, status code)
http.server.duration HTTP request duration histogram (milliseconds)
http.server.active_requests Currently active HTTP requests
headlamp.cluster_proxy.requests Requests through the cluster proxy
headlamp.plugin.load_count Plugin load operations
headlamp.plugin.delete_count Plugin delete operations
headlamp.errors Application errors by category

Traces

When tracing is enabled, Headlamp exports spans via OTLP (gRPC or HTTP) or to stdout. Instrumented operations include:

  • Plugin list and delete
  • Helm operations
  • Cluster API proxy requests
  • Cluster add, delete, and rename
  • Node drain operations
  • OIDC token refresh (auth middleware)

Configuration

Telemetry can be configured with CLI flags or environment variables. Environment variables use the HEADLAMP_CONFIG_ prefix with underscores; they map to the underlying config keys (matching flag names where applicable).

Flag Environment variable Default Description
--service-name HEADLAMP_CONFIG_SERVICE_NAME headlamp OpenTelemetry service name
--service-version HEADLAMP_CONFIG_SERVICE_VERSION 0.30.0 Service version resource attribute
--tracing-enabled HEADLAMP_CONFIG_TRACING_ENABLED false Enable distributed tracing
--metrics-enabled HEADLAMP_CONFIG_METRICS_ENABLED false Enable metrics and /metrics endpoint
--otlp-endpoint HEADLAMP_CONFIG_OTLP_ENDPOINT localhost:4317 OTLP collector endpoint (host:port)
--use-otlp-http HEADLAMP_CONFIG_USE_OTLP_HTTP false Use OTLP HTTP instead of gRPC
--stdout-trace-enabled HEADLAMP_CONFIG_STDOUT_TRACE_ENABLED false Export traces to stdout
--sampling-rate HEADLAMP_CONFIG_SAMPLING_RATE 1.0 Trace sampling rate (0.0–1.0)

When tracing is enabled, Headlamp exports spans either to stdout (when
--stdout-trace-enabled is true) or via OTLP to the configured
endpoint (--otlp-endpoint / HEADLAMP_CONFIG_OTLP_ENDPOINT, default
localhost:4317). To view traces in Jaeger locally, run make run-jaeger
and send OTLP to localhost:4317 (gRPC). If you set --use-otlp-http=true,
use the HTTP port instead (for example --otlp-endpoint=localhost:4318).

Local development

Enable metrics only

Build the backend, then run with metrics enabled:

bash
npm run backend:build
npm run backend:start:metrics

Or with Make:

bash
make backend && make run-backend-with-metrics

Verify metrics are exposed:

bash
curl http://localhost:4466/metrics

Enable tracing only

Start an OTLP collector first (see Monitoring stack below), then run:

bash
npm run backend:build
npm run backend:start:traces

Or with Make:

bash
make backend && make run-backend-with-traces

Traces are sent to localhost:4317 by default. View the