> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reliantlabs.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Add a custom Connect RPC Go handler with typed React hooks

> Declare a Connect RPC in proto, scaffold its Go handler, return errors with svcerr.Wrap, and call it from React through the generated, typed mutation hook.

You will add `ArchiveProduct` to the `catalog` service: an RPC that takes a product off sale without deleting it. Forge writes the handler stub, a test table and a typed React hook from the proto declaration. You write the body.

Anything that is not plain create, read, update or delete is a custom RPC, and its logic is yours. [Adding a feature](https://docs.reliantlabs.io/forge/adding-features.md#a-custom-rpc) summarizes the rules; this guide runs them end to end.

## Before you begin

* The `shop` project from [Build a Go and React app with Connect RPC](https://docs.reliantlabs.io/guides/forge/build-go-react-app-connect-rpc.md), with its `Product` entity. [Add a database table](https://docs.reliantlabs.io/guides/forge/add-table-crud-api-pages.md) is optional.
* Forge v1.6 or later. Inside Reliant, run it as `reliant forge`, and check the version with `reliant forge --version` inside the project.
* No account. Every step runs locally.

**1. Declare the RPC in the proto**

Add the RPC to the service block and its two messages to the file. An RPC named exactly `Create<E>`, `Get<E>`, `Update<E>`, `Delete<E>` or `List<Es>` would be wired as CRUD, so a verb like `Archive` makes it custom. Forge never invents an RPC: if the service block does not name it, it does not exist.

```protobuf proto/services/catalog/v1/catalog.proto theme={null}
service CatalogService {
  // ArchiveProduct takes a product off sale without deleting it.
  rpc ArchiveProduct(ArchiveProductRequest) returns (ArchiveProductResponse) {
    option (forge.v1.method) = {
      auth_required: true
      activity: {
        verb: "archive"
        target: { kind: "product", id: "id", label: "response.product.name" }
      }
    };
  }
  // ... the Product CRUD rpcs
}

message ArchiveProductRequest {
  string id = 1;
}

message ArchiveProductResponse {
  Product product = 1;
}
```

The `activity` block records each call in the activity stream; the lint step shows why it is required.

**2. Scaffold the handler**

```bash terminal theme={null}
reliant forge scaffold rpc catalog ArchiveProduct
```

```text Output (trimmed) theme={null}
✅ Code generation complete — 65 file(s) written, 13 changed (3 new, 10 updated).
✅ ArchiveProduct is wired on internal/handlers/catalog/*Service (rpc_archive_product.go).
```

It ran `generate` for you, in about 9 seconds here. The stub sits in a file of its own, so two people implementing two RPCs never edit the same file:

```go internal/handlers/catalog/rpc_archive_product.go theme={null}
// FORGE_SCAFFOLD: implement business logic; remove this marker when done.
func (s *Service) ArchiveProduct(
	ctx context.Context,
	req *connect.Request[pb.ArchiveProductRequest],
) (*connect.Response[pb.ArchiveProductResponse], error) {
	return nil, svcerr.Wrap(svcerr.ScaffoldStub("ArchiveProduct"))
}
```

It also wrote `handlers_scaffold_archive_product_test.go`. Its single row passes only while the stub is in place, so it fails as soon as you implement the RPC.

**3. Write the handler**

Replace the stub. The handler validates, does the work through `s.deps`, and returns every error through `svcerr.Wrap`:

```go internal/handlers/catalog/rpc_archive_product.go theme={null}
func (s *Service) ArchiveProduct(
	ctx context.Context,
	req *connect.Request[pb.ArchiveProductRequest],
) (*connect.Response[pb.ArchiveProductResponse], error) {
	if req.Msg.GetId() == "" {
		return nil, svcerr.Wrap(svcerr.InvalidArgument("id is required"))
	}
	p := &db.Product{ID: req.Msg.GetId(), Active: false}
	// Writes only the active column; a missing row is svcerr.NotFound("product").
	if err := db.UpdateProductMasked(ctx, s.deps.DB, p, []string{"active"}); err != nil {
		return nil, svcerr.Wrap(err)
	}
	out, err := productToProto(p)
	if err != nil {
		return nil, svcerr.Wrap(err)
	}
	return connect.NewResponse(&pb.ArchiveProductResponse{Product: out}), nil
}
```

`svcerr.Wrap` keeps the code and message of an error you created (`invalid_argument`, `not_found`). Any other error, such as a raw database error, reaches the client as `internal server error`, and the original is logged with the request ID, so you never write a `connect.Code` switch. `db.UpdateProductMasked` and `productToProto` are generated; hand-written queries go in `internal/db/product_repo_ext.go`.

**4. Replace the scaffold test row**

Swap the stub row for real cases. The test harness starts a real Postgres for you:

```go internal/handlers/catalog/handlers_scaffold_archive_product_test.go theme={null}
database := crudTestDB(t)
svc := catalog.NewTestCatalog(t, catalog.WithDB(database))
ctx := catalog.AuthedContext(t)
created, err := svc.CreateProduct(ctx, connect.NewRequest(catalog.NewCreateProductRequest(t, database, 0)))
if err != nil {
	t.Fatalf("create: %v", err)
}
id := created.Msg.GetProduct().GetId()

tdd.RunRPCCases(t, []tdd.RPCCase[pb.ArchiveProductRequest, pb.ArchiveProductResponse]{
	{Name: "archives_an_active_product", Req: connect.NewRequest(&pb.ArchiveProductRequest{Id: id}), Ctx: ctx,
		Check: func(t *testing.T, resp *connect.Response[pb.ArchiveProductResponse]) {
			if resp.Msg.GetProduct().GetActive() {
				t.Fatalf("product %s is still active", id)
			}
		}},
	{Name: "missing_id", Req: connect.NewRequest(&pb.ArchiveProductRequest{}), Ctx: ctx, WantErr: connect.CodeInvalidArgument},
	{Name: "unknown_product", Req: connect.NewRequest(&pb.ArchiveProductRequest{Id: "does-not-exist"}), Ctx: ctx, WantErr: connect.CodeNotFound},
}, svc.ArchiveProduct)
```

```bash terminal theme={null}
task test:short -- -v -run TestArchiveProduct ./internal/handlers/catalog/...
```

```text theme={null}
--- PASS: TestArchiveProduct_Generated (0.11s)
    --- PASS: TestArchiveProduct_Generated/archives_an_active_product (0.00s)
    --- PASS: TestArchiveProduct_Generated/missing_id (0.00s)
    --- PASS: TestArchiveProduct_Generated/unknown_product (0.00s)
ok  	example.com/shop/internal/handlers/catalog	0.127s
```

**5. Regenerate and run the gate**

```bash terminal theme={null}
reliant forge generate && go build ./... && reliant forge lint --quiet
```

Without the `activity` block from the first step, lint fails the RPC:

```text theme={null}
❌ forge convention lint — 1 error
   ✗ proto/services/catalog/v1/catalog.proto:20 [forgeconv-activity-declared] rpc CatalogService.ArchiveProduct mutates (its name is not a read verb and it is not NO_SIDE_EFFECTS) but declares no activity event
```

A name that starts with a read verb (`Get`, `List`, `Search`, ...) or `option idempotency_level = NO_SIDE_EFFECTS;` marks a read instead. To opt a mutation out, write `activity: { none: "<why>" }`. The [rule's reference](https://docs.reliantlabs.io/forge/linting/rules-conventions.md#forgeconv-activity-declared) has the details. With the block in place:

```text theme={null}
✅ All 29 gating linters passed.
```

To re-check only this rule while you iterate, run `reliant forge lint --conventions`, which takes under a second. The full run took 80 seconds here.

**6. Call it from React**

`generate` added a mutation hook to the service's hooks file:

```bash terminal theme={null}
reliant forge project shapes --grep ArchiveProduct
```

```text theme={null}
rpc      CatalogService.ArchiveProduct   proto/services/catalog/v1/catalog.proto:20
handler  CatalogService.ArchiveProduct   internal/handlers/catalog/rpc_archive_product.go:14
hook     useArchiveProduct               frontends/web/src/hooks/catalog-service-hooks_gen.ts:209
```

```ts frontends/web/src/hooks/catalog-service-hooks_gen.ts theme={null}
export const useArchiveProduct = createMutationHook<typeof ArchiveProductRequestSchema, ArchiveProductResponse>(
  catalogServiceKeys.all,
  (req) => client.archiveProduct(req),
);
```

The key is `catalogServiceKeys.all`: a custom mutation's hook invalidates every query on its service, so a list rendered with `useListProducts` refetches after an archive. While the handler was a stub, `catalogServiceImplemented.archiveProduct` was `false`; the `generate` after you implemented it set it to `true`. Call it like any React Query mutation: `const archive = useArchiveProduct(); archive.mutate({ id })`.

**7. Verify it against the running API**

Start the stack with `reliant forge env up dev`, sign in as the development user from `idp-steps.yaml`, and call the RPC over plain HTTP with the session cookie:

```bash terminal theme={null}
curl -s -c cj -X POST localhost:8085/auth/login -H 'content-type: application/json' \
  -d '{"email":"admin@shop.localhost","password":"Password1!"}'
curl -s -b cj -X POST localhost:8085/services.catalog.v1.CatalogService/ArchiveProduct \
  -H 'content-type: application/json' -d '{"id":"0134c82b-e994-5777-a85e-9f27cbf14f3f"}'
```

```text theme={null}
{"product":{"name":"sample_name_5", "priceCents":"5", "id":"0134c82b-...", "updatedAt":"2026-11-20T10:38:07.799540207Z"}}
```

`active` is missing from the JSON because it is now `false`, the default. An unknown ID answers `{"code":"not_found","message":"product not found"}`, and an empty one answers `{"code":"invalid_argument","message":"id is required"}`. The API log at `.forge/logs/dev/api.log` has an `activity.event` line with `"verb":"archive"`. Stop the stack with `reliant forge env down dev`.

## What this does not do

* **No access control.** `auth_required` only decides whether the caller is signed in. To limit who may archive a product, read `middleware.GetUser(ctx)` in the handler and check it there.
* **No business logic.** Forge writes the stub, the test table and the hook. The handler body and its tests are yours, and `generate` never rewrites them.

## Troubleshooting

> [accordion] forgeconv-activity-declared: ... mutates ... but declares no activity event
>
> Add an `activity` block to the RPC's `forge.v1.method` option, or `activity: { none: "<why>" }`, then run `reliant forge generate` before `lint`. Lint reads the result that `generate` records.

> [accordion] missing Authorization header (procedure is not on the unauthenticated allow-list)
>
> The call carried no session. Sign in through `/auth/login` first and send the cookie, or set `auth_required: false` on the RPC if it is meant to be public.

## Next steps

> [card] [Add a worker or cron job](https://docs.reliantlabs.io/guides/forge/background-worker-cron-job.md)
>
> Run work on a schedule in the same server process

> [card] [Add a table](https://docs.reliantlabs.io/guides/forge/add-table-crud-api-pages.md)
>
> Generate the CRUD API and pages for a new entity

> [card] [How forge generate works](https://docs.reliantlabs.io/deep-dives/how-forge-generate-works.md)
>
> What each generate step writes, and why a re-run is cheap

> [card] [Adding a feature](https://docs.reliantlabs.io/forge/adding-features.md)
>
> The everyday loop: services, RPCs, migrations, the gate


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.