Skip to content
Get startedDocs 1.3.x

Build Your First Connectum Service ​

Start with init, describe a protected page in protobuf and add a short handler. The scaffold provides the server, health checks, reflection and shutdown wiring; select auth and observability when creating the project.

From init to a protected page

Build a protected Page service

Describe the operation, generate its types and add the handler. The server foundation comes from the CLI.

Start with the foundation in place

Auth and observability are selected here. Health, reflection and graceful shutdown are already in the scaffold.

Terminal

bash
npx @connectum/[email protected] init private-page --auth --otel --yes
cd private-page
pnpm install

private-page/ · scaffolded source files

Files created by init. Installed dependencies are omitted.

text
private-page/
├── .dockerignore
├── .gitignore
├── Dockerfile
├── Dockerfile.bun
├── README.md
├── buf.gen.yaml
├── buf.yaml
├── package.json
├── pnpm-workspace.yaml
├── proto/
│   └── greeter/
│       └── v1/
│           └── greeter.proto
├── src/
│   ├── auth.ts
│   ├── index.ts
│   ├── server.ts
│   └── services/
│       └── greeterService.ts
├── tests/
│   └── e2e/
│       └── e2e.test.ts
└── tsconfig.json

These are code and recorded results from the included runnable example. Selecting a step does not run a shell, compiler or server in this page.

Read the complete server and authentication setup

Configure JWKS_URI, JWT_ISSUER and JWT_AUDIENCE for your issuer. The verification helper uses temporary test-only keys and a loopback JWKS endpoint; init does not create a login service.

The CLI adds a narrow allow rule for health and reflection probes. This example preserves it unchanged. GetPage still requires a verified JWT. Protocol registration alone does not grant authorization.

src/server.ts

typescript
/**
 * Server factory — services, health, reflection, interceptors, graceful shutdown.
 *
 * @module server
 */

import { createServer } from "@connectum/core";
import type { Server } from "@connectum/core";
import { Healthcheck } from "@connectum/healthcheck";
import { Reflection } from "@connectum/reflection";
import { createOtelInterceptor } from "@connectum/otel";
import { createDefaultInterceptors, createErrorHandlerInterceptor } from "@connectum/interceptors";
import { buildAuthInterceptors } from "#auth.ts";
import { greeterService } from "#services/greeterService.ts";
import { pageService } from "#services/pageService.ts";

/**
 * Build a Connectum server hosting GreeterService.
 *
 * @param port - TCP port to bind (0 = random, for tests).
 * @param autoShutdown - install SIGTERM/SIGINT graceful-shutdown handlers.
 */
export function buildServer(port = 5000, autoShutdown = false): Server {
    return createServer({
        services: [greeterService, pageService],
        port,
        host: "0.0.0.0",
        allowHTTP1: false,
        protocols: [Healthcheck({ httpEnabled: true }), Reflection()],
        interceptors: [createOtelInterceptor({ trustRemote: false }), createErrorHandlerInterceptor(), ...buildAuthInterceptors(), ...createDefaultInterceptors({ errorHandler: false })],
        shutdown: { autoShutdown, timeout: 10_000 },
    });
}

src/auth.ts

typescript
/**
 * Authentication (JWT via JWKS) + authorization (driven by proto `(connectum.auth.v1.*)`
 * annotations). Configure via env: JWKS_URI, JWT_ISSUER, JWT_AUDIENCE.
 *
 * @module auth
 */

import { AuthzEffect, createJwtAuthInterceptor } from "@connectum/auth";
import { createProtoAuthzInterceptor, getPublicMethods } from "@connectum/auth/proto";
import type { Interceptor } from "@connectrpc/connect";
import { GreeterService } from "#gen/greeter/v1/greeter_pb.ts";

// Methods annotated `(connectum.auth.v1.method_auth) = { public: true }` in your proto
// are read here and skipped by the JWT interceptor. Add your services to this list.
const publicMethods = getPublicMethods([GreeterService]);

// The health and reflection services carry no credentials, so they are opened twice: the JWT
// interceptor skips them, and the authorizer, which denies by default, gets an allow rule for them.
// Listing them in `skipMethods` alone leaves them answering `unauthenticated`. Delete an entry to
// require a token for that service.
const protocolMethods = ["grpc.health.v1.Health/*", "grpc.reflection.v1.ServerReflection/*", "grpc.reflection.v1alpha.ServerReflection/*"];

/**
 * Build the auth interceptor chain: JWT authentication followed by proto-driven
 * authorization (deny-by-default — annotate methods/services to allow).
 */
export function buildAuthInterceptors(): Interceptor[] {
    const jwtAuth = createJwtAuthInterceptor({
        jwksUri: process.env.JWKS_URI ?? "http://localhost:8080/.well-known/jwks.json",
        issuer: process.env.JWT_ISSUER,
        audience: process.env.JWT_AUDIENCE,
        algorithms: ["RS256"],
        skipMethods: [...publicMethods, ...protocolMethods],
    });
    const authz = createProtoAuthzInterceptor({
        rules: [{ name: "protocol-endpoints", methods: protocolMethods, effect: AuthzEffect.ALLOW }],
    });
    return [jwtAuth, authz];
}
Read every step without JavaScript

Start with the foundation in place

Auth and observability are selected here. Health, reflection and graceful shutdown are already in the scaffold.

bash
npx @connectum/[email protected] init private-page --auth --otel --yes
cd private-page
pnpm install
text
private-page/
├── .dockerignore
├── .gitignore
├── Dockerfile
├── Dockerfile.bun
├── README.md
├── buf.gen.yaml
├── buf.yaml
├── package.json
├── pnpm-workspace.yaml
├── proto/
│   └── greeter/
│       └── v1/
│           └── greeter.proto
├── src/
│   ├── auth.ts
│   ├── index.ts
│   ├── server.ts
│   └── services/
│       └── greeterService.ts
├── tests/
│   └── e2e/
│       └── e2e.test.ts
└── tsconfig.json

Describe one protected operation

requires: {} accepts an authenticated caller without asking for additional roles or scopes.

proto
syntax = "proto3";

package page.v1;

import "connectum/auth/v1/options.proto";

service PageService {
  rpc GetPage(GetPageRequest) returns (GetPageResponse) {
    option (connectum.auth.v1.method_auth) = { requires: {} };
  }
}

message GetPageRequest {}

message GetPageResponse {
  string title = 1;
  string body = 2;
}

Generate the types and descriptors

Buf generates protobuf code. It does not write the handler or its business logic.

bash
pnpm exec buf generate
typescript
// @generated by protoc-gen-es v2.16.0 with parameter "target=ts,import_extension=.ts,erasable_syntax=true,map_imports=connectum/auth/v1/:@connectum/auth/gen"
// @generated from file page/v1/page.proto (package page.v1, syntax proto3)
/* eslint-disable */

import type { GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";
import { fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2";
import { file_connectum_auth_v1_options } from "@connectum/auth/gen/connectum/auth/v1/options_pb.js";
import type { Message } from "@bufbuild/protobuf";

/**
 * Describes the file page/v1/page.proto.
 */
export const file_page_v1_page: GenFile = /*@__PURE__*/
  fileDesc("ChJwYWdlL3YxL3BhZ2UucHJvdG8SB3BhZ2UudjEiEAoOR2V0UGFnZVJlcXVlc3QiLgoPR2V0UGFnZVJlc3BvbnNlEg0KBXRpdGxlGAEgASgJEgwKBGJvZHkYAiABKAkyUwoLUGFnZVNlcnZpY2USRAoHR2V0UGFnZRIXLnBhZ2UudjEuR2V0UGFnZVJlcXVlc3QaGC5wYWdlLnYxLkdldFBhZ2VSZXNwb25zZSIGorsYAhIAYgZwcm90bzM", [file_connectum_auth_v1_options]);

/**
 * @generated from message page.v1.GetPageRequest
 */
export type GetPageRequest = Message<"page.v1.GetPageRequest"> & {
};

/**
 * Describes the message page.v1.GetPageRequest.
 * Use `create(GetPageRequestSchema)` to create a new message.
 */
export const GetPageRequestSchema: GenMessage<GetPageRequest> = /*@__PURE__*/
  messageDesc(file_page_v1_page, 0);

/**
 * @generated from message page.v1.GetPageResponse
 */
export type GetPageResponse = Message<"page.v1.GetPageResponse"> & {
  /**
   * @generated from field: string title = 1;
   */
  title: string;

  /**
   * @generated from field: string body = 2;
   */
  body: string;
};

/**
 * Describes the message page.v1.GetPageResponse.
 * Use `create(GetPageResponseSchema)` to create a new message.
 */
export const GetPageResponseSchema: GenMessage<GetPageResponse> = /*@__PURE__*/
  messageDesc(file_page_v1_page, 1);

/**
 * @generated from service page.v1.PageService
 */
export const PageService: GenService<{
  /**
   * @generated from rpc page.v1.PageService.GetPage
   */
  getPage: {
    methodKind: "unary";
    input: typeof GetPageRequestSchema;
    output: typeof GetPageResponseSchema;
  },
}> = /*@__PURE__*/
  serviceDesc(file_page_v1_page, 0);

Write the handler and register it

These few lines are handwritten. Authentication stays in the server interceptor chain.

typescript
import { defineService } from '@connectum/core';
import { PageService } from '#gen/page/v1/page_pb.ts';

export const pageService = defineService(PageService, {
    getPage: () => ({
        title: 'Your private page',
        body: 'This content requires a verified JWT.',
    }),
});

Register the service and configure your issuer before starting:

typescript
/**
 * Server factory — services, health, reflection, interceptors, graceful shutdown.
 *
 * @module server
 */

import { createServer } from "@connectum/core";
import type { Server } from "@connectum/core";
import { Healthcheck } from "@connectum/healthcheck";
import { Reflection } from "@connectum/reflection";
import { createOtelInterceptor } from "@connectum/otel";
import { createDefaultInterceptors, createErrorHandlerInterceptor } from "@connectum/interceptors";
import { buildAuthInterceptors } from "#auth.ts";
import { greeterService } from "#services/greeterService.ts";
import { pageService } from "#services/pageService.ts";

/**
 * Build a Connectum server hosting GreeterService.
 *
 * @param port - TCP port to bind (0 = random, for tests).
 * @param autoShutdown - install SIGTERM/SIGINT graceful-shutdown handlers.
 */
export function buildServer(port = 5000, autoShutdown = false): Server {
    return createServer({
        services: [greeterService, pageService],
        port,
        host: "0.0.0.0",
        allowHTTP1: false,
        protocols: [Healthcheck({ httpEnabled: true }), Reflection()],
        interceptors: [createOtelInterceptor({ trustRemote: false }), createErrorHandlerInterceptor(), ...buildAuthInterceptors(), ...createDefaultInterceptors({ errorHandler: false })],
        shutdown: { autoShutdown, timeout: 10_000 },
    });
}
bash
export JWKS_URI="https://your-issuer.example/.well-known/jwks.json"
export JWT_ISSUER="https://your-issuer.example"
export JWT_AUDIENCE="private-page"
export OTEL_TRACES_EXPORTER=console
export OTEL_METRICS_EXPORTER=none
export OTEL_LOGS_EXPORTER=none
pnpm start

Send a request and inspect the response

Choose curl or grpcurl and the credentials to send. The emulator returns the captured response for that protocol and JWT.

json
{
  "paths": {
    "/page.v1.PageService/GetPage": {
      "post": {
        "security": [
          {
            "bearerAuth": []
          }
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  }
}
bash
curl --http2-prior-knowledge -sS \
  http://localhost:5000/page.v1.PageService/GetPage \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Connect-Protocol-Version: 1' \
  -d '{}'

Recorded successful curl response:

json
{
  "title": "Your private page",
  "body": "This content requires a verified JWT."
}
Reproduce the captured checks from the documentation source

The target framework checkout must be built and match the recorded source revision. Generate the project first; the verifier then runs its real process entry, including OTel initialization and shutdown.

bash
pnpm quickstart:generate
CONNECTUM_FRAMEWORK_ROOT=/path/to/target-framework pnpm quickstart:verify
pnpm quickstart:openapi
Build a first RPC manually
Build and verify the first RPC Project setup and protobuf generation feed a typed handler and server, then real clients verify both a greeting and rejection of an invalid request. CALL REPLY Prepare the projectNative .ts: Node ≥25.2; tsx path ≥22.13Bun tutorial: ≥1.3.6 · install dependenciesESM · tsconfig · validator · build permissions Define contract + generationGreeterService.SayHello; name min_len = 1buf.yaml + buf.gen.yaml; fetch dependenciesGenerate .ts imports and erasable enums Types + descriptorsbuild:proto produces gen/greeter_pb.tsinclude_imports includes validation rules Implement SayHellodefineService + response schemaReturn a greeting Start the servercreateServer + default validationHealthcheck + Reflection; h2c listenerReady / stopping; automatic shutdown Make a real callgrpcurl: list, call and health checkcurl: restart in HTTP/1.1 modeUse the fully qualified service name Verify both outcomesGreeting; empty name: INVALID_ARGUMENT Generation: check buf and .ts imports.Calls: check port, service name and TLS.Add TLS, auth and resilience after first call.
grpcurl uses h2c; curl over plaintext HTTP/1.1 requires changing the listener mode and restarting. Verify a greeting and a rejected invalid request before adding TLS, authentication and resilience.

What you will build ​

A PageService returns private content only to an authenticated caller. The contract owns the access requirement; the handler owns the content. OpenAPI is generated in a separate step from the same contract and authorization reader.

Prefer a greeting without auth setup?

The complete manual tutorial builds a GreeterService that accepts a name and returns a greeting:

proto
service GreeterService {
  rpc SayHello(SayHelloRequest) returns (SayHelloResponse);
}

This is a contract excerpt. The tutorial supplies both messages, the handler, server, generation configuration and commands.

Choose how to start ​

Published packages require Node.js ≥22.13.0. The tutorial's native Node.js TypeScript path needs ≥25.2.0; it also shows tsx and Bun alternatives. See runtime requirements and limits.

Find a section from the full guide

The detailed material is preserved on a separate page. Earlier section links still work here.