Skip to content

Add requestGate handler option - #1781

Merged
timostamm merged 2 commits into
mainfrom
tstamm/Add-requestGate-handler-option
Aug 31, 2026
Merged

Add requestGate handler option#1781
timostamm merged 2 commits into
mainfrom
tstamm/Add-requestGate-handler-option

Conversation

@timostamm

@timostamm timostamm commented Aug 27, 2026

Copy link
Copy Markdown
Member

This PR adds a new handler option:

  /**
   * An optional gate that runs after request headers are available, but before
   * any request message is received, decompressed, or parsed.
   *
   * This is the right place to reject unauthenticated requests cheaply. Throw
   * a ConnectError to end any RPC without reading the body.
   *
   * The gate receives the HandlerContext for the call. It may set context
   * values for interceptors and the implementation to consume, and set
   * response headers or trailers.
   */
  requestGate?: (context: HandlerContext) => void | Promise<void>;

To authenticate requests on a server, prefer this option over interceptors. For unary RPCs, interceptors run after the request message is received, decompressed, and parsed. The request gate turns away requests without spending anything on them.

import * as http from "http";
import routes from "./connect";
import { connectNodeAdapter } from "@connectrpc/connect-node";
import { Code, ConnectError } from "@connectrpc/connect";
import type { HandlerContext } from "@connectrpc/connect";
// This can come from an auth library like passport.js
import { authenticate } from "./authenticate";

function authGate(context: HandlerContext) {
  if (authenticate(context.requestHeader.get("Authorization")) === undefined) {
    throw new ConnectError("User not authenticated", Code.Unauthenticated);
  }
}

http
  .createServer(
    connectNodeAdapter({
      routes,
      requestGate: authGate,
    }),
  )
  .listen(8080);

Signed-off-by: Timo Stamm <ts@timostamm.de>
@timostamm
timostamm merged commit 2548dac into main Aug 31, 2026
37 of 39 checks passed
@timostamm
timostamm deleted the tstamm/Add-requestGate-handler-option branch August 31, 2026 11:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants