How-to › Document and support developers

How to run a try-it console without leaking credentials#

Put an allowlist proxy between your reference console and the sandbox, so readers send real requests while the demo key stays on the server and DELETE stays out.

Audience
API producer
Level
intermediate
Topic
Publish reference docs
Verified

Your reference page has a try-it console, and the key that makes it work sits in the page’s JavaScript for anyone to copy. The console’s server is production. An anonymous reader opens the DELETE operation, fills in an id, presses Execute, and the record is gone, signed with your key.

What you get

You will end up with a proxy that adds a read-only demo key to a console’s requests on the server side, and a console that offers only safe operations. This is for you if your reference site sends requests from the reader’s browser.

Short answer

Point the try-it console in your reference docs at a small proxy, not at the API. The proxy holds a read-only demo key and adds it on the server side. It forwards only the listed methods and paths, refuses any path that needs decoding, withholds responses that echo the key as written, and rate limits each client address. Limit the console’s buttons too, with supportedSubmitMethods in Swagger UI.

You will need

Node 22 or later, a sandbox environment for your API, and a demo key the sandbox scopes to read operations. Verified 2026-11-29 against Node 22.23.5, swagger-ui-dist 5.36.0, @scalar/api-reference 1.85.0, @stoplight/elements 9.0.30, and @usebruno/cli 4.4.0, the consoles driven in Chromium through Playwright 1.63.0. The proxy uses Node’s built-ins only.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
A Bruno collectionReaders already hold their own sandbox keys and run requests from a desktop client or CIAn install and a key before the first request, so a casual reader never sends oneYou want a reader to see a response without signing up
Scalar API clientA reference rendered by Scalar, where servers can point every request at your proxyNo option to limit methods, so hideTestRequestButton removes the button from every operationYou need some operations live and others read-only
Stoplight ElementsA web component in a page you already have, with tryItCorsProxy for cross-origin callsNo method option either, so hideTryIt is all or nothing for the pageWrites must stay hidden while reads stay live
Swagger UI try itYou want per-method control in the console itself, through supportedSubmitMethodsA button filter only, since anyone can still send a DELETE with curlReaders should never reach a live endpoint from your page

Swagger UI is the only console of the three with a per-method switch, and it filters buttons, not requests. Scalar and Elements offer one switch for the whole page, so a mixed policy has to live in the proxy. A Bruno collection removes the public endpoint entirely, at the price of a reader who installs a client and brings a key before seeing a single response.

Put an allowlist proxy between the console and the sandbox

The console sends every request to /try on the proxy, because the OpenAPI document’s servers entry names the proxy and not the API. The proxy decides each request from the raw request target. Nothing decodes or normalizes it first.

/** Decide one request from its method and its raw request target. Pure, so it is testable. */
export function decide(method, rawTarget, routes = ROUTES) {
  if (typeof rawTarget !== 'string' || !rawTarget.startsWith(PREFIX + '/')) {
    return { status: 404, reason: 'outside the console prefix' }
  }
  const q = rawTarget.indexOf('?')
  const rawPath = (q === -1 ? rawTarget : rawTarget.slice(0, q)).slice(PREFIX.length)
  const rawQuery = q === -1 ? '' : rawTarget.slice(q + 1)
  if (!SAFE_PATH.test(rawPath)) return { status: 400, reason: 'path needs decoding or resolving' }
  const matches = routes.filter((r) => fits(r.path, rawPath))
  if (matches.length === 0) return { status: 404, reason: 'path not on the allowlist' }
  const route = matches.find((r) => r.method === method)
  if (!route) {
    return { status: 405, reason: `${method} not allowed here`, allow: matches.map((r) => r.method).join(', ') }
  }

SAFE_PATH allows letters, digits, hyphens, and underscores in each segment. A dot, a percent sign, or a backslash fails it, so the proxy never has to agree with the sandbox on what %2e%2e means.1 The path it forwards is the one it checked, appended to the upstream base as a string.

The key goes on after the decision, and the response is read whole before anything is sent back:

    const headers = { authorization: `Bearer ${credential}`, 'accept-encoding': 'identity' }
    for (const h of FORWARD_REQUEST_HEADERS) if (req.headers[h]) headers[h] = req.headers[h]
    const up = request(`${base}${d.upstreamPath}`, { method: d.route.method, headers, agent, timeout: 5000 }, (ur) => {
      const chunks = []
      let size = 0
      ur.on('data', (c) => {
        size += c.length
        if (size > 1_000_000) ur.destroy(new Error('upstream response too large'))
        else chunks.push(c)
      })
      ur.on('error', () => reply(502, { error: 'upstream failed' }))
      ur.on('end', () => {
        const body = Buffer.concat(chunks)
        const type = ur.headers['content-type'] ?? 'application/octet-stream'
        // The key never goes back to the browser as written, even when the API echoes it. A
        // compressed body would hide it from this check, so only an uncompressed one passes.
        const encoding = ur.headers['content-encoding'] ?? 'identity'
        if (encoding !== 'identity' || body.includes(credential) || type.includes(credential)) {
          return reply(502, { error: 'upstream response withheld' })
        }

Only accept is copied from the reader. A pasted Authorization, a cookie, and an X-HTTP-Method-Override header stay behind. The proxy refuses a compressed body because the check cannot read one, and it never follows a redirect or passes on its Location. The check matches the key as written, so an API that returns it in base64 still leaks it. The read-only scope is what limits that leak.

Send what an anonymous reader can send

The demo starts the sandbox stand-in and the proxy, then sends each request as a reader with no key. The targets go out byte for byte, because fetch would resolve .. before the proxy saw it.

node demo.mjs
list pets              GET     200
read one pet           GET     200
delete a pet           DELETE  405  DELETE not allowed here
path off the list      GET     404  path not on the allowlist
dot segments           GET     400  path needs decoding or resolving
encoded dots           GET     400  path needs decoding or resolving
encoded slashes        GET     400  path needs decoding or resolving
backslashes            GET     400  path needs decoding or resolving
absolute-form target   GET     404  outside the console prefix
repeated parameter     GET     400  query parameter limit repeated
endpoint that echoes   GET     502  upstream response withheld
override and own key   GET     200
another origin         GET     403  origin not allowed

requests that reached the sandbox: 4
  methods: GET
  paths: /v1/pets?limit=2 /v1/pets/2 /v1/whoami /v1/pets/1
  carried the demo key: 4
  carried the reader's key or cookie: 0
pets left in the sandbox: 3
responses that contained the demo key: 0

Four requests reached the sandbox, all GET, all signed with the demo key and none with the reader’s. The absolute-form row matters because HTTP/1.1 servers must accept that form.2

Restrict the console as well

The proxy is the control, and the console’s own option is the courtesy that stops readers pressing a button that can only fail. record.sh served one document through each console from 127.0.0.1 and counted the send buttons in a fresh Chromium context:

node show-records.mjs consoles
swagger-ui default: try-it buttons on GET 1, on DELETE 1
swagger-ui supportedSubmitMethods: ['get']: try-it buttons on GET 1, on DELETE 0
incognito GET /v1/pets/2 through swagger-ui: status 200, body {"id":"2","name":"Tibbles"}
  requests the browser sent the proxy: 1, with authorization: false, with cookie: false
  proxy events: GET /v1/pets/2 200
  demo key anywhere in the page, its storage or its cookies: false
scalar default: Test Request buttons on the page 3 (three operations)
scalar hideTestRequestButton: true: Test Request buttons on the page 0 (three operations)
elements default: Send API Request buttons on DELETE 1
elements hideTryIt: Send API Request buttons on DELETE 0

The Swagger UI configuration page describes supportedSubmitMethods as the list of methods with “Try it out” enabled. Scalar’s configuration reference, and the option schema in @scalar/types 0.33.0 that 1.85.0 installs, hold no option that takes a list of methods. Its onBeforeRequest hook can rewrite a request, but the button stays. Its proxyUrl expects a proxy that speaks the Scalar Proxy API, so override servers instead. The Elements options list names hideTryIt, hideTryItPanel, tryItCorsProxy, and tryItCredentialsPolicy, none of them per method, and the 9.0.30 bundle reads those four.

Check it worked

The incognito run in that record is the check. A browser context with no cookies and no storage got a 200 through Swagger UI, sent no credential, and found no key in the page. The tests pin the rest: a refused DELETE, each bypass shape refused before the sandbox, and the echoed key withheld, plain, compressed, or in a header. A control shows the sandbox does echo it. The rate limit runs on a controlled clock, and an https upstream answers 502 when it fails instead of stopping the process.

node --test proxy.test.mjs
1..15
# tests 15
# suites 0
# pass 15
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 119.06016

Allow dots and percent signs in SAFE_PATH and the first test fails. Add a DELETE route and four fail.

When it goes wrong

A reader deletes data from the console. The console points at production, through a proxy that forwards anything with a full-scope key. Three set-ups get the same anonymous request:

node pitfall.mjs
an anonymous DELETE /v1/pets/2 from the console, three ways
pass-through proxy, full-scope key       204  reached the API: 1  pets left: 2
pass-through proxy, read-only demo key   403  reached the API: 1  pets left: 3
allowlist proxy, read-only demo key      405  reached the API: 0  pets left: 3

The scoped key stops the delete at the API, and the allowlist stops it before the API sees it. Keep both, because each covers a mistake in the other.

The console shows a network error for every request. The page is served from an origin the proxy does not know, such as a preview deployment, so the proxy answers 403. Pass that origin as docsOrigin for the deployment.

A documented operation answers 502 through the proxy. Its response carries the demo key, which the proxy withholds by design. Take that operation off the allowlist, or change the sandbox so it stops echoing keys.

When not to do this

Do not run a live console for an API with no sandbox. A proxy in front of production with a read-only key still serves real customer data to anyone who finds the page.

Do not treat supportedSubmitMethods, hideTestRequestButton, or hideTryIt as security. They change what a page draws. Anyone with curl can still send a DELETE to whatever the document names.

Do not ship the proxy without watching it. It is a public endpoint that spends your sandbox quota, and the in-memory counter here resets on restart and counts per instance. Two instances give each reader twice the limit. Behind a load balancer every reader arrives from the address of the balancer, so one limit covers all of them together.

Skip the console when your readers are integrators who already hold keys. A Bruno collection that reads the key from process.env, which Bruno fills from a .env file in the collection, sends real requests with no public endpoint to operate. The recorded run set it in the shell. Bruno masked the token as Bearer ******** in its JSON report in records/bruno.txt.

Last verified

Verified 2026-11-29 against Node 22.23.5. Every output block is what the command preceding it printed in the page’s code directory. The console records come from record.sh, which drove swagger-ui-dist 5.36.0, @scalar/api-reference 1.85.0, and @stoplight/elements 9.0.30 in Chromium through Playwright 1.63.0 and ran @usebruno/cli 4.4.0 against the sandbox stand-in. No hosted service was called, and no screen reader or real browser profile was used.

Footnotes

  1. The URL Standard counts four spellings of the parent directory: .., then .%2e, %2e., and %2e%2e in either case. The single dot gets two. A parser that follows it resolves all six. A proxy that checks the path before the parser does has to know every one of them, which is why this proxy refuses the percent sign outright. ↩︎ Back to text

  2. RFC 9112 says a server MUST accept the absolute-form in requests, even though most HTTP/1.1 clients send it only to a proxy. Node’s server passes it through as req.url, scheme and host included, so a check that expects a leading slash sees a request for another host. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.