Debugbar

On this page 9

@stacksjs/debugbar draws a bar at the foot of every page in development and records what each request did: its queries, a timeline, log lines, exceptions, events, cache operations, mail and jobs. It is the Stacks counterpart of Laravel Debugbar.

There is nothing to install. Run ./buddy dev, open a page, and the bar is there.

When it runs

EnvironmentDebugbar
local, developmentOn, unless APP_DEBUG=false or enabled: false
Anything else that is not productionOff, unless enabled: true
productionOff. No setting changes this

In production the package registers nothing at all: no middleware, no hooks, no /__debugbar routes, no storage directory and no script tag. That is decided from the environment before any configuration is read.

The bar

The bar shows the response status, the route or template, the total time, the number of queries and how long they took, the server's memory, log and exception counts, and who the request was signed in as. Click any of them to open the panel on the matching tab.

  • Queries. Every statement with its bindings, duration, row count and the application file and line that ran it. Filter by text, show only slow or repeated statements, sort by duration, write the bindings back into the SQL, and copy any statement. Statements repeated exactly are marked as duplicates, and a read repeated five or more times with different values is called out as a possible N+1.
  • Timeline. A waterfall of the request: middleware, the handler or the page render, your own measures and every query.
  • Messages, Logs, Exceptions, Events, Cache, Mail, Jobs. What was said and done during the request. Exceptions show the stack and the source lines around the failing line.
  • Route, Auth, Request, Environment. The matched route and its middleware or the rendered template, who made the request, headers and input with secrets redacted, and the app, runtime and git branch.
  • Requests. The page plus every fetch and XMLHttpRequest it has made. Select one to inspect it. The bar follows stx router navigations on its own.
  • Sign in as. See below.

Drag the top edge of the panel to resize it. Minimise the bar to a small badge. The open tab, the height and the minimised state are remembered. Alt+Shift+D toggles the panel and Escape closes it.

Messages and measures

import { debugbar } from '@stacksjs/debugbar'

debugbar.info('cart recalculated', { items: cart.items.length })
debugbar.warn('falling back to the default rate')
debugbar.error(new Error('carrier timed out'))
debugbar.addMessage('resolved tenant', 'tenancy')

const rates = await debugbar.measure('shipping rates', () => carrier.rates(cart))

debugbar.startMeasure('import')
await importRows()
debugbar.stopMeasure('import')

Each call does nothing outside a request the debugbar is collecting, so you can leave them in code that also runs in production, in a queue worker or in a test.

Custom collectors

A collector adds a section to every request record and a tab to the panel.

import { registerCollector } from '@stacksjs/debugbar'

registerCollector({
  name: 'tenant',
  label: 'Tenant',
  collect: collection => ({
    id: currentTenant()?.id,
    path: collection.url.pathname,
  }),
})
HookCalledFor
install(context)Once per process, only where the debugbar is enabledAttaching listeners. Return a function that detaches them
begin(collection)As each collected request beginsCheap per-request setup
collect(collection, response)When the request finishesReturning the section, which is stored as JSON

Inside a listener, context.current() is the request in flight, and collection.push(name, entry) appends to a list you read back in collect with collection.list(name). What a custom collector returns is stored as given, so pass anything sensitive through redact() first.

Sign in as

The tab lists users and signs the browser in as the one you pick: it issues a token for that user, sets the auth cookie and reloads the page.

By default it offers the first 25 rows of the users table. Offer your own list instead:

// config/debugbar.ts
export default defineDebugbar({
  signInAs: {
    users: async () => (await User.where('is_demo', true).get()).map(user => ({
      id: user.id,
      name: user.name,
      email: user.email,
      badge: user.role,
      description: user.bio,
    })),
    tokenStorageKey: 'auth-token',
  },
})

Only a user the resolver returns can be signed in as. If your client keeps its bearer token in localStorage, set tokenStorageKey and the bar writes the new token there before it reloads. It also dispatches stacks:debugbar:signed-in on window, with { user, token } as the event detail, and stacks:debugbar:signed-out on sign out.

Configuration

// config/debugbar.ts
import type { DebugbarConfig } from '@stacksjs/types'
import { defineDebugbar } from '@stacksjs/config'

export default defineDebugbar({
  // enabled: true,
  allowRemote: false,
  storage: { maxRequests: 200 },
  except: ['/health', '/api/dashboard/*'],
  collectors: { events: false },
  queries: {
    slowThresholdMs: 100,
    nPlusOneThreshold: 5,
    backtrace: true,
    maxQueries: 500,
  },
  shortcut: 'alt+shift+d',
  signInAs: { enabled: true },
}) satisfies DebugbarConfig
OptionDefaultWhat it does
enabledunsetSee "When it runs"
allowRemotefalseAnswer clients that are not on this machine
storage.pathstorage/framework/debugbarWhere request records are written
storage.maxRequests200Records kept before the oldest are pruned
except[]Paths never collected. A trailing * matches a prefix
collectorsall onSwitch a built-in collector off by name
queries.slowThresholdMs100Statements at or above this are marked slow
queries.nPlusOneThreshold5Repeats of one read shape that count as a possible N+1
queries.backtracetrueRecord the file and line that ran each statement
queries.maxQueries500Statements kept per request
shortcutalt+shift+dKeys that toggle the panel. false for none
signInAs.enabledtrueOffer the "Sign in as" tab
signInAs.usersfirst 25 usersThe users to offer
signInAs.tokenStorageKeyunsetA localStorage key to write the issued token to

How it works

Page renders and API calls are served by two processes. Each one collects its own requests and writes a JSON record per request to storage/framework/debugbar/, which ignores itself in git. Every response carries the record's id in an X-Debugbar-Id header and a Server-Timing entry. The views server appends one script tag to each full HTML document and serves the records from /__debugbar/requests/:id, so the bar can show an API call's record even though another process handled it.

The bar is a single script with no dependencies, drawn inside a closed shadow root. It does not style the page and the page cannot style it.

Safety

  • Production. The debugbar does not exist there. See "When it runs".
  • Local clients only. Collection, the injected script and everything under /__debugbar/ are limited to a client on this machine asking for a local hostname (localhost, *.localhost, *.test, a loopback address). A request that arrived through a proxy or a tunnel on behalf of another machine is refused. Set allowRemote: true to test from a phone, knowing that everything the bar shows is then readable from that network.
  • Sign in as. In addition to the above it requires a same-origin request and a secret token that was served with the page, so a page on another site cannot trigger it.
  • Redaction. Authorization, Cookie and Set-Cookie headers, fields named like a password, token, secret or key, and bound values that look like a password hash, a JWT or a long token are replaced with [redacted] before a record is written. Cookies are listed by name only.

Limits

  • Model queries (User.find(1)) are recorded on SQLite. On MySQL and Postgres only query builder statements (db.selectFrom(...)) are recorded, and model statements inside a transaction are not recorded on any driver.
  • The template shown for a page is resolved from its URL by the file-routing convention, so a dynamic route names no template.
  • A page compressed before it reaches the views server's response hook is recorded but gets no bar.
  • An app with a strict Content Security Policy needs to allow scripts from its own origin for the bar to load.

Released under the MIT License.