On this page

The HTTP QUERY Method

Every API that has a search endpoint eventually faces the same choice. Put a complex filter in the query string of a GET and fight URL length limits, encoding bugs and access logs full of sensitive data. Or switch to POST /search and lose everything HTTP knows about reads: safety, idempotency, automatic retries and caching.

QUERY is the third option. It is a request method that carries a body like POST but is defined as safe and idempotent like GET, and its responses can be cached. It was standardized as RFC 10008, "The HTTP QUERY Method" (Proposed Standard, June 2026, by J. Reschke, J. M. Snell and M. Bishop). Before that it was the IETF httpbis draft draft-ietf-httpbis-safe-method-w-body, which itself replaced the older draft-snell-search-method (Datatracker).

QUERY /contacts HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json

{ "where": { "city": "Pune", "tags": { "any": ["vip", "beta"] } }, "limit": 50 }
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=60
Accept-Query: application/json, "application/sql"

{ "items": [ ... ], "next": "..." }

Status as of 2026-11-07

QUERY is a published RFC (RFC 10008) and is registered in the IANA HTTP Method Registry as safe and idempotent. The standard is done. Support across the network path (proxies, CDNs, WAFs, browsers, frameworks) is still patchy, and the Ecosystem Support section below spells out what has been verified. Plan for a fallback.


Why QUERY Exists

Problem 1: GET has no defined body semantics

RFC 9110 §9.3.1 says content in a GET request "has no generally defined semantics" and may lead some implementations to reject the request. In practice:

  • Some proxies and load balancers strip the body of a GET.
  • Some reject the request outright.
  • Caches ignore the body completely when building a cache key, so two GETs with different bodies get the same cached response. That is a correctness bug, not just a performance one.
  • Browser fetch() throws a TypeError if you pass a body with GET.

Elasticsearch's GET /_search with a JSON body is the famous example. It works only because Elasticsearch also accepts POST for the same endpoint, and most clients quietly use the POST form.

Problem 2: Query strings don't scale

Moving the filter into the URL works until it doesn't.

ConstraintTypical limitWhat happens
Browser URL lengthVaries by browserVery long URLs get truncated or rejected
Server request-line limitsnginx large_client_header_buffers defaults to 8 KB per line; many servers sit around 8 KB414 URI Too Long
CDN / load balancer limitsUsually 8–16 KB of headers and URL combined414 or 400 returned by the edge before your app sees it
EncodingEverything must be percent-encodedNested structures need ad hoc conventions (filter[tags][]=a)
TypesStrings only?active=false arrives as the string "false"

A real-world search (a few dozen IDs, a geo polygon, a full-text clause) can easily cross 8 KB.

Problem 3: URLs leak

Query strings are written to access logs, proxy logs, browser history, Referer headers and analytics tools. A filter like ?email=alice@example.com&diagnosis=... ends up in places your data-retention policy never covered. RFC 10008's security considerations call this out directly: carrying the query in the body reduces exposure through URI logging.

Problem 4: POST throws away HTTP's read semantics

POST /search fixes the size and logging problems, but it tells every intermediary "this may change state":

  • Clients, SDKs and proxies won't automatically retry a POST after a connection reset.
  • Shared caches won't reuse a POST response for a later POST.
  • Prefetching, link checkers and crawlers correctly stay away.
  • Your API documentation has to say "this POST is actually a read", and every new engineer has to learn the exception.

QUERY keeps POST's body and gets back GET's guarantees.


First Principles: Safe, Idempotent, Cacheable

These three properties are different, and QUERY is the first method to combine all three with a request body.

  • Safe: the client doesn't request, and doesn't expect, any state change. The server can still log, count or create auxiliary resources, but the client isn't responsible for those side effects. Safe implies idempotent.
  • Idempotent: sending the same request N times has the same intended effect as sending it once. This is what makes automatic retries legal.
  • Cacheable: a cache may store the response and reuse it for a later equivalent request.
MethodSafeIdempotentCacheableRequest bodyTypical use
GETYesYesYesNo defined semanticsFetch a resource by URI
HEADYesYesYesNo defined semanticsFetch headers only
QUERYYesYesYes (body in cache key)Yes, requiredAsk the target to evaluate a query in the body
POSTNoNoOnly with explicit freshness, and rarely usedYesCreate or process
PUTNoYesNoYesReplace a resource
PATCHNoNot by defaultNoYesPartial update
DELETENoYesNoNo defined semanticsRemove a resource

See Idempotency & Safe Retries for how idempotency is used in retry logic.

What QUERY means

A QUERY asks the target resource to process the enclosed content safely and idempotently and return the result. The target URI (including its own query string, if any) identifies what is queried. The body says how to query it. The Content-Type says which query language the body uses.

That last point matters. QUERY doesn't define a query language. application/json with your own filter schema, application/sql, application/jsonpath, GraphQL or application/x-www-form-urlencoded are all legitimate. Content negotiation decides which ones the server accepts.


Core Mechanics

Basic request and response flow

sequenceDiagram
    participant C as Client
    participant S as Server (/contacts)
    C->>S: QUERY /contacts<br/>Content-Type: application/json<br/>{ "where": ... }
    alt Content-Type missing
        S-->>C: 400 Bad Request
    else Media type not supported for QUERY here
        S-->>C: 415 Unsupported Media Type<br/>Accept-Query: application/json
    else Body doesn't match declared type
        S-->>C: 400 Bad Request (no content sniffing)
    else Valid syntax, can't be processed (unknown field)
        S-->>C: 422 Unprocessable Content
    else Accept can't be satisfied
        S-->>C: 406 Not Acceptable
    else OK
        S-->>C: 200 OK<br/>Cache-Control: max-age=60<br/>results
    end

The status codes come straight from RFC 10008:

SituationStatus
No Content-Type4xx, for example 400
Media type unknown, or known but meaningless as a query for this resource415, ideally with Accept-Query
Content-Type doesn't match the body400 (the server MUST NOT sniff)
Syntactically valid query that can't be processed, such as SQL naming a table that doesn't exist422
No acceptable response format406

Discovering support: Accept-Query

Accept-Query is a response header. It tells clients that the resource supports QUERY and which query media types it accepts. It is a Structured Field List of tokens or strings, with optional parameters:

Accept-Query: "application/jsonpath", application/sql;charset="UTF-8"

Rules worth remembering:

  • Token vs string carries no meaning. Recipients MUST NOT treat application/json and "application/json" differently.
  • Only */* and type/* wildcards are allowed. Order is not significant.
  • It applies to the resource path and ignores the query component of the URI.
  • Send it on OPTIONS, on GET responses for the same path, and on 415 errors. A client can then probe once and cache the answer.
sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: OPTIONS /contacts
    S-->>C: 204 No Content<br/>Allow: GET, QUERY, OPTIONS<br/>Accept-Query: application/json, "application/sql"
    Note over C: Client picks application/sql
    C->>S: QUERY /contacts<br/>Content-Type: application/sql<br/>SELECT name WHERE city = 'Pune'
    S-->>C: 200 OK

Content negotiation in both directions

QUERY negotiates on two axes at once:

  • Request side: the client picks a query language from Accept-Query and declares it with Content-Type.
  • Response side: normal Accept negotiation picks the result format (JSON, CSV, NDJSON).

A cache has to account for both. The response to SELECT ... as CSV is not the same as the response to the same query as JSON, so Accept is part of the cache key through Vary, and Content-Type is part of it as "related metadata" alongside the body.

Caching: the body is part of the cache key

This is the big win over POST and the big trap for implementers. RFC 10008 says QUERY responses are cacheable for later QUERY requests, and the cache key MUST include the request content and related metadata. Caches MAY normalize away insignificant differences (content encoding, formatting implied by a +json suffix, media-type-specific semantics) when building the key. Normalization affects only the key. The request forwarded upstream is unchanged.

flowchart LR
    R[QUERY request] --> M{Method is QUERY?}
    M -- no --> G[Normal GET-style key<br/>method + URI + Vary]
    M -- yes --> D[Decode Content-Encoding]
    D --> N[Normalize body by media type<br/>e.g. canonical JSON]
    N --> H[SHA-256 of<br/>Content-Type + normalized body]
    H --> K[Key = QUERY + URI + body hash + Vary headers]
    K --> L{Hit and fresh?}
    L -- yes --> HIT[Serve from cache]
    L -- no --> UP[Forward original, un-normalized request upstream]
    UP --> S[Store if Cache-Control allows]

Two requests that differ only in JSON whitespace or key order can share an entry if the cache understands JSON. Two requests that differ in a single filter value must never share one. Getting this wrong is the false-positive cache match that RFC 10008's security section warns about.

Turning a query into a GET-able URL: Location and Content-Location

A QUERY response can hand the client a URI so later reads can use plain GET. The RFC gives the two headers distinct meanings:

HeaderPoints toA GET on it...Lifetime
Content-LocationThe result of this particular queryReturns the same result set that was just computed (a snapshot)May be temporary
LocationAn equivalent resource for the query itselfRe-runs the query without resending the bodyServer-defined. If it fails later, the client falls back to the original QUERY
sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: QUERY /contacts<br/>{ "where": { "city": "Pune" } }
    S-->>C: 200 OK<br/>Location: /contacts/queries/q_7f3a<br/>Content-Location: /contacts/results/r_91bc<br/>results
    Note over C: Share or bookmark the query
    C->>S: GET /contacts/queries/q_7f3a
    S-->>C: 200 OK (query re-executed, fresh data)
    Note over C: Page through the exact snapshot
    C->>S: GET /contacts/results/r_91bc?page=2
    S-->>C: 200 OK (same snapshot)
    Note over C,S: Later, after the stored query expires
    C->>S: GET /contacts/queries/q_7f3a
    S-->>C: 404 Not Found
    C->>S: QUERY /contacts (resend original body)

This is how QUERY gets back things people like about GET: shareable links, <a href> navigation, and caching by any GET-only cache on the path.

Don't mint URIs that embed the query

RFC 10008 tells servers to keep sensitive parts of the request body out of any URI they create. Location: /contacts/queries/q_7f3a (opaque ID) is fine. Location: /contacts?email=alice@example.com undoes the privacy benefit you moved to QUERY for.

Redirects

Redirect handling differs from POST, and it is the part HTTP client libraries most often get wrong:

StatusClient behavior for QUERY
301, 308 (permanent)Resend QUERY with the same body to the new URI. The historical "POST becomes GET" rewrite does not apply
302, 307 (temporary)Resend QUERY with the same body
303 See OtherGET the Location URI, which is how a server says "the result lives over there"

Go is an example: golang/go#80488 tracks special-casing QUERY so 301/302 keep the method and body. Check your client library before you rely on it.

Conditional requests

The selected representation of a QUERY is the same as a GET on the equivalent resource, so ETag, If-None-Match and 304 Not Modified work as defined in RFC 9110 §13. Range requests are technically allowed but rarely useful. Use the query language's own paging instead.


Ecosystem Support (as of writing)

Only items verified against a primary or first-hand source are listed. Items marked "tracker" come from a community adoption tracker (last revised 2026-11-06) and not from the project itself.

ComponentStatusSource
StandardRFC 10008, Proposed Standard, June 2026rfc-editor.org
Node.js httpParser support via llhttp 9.2.0 (nodejs/node#51719). Confirmed working on Node 22.2.0. Didn't work on Node 21.7.3expressjs/express#5615
ExpressWorks on QUERY-capable Node. Maintainers said "22 and up have stable support"expressjs/express#5615
Fastify v5QUERY is a built-in method (with GET, POST, etc.); no addHttpMethod neededFastify Server docs
Go net/httpArbitrary methods already work (http.NewRequest("QUERY", ...), mux.HandleFunc("QUERY /data", ...) since Go 1.22). The http.MethodQuery constant is accepted and on master for the next releasegolang/go#80058, kmcd.dev
curlcurl -X QUERY -H 'Content-Type: application/json' --data '...' works (curl doesn't restrict -X). Set Content-Type yourself, because --data defaults to form encodingkmcd.dev
.NET 10Built-in support reported on client and server; .NET 11 previews add OpenAPI recognitionSANS ISC, startdebugging.net
OpenAPI 3.2query is a fixed operation field on the Path Item Object (spec released 2025-09-23). Tooling lags: some parsers silently drop query operationsOpenAPI 3.2 spec, readmeio/oas#1234
nginxProxies QUERY but never caches it. limit_except rejects it. Core support PR is openSANS ISC, tracker (nginx/nginx#1488)
Caddy, TraefikPass it through untouchedSANS ISC
Apache httpdNeeds configuration changesSANS ISC
EnvoyTracker lists support as merged (envoyproxy/envoy#46496)tracker
CDNs (Cloudflare, Akamai)Both employ RFC authors, but "reliable at-scale QUERY caching isn't there yet". Cloudflare body-keyed caching is tracked in cloudflare/workerd#6849SANS ISC, tracker
Browsers (fetch/XHR)Can send QUERY. Not CORS-safelisted, so cross-origin requests are preflighted. Don't expect the browser HTTP cache to store responses. <form method="query"> is not a thing yet (whatwg/html#12594). Fetch-spec work is tracked in whatwg/fetch#1938SANS ISC, tracker
WAFsNo vendor-specific data found. As of writing, support is unclear. Test your own WAF (see below)SANS ISC

Practical reading of this table

QUERY is production-ready for server-to-server traffic you control end to end (your service mesh, your SDK, your backend). For browser-facing or third-party-proxied traffic it is early: it works, but expect preflights, no browser caching and no CDN caching by default.


Implementation

The examples below use TypeScript on Node 22+. Assert support at startup instead of finding out from a 400 in production:

// startup-check.ts
import http from 'node:http';

if (!http.METHODS.includes('QUERY')) {
  throw new Error(
    `Node ${process.version} does not parse the QUERY method. Use Node 22.2.0 or later.`,
  );
}

Server: Fastify handling QUERY

Fastify v5 knows QUERY natively. The handler below validates the media type, maps errors to the RFC's status codes, advertises Accept-Query, sets cache headers, and mints an opaque Location for the query.

// server.ts
import Fastify, { type FastifyReply, type FastifyRequest } from 'fastify';
import { createHash, randomUUID } from 'node:crypto';
import { z } from 'zod';

const ACCEPT_QUERY = 'application/json';
const MAX_QUERY_BYTES = 64 * 1024; // queries are small, so don't let QUERY become an upload endpoint

const app = Fastify({ bodyLimit: MAX_QUERY_BYTES, logger: true });

// The query language for /contacts: a tiny JSON filter schema.
const ContactQuery = z
  .object({
    where: z
      .object({
        city: z.string().max(100).optional(),
        tags: z.object({ any: z.array(z.string()).max(50) }).optional(),
        createdAfter: z.string().datetime().optional(),
      })
      .strict(),
    fields: z.array(z.enum(['id', 'name', 'email', 'city', 'tags'])).optional(),
    limit: z.number().int().min(1).max(500).default(50),
    cursor: z.string().optional(),
  })
  .strict();

type ContactQuery = z.infer<typeof ContactQuery>;

// Stored queries back the Location header. Use Redis or a DB table in production.
// Simplification: in-memory Map, lost on restart and not shared across instances; move to Redis with TTL for multi-instance.
const storedQueries = new Map<string, { query: ContactQuery; expiresAt: number }>();
const STORED_QUERY_TTL_MS = 15 * 60 * 1000;

function mediaType(req: FastifyRequest): string | undefined {
  return req.headers['content-type']?.split(';')[0]?.trim().toLowerCase();
}

function sendProblem(reply: FastifyReply, status: number, title: string, detail?: string) {
  return reply
    .code(status)
    .header('Accept-Query', ACCEPT_QUERY)
    .type('application/problem+json')
    .send({ type: 'about:blank', title, status, detail });
}

async function runContactQuery(q: ContactQuery) {
  // Translate the validated filter into a parameterized DB query. Never string-concatenate.
  return { items: [] as unknown[], next: null as string | null, query: q };
}

// Advertise support on OPTIONS and GET so clients can discover it.
app.options('/contacts', async (_req, reply) => {
  reply
    .code(204)
    .header('Allow', 'GET, QUERY, OPTIONS')
    .header('Accept-Query', ACCEPT_QUERY)
    .send();
});

app.get('/contacts', async (_req, reply) => {
  reply.header('Accept-Query', ACCEPT_QUERY);
  return runContactQuery({ where: {}, limit: 50 });
});

app.route({
  method: 'QUERY',
  url: '/contacts',
  handler: async (req, reply) => {
    const type = mediaType(req);
    if (!type) return sendProblem(reply, 400, 'Content-Type is required for QUERY');
    if (type !== 'application/json') {
      return sendProblem(reply, 415, 'Unsupported query media type', `Got ${type}`);
    }

    const parsed = ContactQuery.safeParse(req.body);
    if (!parsed.success) {
      // Valid JSON (Fastify already parsed it), but not a query we can run.
      return sendProblem(reply, 422, 'Query cannot be processed', parsed.error.message);
    }

    const result = await runContactQuery(parsed.data);

    // Opaque ID: keeps the filter out of URLs, logs and Referer headers.
    const id = randomUUID();
    storedQueries.set(id, { query: parsed.data, expiresAt: Date.now() + STORED_QUERY_TTL_MS });

    // Strong validator over the result lets clients revalidate with If-None-Match.
    const body = JSON.stringify(result);
    const etag = `"${createHash('sha256').update(body).digest('base64url').slice(0, 27)}"`;
    if (req.headers['if-none-match'] === etag) return reply.code(304).send();

    return reply
      .header('Accept-Query', ACCEPT_QUERY)
      .header('Location', `/contacts/queries/${id}`)
      .header('Cache-Control', 'private, max-age=30') // per-user data: never let shared caches store it
      .header('Vary', 'Accept, Authorization')
      .header('ETag', etag)
      .type('application/json')
      .send(body);
  },
});

// GET on the equivalent resource re-runs the stored query.
app.get<{ Params: { id: string } }>('/contacts/queries/:id', async (req, reply) => {
  const entry = storedQueries.get(req.params.id);
  if (!entry || entry.expiresAt < Date.now()) {
    storedQueries.delete(req.params.id);
    return sendProblem(reply, 404, 'Stored query expired', 'Resend the original QUERY');
  }
  reply.header('Cache-Control', 'private, max-age=30');
  return runContactQuery(entry.query);
});

await app.listen({ port: 3000, host: '0.0.0.0' });

Notes on the choices above:

  • bodyLimit is set low on purpose. A query body should be kilobytes. A 10 MB "query" is either a bug or an attack, and because QUERY is safe and retryable, a client or proxy may resend that 10 MB several times.
  • .strict() schemas reject unknown fields with 422 instead of silently ignoring them. A typo like "citty" that is ignored returns all contacts, which is a data leak dressed up as a successful query.
  • private cache directive: the response depends on who is asking. Use public, max-age=... only for responses that are truly the same for every caller, such as a product catalog search.
  • Authorization must run before the query executes, exactly as for GET. "Safe" means no state change. It doesn't mean "no authorization needed".

Client: fetch with discovery and fallback

Node 22's global fetch (undici) and browsers can both send QUERY. The client below:

  1. Uses QUERY by default.
  2. Falls back to POST with an override header when the path rejects the method (405, 501, or a 400 from an intermediary).
  3. Remembers the fallback per origin so it doesn't pay for a failed attempt on every request.
  4. Retries network errors only for QUERY, because QUERY is idempotent and POST is not.
// query-client.ts
type QueryOptions = {
  contentType?: string;
  accept?: string;
  signal?: AbortSignal;
  retries?: number;
};

// Origins where we've learned QUERY doesn't make it through.
const fallbackOrigins = new Set<string>();

const METHOD_REJECTED = new Set([405, 501]);

export async function httpQuery<T>(
  url: string,
  body: unknown,
  { contentType = 'application/json', accept = 'application/json', signal, retries = 2 }: QueryOptions = {},
): Promise<T> {
  const origin = new URL(url).origin;
  const payload = contentType.includes('json') ? JSON.stringify(body) : String(body);

  const send = (method: 'QUERY' | 'POST') =>
    fetch(url, {
      // Must be uppercase. Fetch only normalizes the case of DELETE/GET/HEAD/OPTIONS/POST/PUT,
      // so 'query' would go on the wire as lowercase and most servers would reject it.
      method,
      headers: {
        'Content-Type': contentType,
        Accept: accept,
        ...(method === 'POST' ? { 'X-HTTP-Method-Override': 'QUERY' } : {}),
      },
      body: payload,
      signal,
    });

  if (!fallbackOrigins.has(origin)) {
    for (let attempt = 0; ; attempt++) {
      let res: Response;
      try {
        res = await send('QUERY');
      } catch (err) {
        // QUERY is idempotent, so retrying after a network failure is allowed.
        if (attempt >= retries || signal?.aborted) throw err;
        await new Promise((r) => setTimeout(r, 2 ** attempt * 200));
        continue;
      }

      const looksRejectedByPath =
        METHOD_REJECTED.has(res.status) ||
        // A 400 without Accept-Query probably came from a proxy that didn't understand
        // the method, not from the origin rejecting our query.
        (res.status === 400 && !res.headers.has('accept-query'));

      if (!looksRejectedByPath) return parse<T>(res);
      fallbackOrigins.add(origin);
      break;
    }
  }

  // Fallback: POST is NOT idempotent from the network's point of view, so never auto-retry it.
  return parse<T>(await send('POST'));
}

async function parse<T>(res: Response): Promise<T> {
  if (!res.ok) {
    const detail = await res.text().catch(() => '');
    throw new Error(`QUERY failed: ${res.status} ${res.statusText} ${detail}`.trim());
  }
  return (await res.json()) as T;
}
// usage
const contacts = await httpQuery<{ items: Contact[] }>('https://api.example.com/contacts', {
  where: { city: 'Pune', tags: { any: ['vip'] } },
  limit: 50,
});

The 400 heuristic is a heuristic

A 400 without Accept-Query is probably an intermediary refusing an unknown method, but your own server could also send one. If you control the server, always send Accept-Query on every response from QUERY-capable routes, including errors. The heuristic then becomes reliable.

Fallback on the server: POST + X-HTTP-Method-Override

When the network path between client and server drops QUERY, the old method-override trick tunnels it through POST. Accept it, but with strict limits:

// method-override.ts (Fastify hook)
import type { FastifyInstance } from 'fastify';

// Only allow overriding INTO safe methods. Never accept an override to DELETE, PUT or PATCH:
// that turns every "harmless" POST into a write bypass for WAF rules and audit filters
// that key on the method.
const ALLOWED_OVERRIDES = new Set(['QUERY']);

// Only on routes that actually implement QUERY.
const QUERY_ROUTES = new Set(['/contacts']);

export function registerQueryOverride(app: FastifyInstance) {
  app.addHook('onRequest', async (req, reply) => {
    if (req.method !== 'POST') return;
    const override = req.headers['x-http-method-override'];
    if (typeof override !== 'string') return;

    const target = override.toUpperCase();
    const path = req.url.split('?')[0];
    if (!ALLOWED_OVERRIDES.has(target) || !QUERY_ROUTES.has(path)) {
      return reply.code(400).send({ title: 'Unsupported method override' });
    }

    // Tell caches and observers that the response depends on this header.
    reply.header('Vary', 'X-HTTP-Method-Override');
    // Mark the response so dashboards can track how much traffic still needs the fallback.
    reply.header('X-Served-Via', 'method-override');
  });
}

The cleanest routing option is a dedicated alias (POST /contacts/query) that calls the same handler. Rewriting req.method inside the framework works in some routers and not others, so use the alias unless you've tested the rewrite on your framework version.

Method override has real costs

  • No caching. Every intermediary sees a POST. Shared caches won't store it, so you lose the main benefit of QUERY.
  • No automatic retries. Clients and proxies treat the request as non-idempotent.
  • CSRF exposure. A cross-site <form method="post"> can't set custom headers, which helps. But if you also accept the override as a query parameter or form field (_method=QUERY), you're back to accepting cross-site POSTs. Accept the header only.
  • Security tooling blind spots. WAF rules written for "POST /contacts" now see search traffic, and rules written for QUERY never fire. Log the effective method.

Caching proxy keyed on a normalized body hash

Since nginx doesn't cache QUERY and CDN support is still arriving, you may need to cache at your own edge or in a sidecar. The core is the cache key: method + URI + media type + normalized body + Vary headers.

// query-cache-key.ts
import { createHash } from 'node:crypto';
import { gunzipSync, brotliDecompressSync } from 'node:zlib';

/** Canonical JSON: sorted object keys, no insignificant whitespace. Array order is preserved,
 *  because in most query languages ["a","b"] and ["b","a"] can mean different things (ordering, priority). */
export function canonicalJson(value: unknown): string {
  if (value === null || typeof value !== 'object') return JSON.stringify(value);
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
  const entries = Object.keys(value as Record<string, unknown>)
    .sort()
    .filter((k) => (value as Record<string, unknown>)[k] !== undefined)
    .map((k) => `${JSON.stringify(k)}:${canonicalJson((value as Record<string, unknown>)[k])}`);
  return `{${entries.join(',')}}`;
}

function decodeBody(raw: Buffer, contentEncoding: string | undefined): Buffer {
  switch ((contentEncoding ?? 'identity').toLowerCase()) {
    case 'identity':
      return raw;
    case 'gzip':
      return gunzipSync(raw, { maxOutputLength: 1024 * 1024 });
    case 'br':
      return brotliDecompressSync(raw, { maxOutputLength: 1024 * 1024 });
    default:
      throw new Error(`Uncacheable Content-Encoding: ${contentEncoding}`);
  }
}

export type KeyInput = {
  method: string;
  url: string; // full URI including query string
  contentType: string | undefined;
  contentEncoding: string | undefined;
  body: Buffer;
  varyValues: Record<string, string | undefined>; // e.g. { accept, authorization }
};

/** Returns null when the request should bypass the cache. */
export function queryCacheKey(input: KeyInput): string | null {
  if (input.method !== 'QUERY' || !input.contentType) return null;

  const [type, ...params] = input.contentType.split(';').map((s) => s.trim().toLowerCase());
  let normalized: string;
  try {
    const decoded = decodeBody(input.body, input.contentEncoding);
    if (type === 'application/json' || type.endsWith('+json')) {
      normalized = canonicalJson(JSON.parse(decoded.toString('utf8')));
    } else {
      // Unknown query language: don't guess. Byte-exact keys are always correct, just less effective.
      normalized = decoded.toString('base64');
    }
  } catch {
    return null; // let the origin produce the 400/415
  }

  const h = createHash('sha256');
  h.update(`QUERY\n${input.url}\n${type};${params.sort().join(';')}\n`);
  for (const name of Object.keys(input.varyValues).sort()) {
    h.update(`${name}:${input.varyValues[name] ?? ''}\n`);
  }
  h.update(normalized);
  return `q:${h.digest('base64url')}`;
}
// query-cache-key.check.ts (run with: node --experimental-strip-types query-cache-key.check.ts)
import assert from 'node:assert/strict';
import { canonicalJson, queryCacheKey } from './query-cache-key.ts';

const base = {
  method: 'QUERY',
  url: 'https://api.example.com/catalog',
  contentType: 'application/json',
  contentEncoding: undefined,
  varyValues: { accept: 'application/json' },
};
const key = (json: string) => queryCacheKey({ ...base, body: Buffer.from(json) });

// Whitespace and key order are insignificant.
assert.equal(key('{"a":1,"b":[1,2]}'), key('{ "b": [1, 2],\n "a": 1 }'));
// Array order is significant.
assert.notEqual(key('{"b":[1,2]}'), key('{"b":[2,1]}'));
// Different values never collide.
assert.notEqual(key('{"city":"Pune"}'), key('{"city":"Mumbai"}'));
// Different Accept means different entry.
assert.notEqual(
  key('{"a":1}'),
  queryCacheKey({ ...base, varyValues: { accept: 'text/csv' }, body: Buffer.from('{"a":1}') }),
);
// Non-QUERY and malformed bodies bypass.
assert.equal(queryCacheKey({ ...base, method: 'POST', body: Buffer.from('{}') }), null);
assert.equal(key('{not json'), null);
assert.equal(canonicalJson({ z: 1, a: { y: 2, b: 3 } }), '{"a":{"b":3,"y":2},"z":1}');
console.log('query cache key checks passed');

The proxy around it is a normal read-through cache. Forward the original bytes upstream, store only when the response's Cache-Control allows it, and respect private:

// query-cache-proxy.ts (excerpt)
import http from 'node:http';
import { queryCacheKey } from './query-cache-key.ts';

const UPSTREAM = 'http://127.0.0.1:3000';
const MAX_BODY = 64 * 1024;
// Simplification: in-process Map with no eviction; use an LRU or Redis with TTL before real traffic.
const cache = new Map<string, { status: number; headers: Record<string, string>; body: Buffer; expires: number }>();

http
  .createServer(async (req, res) => {
    const chunks: Buffer[] = [];
    let size = 0;
    for await (const c of req) {
      size += c.length;
      if (size > MAX_BODY) return void res.writeHead(413).end();
      chunks.push(c);
    }
    const body = Buffer.concat(chunks);

    const key = queryCacheKey({
      method: req.method ?? '',
      url: `${UPSTREAM}${req.url}`,
      contentType: req.headers['content-type'],
      contentEncoding: req.headers['content-encoding'],
      body,
      varyValues: { accept: req.headers.accept },
    });

    // Requests carrying credentials skip the shared cache entirely.
    const cacheable = key !== null && !req.headers.authorization && !req.headers.cookie;
    const hit = cacheable ? cache.get(key) : undefined;
    if (hit && hit.expires > Date.now()) {
      res.writeHead(hit.status, { ...hit.headers, 'x-cache': 'HIT' });
      return void res.end(hit.body);
    }

    const upstream = await fetch(`${UPSTREAM}${req.url}`, {
      method: req.method,
      headers: req.headers as Record<string, string>,
      body: body.length ? body : undefined, // original bytes, not the normalized form
    });
    const upstreamBody = Buffer.from(await upstream.arrayBuffer());
    const headers = Object.fromEntries(upstream.headers);
    const cc = upstream.headers.get('cache-control') ?? '';
    const maxAge = /(?:^|,)\s*(?:s-maxage|max-age)=(\d+)/.exec(cc)?.[1];

    if (cacheable && upstream.ok && maxAge && !/private|no-store/.test(cc)) {
      cache.set(key, { status: upstream.status, headers, body: upstreamBody, expires: Date.now() + Number(maxAge) * 1000 });
    }
    res.writeHead(upstream.status, { ...headers, 'x-cache': 'MISS' });
    res.end(upstreamBody);
  })
  .listen(8080);

The excerpt leaves out hop-by-hop header stripping, request coalescing, and honoring the response's Vary instead of a fixed list. A production proxy needs all three. If you can, prefer adding QUERY caching to the proxy you already run (Envoy, a CDN worker) over shipping a new one.

Describing QUERY in OpenAPI 3.2

openapi: 3.2.0
info: { title: Contacts API, version: 1.0.0 }
paths:
  /contacts:
    query:
      operationId: queryContacts
      summary: Search contacts with a JSON filter
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContactQuery' }
      responses:
        '200':
          description: Matching contacts
          headers:
            Location:
              description: Equivalent resource; GET re-runs this query
              schema: { type: string, format: uri-reference }
        '415':
          description: Query media type not supported
          headers:
            Accept-Query:
              schema: { type: string }
        '422':
          description: Query is well-formed but cannot be processed

Check every tool in your pipeline (linters, code generators, docs renderers, gateways that import specs). Several are known to silently drop query operations, so the endpoint disappears from the generated SDK without any error.


Edge Cases and Failure Modes

Intermediaries that reject unknown methods

The most common failure isn't your code. It's something in between:

flowchart LR
    C[Client] --> CDN[CDN / edge]
    CDN --> WAF[WAF]
    WAF --> LB[Load balancer]
    LB --> RP[nginx / ingress]
    RP --> APP[App server]
    CDN -. "may reject: 405/501 or 400" .-> C
    WAF -. "may block unknown method,<br/>or let it through uninspected" .-> C
    RP -. "limit_except denies it;<br/>never caches it" .-> C

Before rollout, send curl -X QUERY through every hop in every environment, including corporate egress proxies if your clients are enterprises. Keep the fallback in the client until telemetry shows the fallback rate is near zero.

WAF bypass, the dangerous direction

The opposite failure is worse: a WAF that doesn't recognize QUERY might pass it through without inspecting the body. Rules written as "inspect bodies of POST/PUT/PATCH" skip QUERY entirely. A SQL-injection payload that's blocked as POST may get through as QUERY. SANS ISC suggests a direct test: send the same malicious payload as POST and as QUERY and compare. Then add QUERY to every method-based rule (http.method in {"GET", "POST", "QUERY"} style conditions).

CORS: every cross-origin QUERY is preflighted

Only GET, HEAD and POST are CORS-safelisted methods. RFC 10008 confirms QUERY isn't one, so browsers send a preflight:

sequenceDiagram
    participant B as Browser (app.example.com)
    participant A as API (api.example.com)
    B->>A: OPTIONS /contacts<br/>Origin: https://app.example.com<br/>Access-Control-Request-Method: QUERY<br/>Access-Control-Request-Headers: content-type
    A-->>B: 204<br/>Access-Control-Allow-Origin: https://app.example.com<br/>Access-Control-Allow-Methods: GET, POST, QUERY<br/>Access-Control-Allow-Headers: content-type<br/>Access-Control-Max-Age: 600
    B->>A: QUERY /contacts { ... }
    A-->>B: 200 OK<br/>Access-Control-Allow-Origin: https://app.example.com

In practice:

  • Add QUERY to Access-Control-Allow-Methods explicitly. Many CORS middlewares default to a fixed list that doesn't include it.
  • Set Access-Control-Max-Age so the preflight is cached and you pay the extra round trip once per resource, not once per request.
  • A JSON POST /search from a browser is also preflighted, because Content-Type: application/json isn't a safelisted content type. Moving from that to QUERY doesn't add a round trip.

Cache key normalization mistakes

MistakeConsequence
Body not in the key at all (treating QUERY like GET)Every query returns whatever was cached first. A data leak across users if the cache is shared
Over-normalizing (sorting arrays, lowercasing values, dropping null)Different queries collide. For example, "sort": ["price", "name"] and ["name", "price"] return the same cached page
Not decoding Content-Encoding before hashingHarmless but wasteful: gzip and identity versions of the same query miss each other
Ignoring Content-Type in the keyA JSONPath body and a SQL body with the same bytes collide (rare, but real for short queries)
Ignoring Vary / AuthorizationUser A's results served to user B
Hashing with a fast non-cryptographic hashAttacker-crafted collisions can poison entries. Use SHA-256

When unsure, hash the exact bytes. A missed cache hit costs latency. A false hit costs correctness.

Body size limits

  • Set a specific, small body limit on QUERY routes (tens of KB). Global limits sized for file uploads are far too big.
  • Remember that retries multiply cost: a 1 MB QUERY retried three times by a client and twice by a proxy is a 6 MB request in total.
  • Decompression bombs: a 10 KB gzip body can expand to gigabytes. Cap the decompressed size (the maxOutputLength in the cache-key code above) and reject compressed bodies you don't need.
  • Bound query complexity, not just size: maximum filter depth, number of OR branches, result limit. Safe doesn't mean cheap.

Logging and privacy

QUERY moves sensitive filters out of the URL, but they can still leak:

  • Request body logging: if your middleware logs bodies of non-GET requests, it now logs every search. Redact or skip QUERY bodies explicitly.
  • Minted URIs: as noted above, Location and Content-Location must use opaque IDs.
  • Cache storage: cached QUERY responses (and, for debugging, sometimes keys or bodies) persist in the cache. Treat the cache as a data store under your retention policy.
  • Tracing: span attributes often capture http.request.body for non-GET methods. Check your OpenTelemetry instrumentation config.

"Safe" is a promise you must keep

Intermediaries and clients may repeat, prefetch or retry QUERY freely. If your QUERY handler does anything non-idempotent (decrements a quota, marks items as "seen", enqueues a job), that side effect will eventually happen multiple times. Logging and metrics are fine. Business state changes are not. If the operation changes state, it's a POST.


Decision Framework

CriterionGET + query stringPOST /searchQUERYGraphQL (POST)
Complex / nested filtersAwkward encodingNatural (JSON)Natural (any media type)Natural (typed language)
Size limit~8 KB in practiceBody limitBody limitBody limit
Safe + idempotent by specYesNoYesNo (over POST)
Automatic retries by intermediariesYesNoYesNo
HTTP caching by intermediariesYes, everywhereEffectively noBy spec yes, in practice only where implementedNo (needs persisted queries + GET)
Bookmarkable / shareableYesNoVia LocationVia persisted-query IDs
Filters kept out of URL logsNoYesYesYes
Browser CORS cost (JSON body)Simple requestPreflightPreflightPreflight
Works through every proxy todayYesYesNo: verify each hopYes
Tooling maturityUniversalUniversalEarly (2026)Mature, separate ecosystem

How to choose

flowchart TD
    A[Read-only search / filter endpoint] --> B{Fits comfortably in a URL<br/>and contains nothing sensitive?}
    B -- yes --> GET[GET with query string]
    B -- no --> C{Do you control every hop?<br/>own SDK, mesh, proxies}
    C -- yes --> Q[QUERY]
    C -- no --> D{Browser-facing or third-party proxies?}
    D -- yes --> QF[QUERY with POST fallback,<br/>or POST /search for now]
    D -- no --> Q
    A --> G{Clients need to pick fields across<br/>many related types?}
    G -- yes --> GQL[GraphQL]

Rules of thumb:

  • Simple filters stay on GET. GET /orders?status=shipped&page=2 is still the most cacheable, debuggable and compatible request on the web. Don't move it to QUERY for the sake of it.
  • Use QUERY for new internal search APIs where filters are structured, large or sensitive, and you control client and server.
  • Keep POST /search as an alias on public APIs while proxy and CDN support catches up. Point both at the same handler so behavior can't drift.
  • QUERY doesn't replace GraphQL. GraphQL is a query language plus a schema and type system. QUERY is a transport method. GraphQL could be carried by QUERY (Content-Type: application/graphql-response+json responses, query documents in the body), which would give GraphQL reads proper HTTP semantics, but tooling for that combination is very early.

War Story (illustrative scenario, not a real incident)

A team runs a B2B analytics API. Customers build saved reports whose filters include account IDs, email domains and free-text notes. The API started as GET /reports/run?filter=<base64 JSON>. As reports grew, the base64 blob routinely hit 6–10 KB, and some customers behind corporate proxies got intermittent 414 URI Too Long. A security review also found full filter payloads, including customer email addresses, in CDN access logs kept for 13 months.

Attempt 1: POST /reports/run. The 414s and the logging problem disappeared. So did the CDN cache, which had been absorbing about 60% of dashboard refreshes. Origin load roughly doubled, and the mobile SDK stopped retrying failed requests, because its retry policy (correctly) excluded POST. Users on flaky networks saw "Report failed" banners instead of transparent retries.

Attempt 2: QUERY /reports/run. Server-to-server customers using the official SDK switched first, and retries came back immediately. Browser traffic went through a CDN that didn't cache QUERY yet, so the team added a small caching layer in front of origin, keyed on a SHA-256 of canonical JSON plus Accept and tenant ID.

The bug. The first version of the cache key normalizer sorted all arrays "for better hit rates." Reports have a groupBy: ["region", "month"] field, where order determines the nesting of the output. Two customers' dashboards silently swapped layouts whenever their reports differed only in groupBy order. Because tenant ID was in the key, no data crossed tenants, but a customer escalated with screenshots showing "the numbers rearranging themselves."

The fixes.

  1. The normalizer stopped touching arrays. It only sorts object keys and strips whitespace, with a unit test that asserts ["a","b"] and ["b","a"] hash differently.
  2. Responses gained a Location: /reports/saved/<opaque-id> header. The dashboard switched to GET on that URI for refreshes, which the existing CDN could cache, and the cache-hit rate recovered past its original level.
  3. The WAF team found that their body-inspection rule listed POST, PUT, PATCH only. QUERY bodies weren't being inspected at all. They added QUERY to the rule before broadening the rollout.
  4. A POST + X-HTTP-Method-Override: QUERY fallback stayed in the SDK for customers behind proxies that returned 405. Telemetry showed about 3% of enterprise traffic still needed it six months later.

Lesson. QUERY fixed the problem it was designed for (big, sensitive, retryable reads), but the cache key is where correctness lives. Over-normalizing is a silent data-integrity bug, and every security control keyed on the method needs QUERY added explicitly.


Further Reading