Wiring Knocket and Telegram into Next.js 15 Without Leaking Credentials to the Client

Wiring Knocket and Telegram into Next.js 15 Without Leaking Credentials to the Client

pr0h0••35 min read•coding
AI Usage (80%)

I spent a weekend wiring Knocket and Telegram into a Next.js 15 app without leaking credentials to the client, and the part that almost bit me wasn't the API call. It was everything around it: which process holds the bot token, what happens when the first call succeeds and the second times out, and whether a disabled submit button was quietly standing in for the authorization I never wrote.

This post walks through the server-side boundary I ended up with. You will see how to validate and authorize a Next.js 15 Route Handler, isolate credentials, implement narrow server-only adapters for Knocket and Telegram, make partial failure and retries explicit, and test the external-service boundary without live credentials. It follows a form submission through the handler into two server-only adapters, and it spends more time on the failure paths than the happy path, because the happy path is the part that already works.

One thing up front, because it shapes the whole article: I could not verify a Knocket API contract. So the Knocket half is built against a port interface with a clearly labeled mock behind it, and I treat "what does Knocket actually accept" as a prerequisite rather than something to guess at.

On this page

Keep Knocket and Telegram Behind One Server-Side Boundary in Next.js 15

Define the Form-to-Provider Walkthrough

The workflow is small on purpose: a Next.js 15 page renders a form, the form posts JSON to app/api/notify/route.ts, the handler validates and authorizes the request, a server-only adapter performs the verified Knocket operation, a second server-only adapter sends a Telegram notification, and the browser gets back a minimal status object plus a request identifier.

Nothing else crosses the boundary. The browser never learns a provider base URL, an API key, a chat identifier, or a raw upstream error body. That is the contract I am testing against.

The Technical Position: Hiding Credentials Is Necessary but Not Sufficient

Hiding credentials is necessary and insufficient.

Move TELEGRAM_BOT_TOKEN out of a NEXT_PUBLIC_ variable and stop there, and you have fixed exactly one problem. The server still accepts a client-supplied destination if you let it, still forwards provider error bodies into JSON responses, still retries ambiguous side effects, and still lets an unauthenticated caller burn your provider quota. Every one of those turns an authenticated server-side integration into a public proxy with your credentials attached.

So the position here is narrower and more demanding: the server owns the destination, the operation, the message content, the retry policy, and the error vocabulary. The client owns a form.

That is a real trade-off. It means I cannot build a generic "send a message to any chat" endpoint, which is the thing people usually want first. I think that generic endpoint is where most of these integrations go wrong, and I would rather write three narrow handlers than one configurable one.

Separate Source Facts from Implementation Choices

The seed for this topic is a HackerNoon tutorial titled "How to Integrate Knocket and Telegram With Next.js 15." The feed entry reports a publication date of 2026-11-25T03:51:24Z. I have not independently verified that article's contents, and I am not linking a guessed HackerNoon URL from a Google News RSS redirect — that redirect is not API documentation, and treating a headline as a contract is how invented endpoints get born.

Here is the ledger I keep while writing something like this:

ClaimSource typeStatus in this post
A HackerNoon tutorial with this title exists in the feedFeed entry (secondary)Reported by the seed; not independently verified
Reported publication date 2026-11-25Feed entryReported as-is, unverified
Knocket has an API with a specific endpoint, auth scheme, or SDKNone suppliedUnverified — treated as a prerequisite
sendMessage takes chat_id and text and returns okTelegram Bot API docs (primary)Confirmed
A 429 carries parameters.retry_afterTelegram Bot API docs (primary)Confirmed
Next.js 15 no longer caches GET Route Handlers by defaultNext.js 15 release notes (primary)Confirmed
Anything in the code belowMy implementationNot a provider statement

Everything else in this post that is not in that table is either a library behavior I cite to its docs or an implementation choice I am telling you I made.

Verify the Provider Contracts Before Writing Integration Code

Confirm Knocket's Identity and API Contract

I am not going to invent an SDK, an endpoint path, an auth header, or a delivery guarantee for Knocket. What I can tell you is the exact list of things to pull from its official documentation before a line of adapter code gets written:

  • Identity — what class of service is this? A notification broker, a webhook router, a workflow trigger? The answer changes the completion semantics.
  • Operation — is there a "create application" style call at all, or does the real product model look different?
  • Authentication — API key header, bearer token, HMAC-signed request, OAuth client credentials? The scheme decides whether you need signing code, which is not something you can bolt on later.
  • Request schema — required fields, field types, maximum lengths, and whether unknown fields are rejected or ignored.
  • Response envelope — is acceptance reported as an HTTP status, a body field, or both? Is there an identifier you can correlate against?
  • Documented limits — rate limits, payload caps, retention, and any stated SLA.

If the docs do not answer the response-envelope question, you do not have a contract. You have a guess with a base URL. An adapter built on a guess will "work" in a demo and misclassify every real failure.

Verify Telegram's sendMessage Contract

Telegram is the opposite situation: the contract is public and specific, so I can hold the implementation to it.

Per the Bot API sendMessage reference:

  • The endpoint is https://api.telegram.org/bot<token>/sendMessage. The bot token lives in the URL path, not in a header.
  • chat_id accepts an integer or a string channel username, and is required.
  • text is required and documented as 1–4096 characters after entity parsing.
  • parse_mode is optional. Set it, and you are opting into an escaping problem you now own.
  • The response body is JSON with an ok boolean. Success returns result containing the sent Message. Failure returns ok: false with error_code and description.
  • Failures may include a parameters object. The documented members include retry_after (present on 429) and migrate_to_chat_id.

The Making requests section is also worth reading once: it is where the "token is in the URL" design is stated plainly, which is the source of the logging hazard I deal with later.

Record Unresolved Knocket Details as Explicit Prerequisites

I am going to write a KnocketClient interface and put a mock behind it. That mock is useful for testing orchestration, error normalization, and partial-failure behavior. It is not evidence of Knocket compatibility, and I will not describe it as such.

⚠️

A passing test suite against a mock proves your orchestration is internally consistent. It proves nothing about the provider. If you ship and the mock was wrong about the response envelope, every failure will be misclassified and you will find out from a support ticket.

The prerequisites before replacing the mock are: verified auth scheme, verified endpoint, verified request schema, verified success/acceptance signal, and a documented idempotency story. That last one determines whether the retry section below can be automated at all.

Create a Reproducible Next.js 15 Project

Pin the Next.js 15 Toolchain

Next.js 15 requires React 19 and Node.js 18.18 or newer. I pin the patch in the lockfile rather than floating on latest, because a Route Handler's behavior depends on framework defaults that have moved between minor releases — most notably the caching changes described in the Next.js 15 release notes.

node --version
## v20.18.1

mkdir notify-boundary && cd notify-boundary
npx create-next-app@15 --ts --app --eslint --no-tailwind --no-src-dir --import-alias "@/*" .

Expected output (illustrative — this is the shape create-next-app produces, not a transcript from my run):

✔ Would you like to use Turbopack for `next dev`? … Yes
Success! Created notify-boundary

Then install the additions and record what you actually got:

npm install zod server-only
npm install -D vitest @types/node
npm ls next react react-dom zod server-only --depth=0
[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

Write those exact versions into your notes. "Next.js 15" is a range, not a version, and the difference between two patches has changed Route Handler defaults before.

Map the Example Across Server, Shared, and Client Files

app/
  page.tsx                  client form, no secrets
  api/notify/route.ts       validation, auth, rate limit, orchestration
server/
  config.ts                 server-only env schema
  knocket.ts                port interface + labeled mock
  telegram.ts               sendMessage adapter
  rate-limit.ts             per-user limiter (with caveats)
  log.ts                    structured logging + redaction
shared/
  contract.ts               request/response types and field limits
tests/
  notify.test.ts
  telegram.test.ts
  redaction.test.ts

The split is the point. shared/ contains no import "server-only" and no process.env reads, so it is safe in a client import graph. server/ contains both.

Define the Workflow and Completion Policy

This is where I see the most confusion, so I am stating it as policy:

  • Knocket acceptance means Knocket's API reported success according to its own contract. It does not mean the downstream thing happened.
  • Telegram acceptance means the Bot API returned ok: true and a message_id. It does not mean the human read it, and it does not mean a webhook you configured elsewhere fired.
  • End-user delivery is only claimable with evidence from whoever actually delivers, which for both providers is outside this code.

The handler therefore reports what it knows: complete, partial, or failed. It never says "delivered."

Isolate Credentials and Validate Server Configuration

Use Local Env and Deployment Secrets, Never NEXT_PUBLIC_

## .env.local — never committed
KNOCKET_MODE=mock
KNOCKET_BASE_URL=https://api.knocket.invalid
KNOCKET_API_KEY=knocket_sentinel_replace_me_0000
TELEGRAM_BOT_TOKEN=123456789:AAAA_sentinel_replace_me_0000000000000
TELEGRAM_CHAT_ID=-1001234567890
NOTIFY_TIMEOUT_MS=3000

.invalid is a reserved TLD, so a misconfigured non-mock deployment fails DNS resolution instead of quietly hitting something real.

The NEXT_PUBLIC_ prefix is not a naming convention — it is an instruction to inline the value into the client bundle at build time. Next.js's environment variable docs are explicit about this, and process.env references outside server code are not a hiding place either.

Validate With a Server-Only Config Module

// server/config.ts



const EnvSchema = z
  .object({
    KNOCKET_MODE: z.enum(["mock", "live"]).default("mock"),
    KNOCKET_BASE_URL: z.string().url(),
    KNOCKET_API_KEY: z.string().min(16),
    TELEGRAM_BOT_TOKEN: z.string().regex(/^\d+:[A-Za-z0-9_-]{30,}$/),
    TELEGRAM_CHAT_ID: z.string().regex(/^-?\d+$/),
    NOTIFY_TIMEOUT_MS: z.coerce.number().int().min(500).max(10_000).default(3000),
  })
  .refine((v) => !(process.env.NODE_ENV === "production" && v.KNOCKET_MODE === "mock"), {
    message: "KNOCKET_MODE cannot be mock in production",
    path: ["KNOCKET_MODE"],
  });

type Config = z.infer<typeof EnvSchema>;
let cached: Config | null = null;

export function getConfig(): Config {
  if (cached) return cached;
  const parsed = EnvSchema.safeParse(process.env);
  if (!parsed.success) {
    // Field paths only. Never the values, never the raw Zod error object.
    const fields = [...new Set(parsed.error.issues.map((i) => i.path.join(".") || "(root)"))];
    throw new Error(`Invalid server configuration: ${fields.join(", ")}`);
  }
  cached = parsed.data;
  return cached;
}

Two deliberate decisions here.

Validation is lazy, at request time, not at build time. A module-level throw at import time during next build will fail the build for a missing secret, which sounds good until your CI build has no production secrets and every pull request turns red. Lazy validation moves the failure to the first request, where a missing secret is an availability incident you can monitor rather than a build you learn to ignore.

The error message lists field names, not values. A validation error is a structured object that often captures the input. Log the whole Zod error, and you have just written a partial secret into your log aggregator.

Keep Shared Types Away from Credential Modules

The failure mode is unglamorous: someone adds a helper to shared/contract.ts, the helper imports server/config.ts for a constant, and a client component imports the contract type. import type is erased, so this compiles, and now the config module is in the client graph.

server-only turns that into a build error instead of a production leak:

The package is a single line that throws when resolved from a client environment, documented on npm. It is the cheapest guardrail in this entire post and I would put it in every module that reads process.env.

Data can still leak around the type. Watch these paths specifically:

  • Rendered props — passing a full server object into a client component serializes everything on it, not just the fields you destructure later.
  • API responses — NextResponse.json(error) where error is an upstream body.
  • Source maps — client chunk maps in .next/static are served if you enable them; they do not contain server code, but they do expose your client code shape.
  • Diagnostics — dev error overlays and console.log calls that ship.

Treat Telegram's Token-in-URL Design as a Logging Hazard

https://api.telegram.org/bot<token>/sendMessage means the credential is inside the request URL. Anything that records URLs records the token: fetch debug logging, an error reporter that captures request.url, an APM span name, a reverse proxy access log if the call were ever proxied, and console.error(err) where err carries the URL.

// server/log.ts
const TOKEN_IN_PATH = /\b\d+:[A-Za-z0-9_-]{30,}\b/g;
const TELEGRAM_URL = /https:\/\/api\.telegram\.org\/bot[^\s"')]+/g;

export function redact(value: unknown): unknown {
  if (typeof value === "string") {
    return value.replace(TELEGRAM_URL, "https://api.telegram.org/bot[REDACTED]/…").replace(TOKEN_IN_PATH, "[REDACTED_TOKEN]");
  }
  if (Array.isArray(value)) return value.map(redact);
  if (value && typeof value === "object") {
    return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redact(v)]));
  }
  return value;
}

export function logEvent(event: string, fields: Record<string, unknown> = {}) {
  console.log(JSON.stringify({ event, ...(redact(fields) as Record<string, unknown>) }));
}

Redaction is a backstop, not a licence to log request objects. The adapter below never puts the URL into a structured field in the first place.

Validate and Authorize the Next.js Route Handler

Bound and Strictly Validate the Request Body

// app/api/notify/route.ts (validation portion)



export const runtime = "nodejs";

const BodySchema = z
  .object({
    name: z.string().trim().min(1).max(MAX_NAME),
    email: z.string().trim().email().max(MAX_EMAIL),
    message: z.string().trim().min(1).max(MAX_MESSAGE),
  })
  .strict(); // unknown keys such as chatId are rejected, not silently dropped

const MAX_BODY_BYTES = 8 * 1024;

async function readBounded(req: Request, maxBytes: number): Promise<string | null> {
  const reader = req.body?.getReader();
  if (!reader) return "";
  const decoder = new TextDecoder();
  let received = 0;
  let out = "";
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    received += value.byteLength;
    if (received > maxBytes) {
      await reader.cancel();
      return null;
    }
    out += decoder.decode(value, { stream: true });
  }
  return out + decoder.decode();
}

.strict() matters more than it looks. Without it, a request containing chatId is accepted and the extra key is dropped — which is fine, until somebody "helpfully" threads the parsed object into the adapter and the client-supplied destination becomes real. Rejecting unknown keys makes that refactor impossible to do accidentally.

Reading with a byte counter rather than calling req.text() means an oversized body stops consuming memory at the cap instead of after it.

Use the Application Session You Already Have

The handler should call the application's existing session helper and check a server-side permission. If your form is genuinely public, say so and design for it — an explicit abuse-control plan (proof-of-work, CAPTCHA with server verification, per-IP and per-identity quotas) is a real design. A fabricated "auth" check that reads a header the client controls is not authentication, it is decoration.

Check Origin Without Confusing It With Authorization

Route Handlers do not get the same automatic protections as other Next.js primitives. Server Actions have a built-in Origin-versus-Host comparison controlled by serverActions.allowedOrigins; a Route Handler does not. For a cookie-authenticated endpoint you need your own check.

const ALLOWED_ORIGINS = new Set(["https://app.example.com"]);

function originAllowed(req: Request): boolean {
  const origin = req.headers.get("origin");
  const site = req.headers.get("sec-fetch-site");
  if (origin && !ALLOWED_ORIGINS.has(origin)) return false;
  if (site && site !== "same-origin") return false;
  return true;
}

An origin check is CSRF defense. It is not authorization, it does not stop a logged-in attacker, and CORS is not an access control at all — Access-Control-Allow-Origin governs whether browser JavaScript on another origin can read your response, not whether the request is allowed to have an effect. A server-to-server curl ignores CORS entirely.

Keep Provider Destinations Out of Browser-Controlled Input

The handler reads TELEGRAM_CHAT_ID, provider base URLs, and the Knocket operation from server config. None of these appear in the request schema, and .strict() enforces that. Add per-identity rate limiting and a request identifier:

// server/rate-limit.ts
const WINDOW_MS = 60_000;
const MAX_PER_WINDOW = 5;
const buckets = new Map<string, { count: number; resetAt: number }>();

export function checkRateLimit(key: string) {
  const now = Date.now();
  const bucket = buckets.get(key);
  if (!bucket || bucket.resetAt <= now) {
    buckets.set(key, { count: 1, resetAt: now + WINDOW_MS });
    return { allowed: true, retryAfter: 0 };
  }
  bucket.count += 1;
  if (bucket.count > MAX_PER_WINDOW) {
    return { allowed: false, retryAfter: Math.ceil((bucket.resetAt - now) / 1000) };
  }
  return { allowed: true, retryAfter: 0 };
}

This is a single-process Map. On a serverless platform every instance has its own, so the effective limit is MAX_PER_WINDOW × instance count, and it resets on every cold start. I am showing it because it is honest about what it is, not because it is sufficient. Production needs shared storage — Redis, a Postgres table with a unique constraint, or the platform's rate-limit primitive.

Implement Narrow Server-Only Provider Adapters

Build the Knocket Adapter Around a Port Interface Until the Contract Is Verified

Since there is no verified contract, the interface is the deliverable:

// server/knocket.ts


export type KnocketAcceptance =
  | { status: "accepted"; reference: string }
  | { status: "rejected"; reason: "invalid_request" | "unauthorized" }
  | { status: "unknown"; reason: "timeout" | "transport_error" | "invalid_response" };

export interface KnocketClient {
  createApplication(input: {
    idempotencyKey: string;
    applicant: { name: string; email: string; message: string };
  }): Promise<KnocketAcceptance>;
}

// ─────────────────────────────────────────────────────────────
// MOCK. Not a Knocket integration. The live contract — endpoint,
// auth scheme, request schema, and success signal — is unverified.
// Do not describe this as a working Knocket adapter.
// ─────────────────────────────────────────────────────────────
export function createMockKnocketClient(): KnocketClient {
  return {
    async createApplication({ idempotencyKey }) {
      await new Promise((resolve) => setTimeout(resolve, 25));
      return { status: "accepted", reference: `mock_${idempotencyKey.slice(0, 8)}` };
    },
  };
}

export function getKnocketClient(): KnocketClient {
  const { KNOCKET_MODE } = getConfig();
  if (KNOCKET_MODE === "mock") return createMockKnocketClient();
  throw new Error("KNOCKET_MODE=live but no verified client implementation exists");
}

When the contract is verified, the live client implements the same interface and the route handler does not change. That is the whole benefit of the port. It also means the three unknown categories are already plumbed through and you cannot accidentally ignore an ambiguous timeout.

Implement sendMessage With a Server-Owned Destination

// server/telegram.ts



const TIMEOUT_MS = 3_000;
const MAX_RESPONSE_BYTES = 8 * 1024;

export type TelegramResult =
  | { status: "sent"; messageId: number }
  | { status: "rate_limited"; retryAfter: number }
  | { status: "rejected"; errorCode: number; description: string }
  | { status: "timeout" }
  | { status: "transport_error"; code: string }
  | { status: "invalid_response"; reason: string };

type Payload = {
  ok?: unknown;
  result?: { message_id?: unknown };
  error_code?: unknown;
  description?: unknown;
  parameters?: { retry_after?: unknown };
};

export async function sendTelegramMessage(text: string): Promise<TelegramResult> {
  const { TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID } = getConfig();
  const url = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;

  let res: Response;
  try {
    res = await fetch(url, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ chat_id: TELEGRAM_CHAT_ID, text }), // no parse_mode
      signal: AbortSignal.timeout(TIMEOUT_MS),
      redirect: "error", // a followed redirect would replay the bot token to another host
      cache: "no-store",
    });
  } catch (err) {
    if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
      return { status: "timeout" };
    }
    return { status: "transport_error", code: transportCode(err) };
  }

  const body = await readBounded(res, MAX_RESPONSE_BYTES);
  if (body === null) return { status: "invalid_response", reason: "response_too_large" };

  let payload: Payload;
  try {
    payload = JSON.parse(body) as Payload;
  } catch {
    return { status: "invalid_response", reason: "not_json" };
  }

  if (res.status === 429) {
    const retryAfter = payload.parameters?.retry_after;
    if (typeof retryAfter === "number" && retryAfter > 0) return { status: "rate_limited", retryAfter };
    return { status: "invalid_response", reason: "429_without_retry_after" };
  }

  if (payload.ok !== true) {
    const errorCode = typeof payload.error_code === "number" ? payload.error_code : res.status;
    const description = typeof payload.description === "string" ? payload.description.slice(0, 200) : "unknown";
    return { status: "rejected", errorCode, description };
  }

  const messageId = payload.result?.message_id;
  if (typeof messageId !== "number") return { status: "invalid_response", reason: "missing_message_id" };

  return { status: "sent", messageId };
}

function transportCode(err: unknown): string {
  const cause = (err as { cause?: { code?: unknown } } | undefined)?.cause;
  if (cause && typeof cause.code === "string") return cause.code; // ENOTFOUND, ECONNREFUSED, …
  return err instanceof Error ? err.name : "unknown";
}

A few choices worth defending:

No parse_mode. Plain text means <, >, &, and * are literal characters. Bot API MarkdownV2 requires escaping a long list of reserved characters, and HTML mode requires escaping <, >, and &. Set either, and you own an escaping bug in a notification path where a mangled message stays invisible until someone complains. Text-only is the correct default here, and I would only opt in with a dedicated formatter and escaping tests.

redirect: "error". Not paranoia. fetch defaults to follow, and since the token is in the URL path, following a redirect to another host hands the credential to that host. Erroring out means a misdirected request fails loudly instead of leaking quietly.

AbortSignal.timeout. Node's fetch (undici) has generous default timeouts measured in minutes; those defaults exist for large downloads, not for a 40-character chat message. A 3-second abort is right for this call. The abort covers the response headers, and the body read is bounded separately.

Distinct failure categories. timeout, transport_error, rejected, rate_limited, and invalid_response are five different operational situations. A rejected with error_code: 400 means the bot token is real but the request is wrong — retrying is pointless. An invalid_response with not_json often means something between you and Telegram responded (a proxy, a captive portal) — that is a networking investigation, not a Telegram investigation. Collapsing them into one error string throws away the only information that matters at 3 a.m.

Normalize Provider Errors Without Leaking Upstream Bodies

I deliberately do not return the raw description field to the client. Telegram's description is human-readable and usually harmless, but "usually" is doing a lot of work in a response that goes to a browser. The handler receives the structured result and maps it to a safe category; the adapter's description goes to the server log only, truncated and redacted.

The same rule applies to the timeout cause: ENOTFOUND is a useful internal signal and a mildly useful reconnaissance signal externally. Keep it server-side.

Make Partial Failure and Retry Semantics Explicit

Orchestrate Knocket Before Telegram in a Documented Order

Knocket first, Telegram second. This is the correct order because Knocket is the operation of record — if it fails definitively, there is nothing worth notifying anyone about, and we skip the Telegram call entirely.

// app/api/notify/route.ts (orchestration portion)
const knocket = await getKnocketClient().createApplication({
  idempotencyKey: requestId,
  applicant: parsed.data,
});

if (knocket.status !== "accepted") {
  logEvent("knocket_not_accepted", { requestId, category: knocket.status });
  return NextResponse.json(
    { status: "failed", requestId, reason: "provider_unavailable" } satisfies NotifyResponse,
    { status: 502 },
  );
}

const text = [
  `New application ${requestId}`,
  `${parsed.data.name} <${parsed.data.email}>`,
  parsed.data.message.slice(0, 400),
].join("\n");

const telegram = await sendTelegramMessage(text);

if (telegram.status === "sent") {
  logEvent("notify_complete", { requestId, telegramMessageId: telegram.messageId });
  return NextResponse.json({ status: "complete", requestId } satisfies NotifyResponse, { status: 200 });
}

logEvent("telegram_not_sent", { requestId, category: telegram.status });
return NextResponse.json(
  { status: "partial", requestId, reason: "notification_failed" } satisfies NotifyResponse,
  { status: 202 },
);

Note the truncated message body in the Telegram text. sendMessage caps at 4096 characters after entity parsing, and my schema caps message at 1000, so this particular slice is not load-bearing — but it documents where the boundary is. Raise MAX_MESSAGE, and that slice becomes the thing preventing a 400.

The result matrix:

KnocketTelegramHTTPPublic statusReal-world state
acceptedsent200completeApplication recorded, operator notified
acceptedrejected (4xx)202partialApplication recorded, nobody notified
acceptedtimeout202partialApplication recorded, notification status unknown
acceptedrate_limited202partialApplication recorded, notification dropped
rejected (definitive)not attempted502failedNothing happened
timeout / unknownnot attempted502failedApplication state unknown

That last row is the one that keeps me up. A 502 with failed is a lie if Knocket timed out after accepting the request. The honest mapping is to return 502 for the HTTP layer (so the client knows the operation did not complete from its perspective) while logging the internal unknown category, and to make sure the client message does not say "nothing was saved."

⚠️

If your UI shows "Something went wrong, please try again" after an ambiguous timeout, you have built an automatic duplicate-submission machine. The retry is initiated by the user, and the server has no idea the first attempt landed.

A Timeout Does Not Prove the Operation Failed

This is the single most important sentence in the post for anyone integrating two providers: a timeout means you did not receive the response, not that the operation did not happen.

The failure window is real. The request can arrive, be accepted, be committed, and the response can be lost to a connection reset, a load balancer timeout, or an abort that fired 200 ms too early. From the client's perspective it is indistinguishable from a request that never arrived.

Blind retries on ambiguous outcomes create duplicate Knocket operations and duplicate Telegram notifications. The second is annoying. The first may be a duplicate application, a double charge, or a double shipment depending on what the operation actually does — which is exactly why "what does the response envelope look like" was on the prerequisite list.

Use Documented Idempotency, or No Automatic Retry

If and only if Knocket documents an idempotency mechanism — an Idempotency-Key header with a stated retention window, or a client-supplied unique operation id with documented deduplication — then replaying a timeout with the same key is safe, and the handler can retry automatically within that window.

If the docs do not state it, you have two distinct things that must not be conflated:

  • Application-level deduplication — a unique constraint on (user_id, request_id) in your own database, or a short-lived set of recently-seen idempotency keys. This stops your handler from processing the same submission twice. It says nothing about what the provider did with the first attempt.
  • Provider-side idempotency — a guarantee from the provider that two requests with the same key produce one effect. Only the provider can offer this.

I use requestId as the idempotency key in the mock, which is honest about being a placeholder. In the live client, the key must be whatever the verified contract specifies.

The default policy I would ship: no automatic retry on unknown. Surface the ambiguity, log it with the request identifier, and let an operator reconcile.

Handle Telegram Rate Limits With the Documented retry_after Field

429 with parameters.retry_after is the documented signal. The value is in seconds.

For a notification path, I would not sleep in-request. retry_after can legally be tens of seconds, and holding a serverless function open for that risks a platform timeout that loses the work entirely while also costing money. The right move is to hand the notification to a durable queue with a delayed visibility timeout of retry_after seconds, and return partial to the client immediately.

If you do retry inline, the rules are: bounded attempts (Telegram's Bots FAQ discusses broadcast limits, and the per-chat limits are the ones that matter for a single destination), honor retry_after exactly rather than inventing backoff, and never launch an unawaited promise — an unawaited sendTelegramMessage() in a serverless environment is a coin flip on whether the runtime freezes it before it completes.

Connect the Client Without Expanding Its Authority

Build a Minimal Client Form With No Provider Knobs

// app/page.tsx
"use client";



type State = { kind: "idle" } | { kind: "pending" } | { kind: "done"; result: NotifyResponse };

export default function Page() {
  const [state, setState] = useState<State>({ kind: "idle" });

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (state.kind === "pending") return;
    const data = new FormData(event.currentTarget);
    setState({ kind: "pending" });
    try {
      const res = await fetch("/api/notify", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          name: data.get("name"),
          email: data.get("email"),
          message: data.get("message"),
        }),
      });
      setState({ kind: "done", result: (await res.json()) as NotifyResponse });
    } catch {
      setState({ kind: "done", result: { status: "failed", requestId: "unknown", reason: "provider_unavailable" } });
    }
  }

  const pending = state.kind === "pending";
  return (
    <form onSubmit={onSubmit} noValidate>
      <input name="name" required disabled={pending} />
      <input name="email" type="email" required disabled={pending} />
      <textarea name="message" required disabled={pending} />
      <button type="submit" disabled={pending}>{pending ? "Sending…" : "Send application"}</button>
      {state.kind === "done" && <ResultPanel result={state.result} />}
    </form>
  );
}

The client sends exactly three fields. It does not send a chat identifier, a provider URL, or an operation name, because the server has no code path that would read them.

Return a Stable Public Response Contract

// shared/contract.ts
export const MAX_NAME = 80;
export const MAX_EMAIL = 254;
export const MAX_MESSAGE = 1000;

export type NotifyResponse =
  | { status: "complete"; requestId: string }
  | { status: "partial"; requestId: string; reason: "notification_failed" }
  | { status: "failed"; requestId: string; reason: "provider_unavailable" }
  | {
      status: "rejected";
      requestId: string;
      code: "invalid_input" | "unauthorized" | "rate_limited" | "bad_origin";
      fields?: string[];
    };

Representative exchanges:

POST /api/notify HTTP/1.1
Content-Type: application/json
Origin: https://app.example.com
Cookie: session=…

{"name":"Ada","email":"[email protected]","message":"Billing question"}
HTTP/1.1 200 OK
Content-Type: application/json

{"status":"complete","requestId":"0f5f0b9e-2f0c-4b5e-8f2a-9a6c1a1d1e11"}
HTTP/1.1 202 Accepted
Content-Type: application/json

{"status":"partial","requestId":"1a7c3d20-8e41-4f88-9b2c-77d0e5a2b314","reason":"notification_failed"}
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{"status":"rejected","requestId":"2b8d4e31-9f52-4a99-8c3d-88e1f6b3c425","code":"invalid_input","fields":["email"]}

Note what is absent from every response: the bot token, chat_id, the Knocket reference, the Telegram description, and any stack trace. The requestId is the only correlation handle the client gets, and it is the one support actually needs.

For a rejected-because-rate-limited response, set Retry-After to the limiter's retryAfter.

Prevent Repeat Submissions Without Relying on the Button

Disabling the button while pending is correct and does not solve the problem. The disabled attribute lives in a React tree a determined user can bypass, a flaky network can defeat (the response never arrives, the state resets, the user clicks again), and a second tab ignores entirely.

Server-side deduplication and rate limiting are the actual controls. The button is a courtesy.

Test the External-Service Boundaries Without Live Credentials

Intercept All Outbound Calls and Fail on Surprises

I use Vitest with undici's MockAgent, which intercepts the global fetch used by Node 18+. disableNetConnect() is the important line: any request without a matching interceptor throws, so a test that "accidentally" calls the real Telegram API fails instead of succeeding and slowly getting your bot banned.

// tests/setup.ts



let original: Dispatcher;
export let agent: MockAgent;

beforeEach(() => {
  original = getGlobalDispatcher();
  agent = new MockAgent();
  agent.disableNetConnect();
  setGlobalDispatcher(agent);
  process.env.KNOCKET_MODE = "mock";
  process.env.KNOCKET_BASE_URL = "https://api.knocket.invalid";
  process.env.KNOCKET_API_KEY = "knocket_sentinel_do_not_use";
  process.env.TELEGRAM_BOT_TOKEN = "123456789:SENTINEL_TOKEN_0000000000000000";
  process.env.TELEGRAM_CHAT_ID = "-1001234567890";
});

afterEach(async () => {
  setGlobalDispatcher(original);
  await agent.close();
});

disableNetConnect() covers the global dispatcher but not a fetch that was given its own dispatcher or a raw https.request. If your adapter uses undici.request directly, or an SDK with its own HTTP client, you need a second net. The test suite should also assert that the process has no live credentials in the environment — a CI check that TELEGRAM_BOT_TOKEN does not start with a real bot id is cheap insurance.

Cover the Rejection Paths and Assert Zero Provider Calls

The pattern: register no interceptors, make the request, expect a rejection status. If the handler reaches for a provider, MockAgent throws and the test fails with a network error rather than passing silently.

// tests/notify.test.ts (selection)



const good = { name: "Ada", email: "[email protected]", message: "Hello" };

function post(body: string, headers: Record<string, string> = {}) {
  return POST(
    new Request("https://app.example.com/api/notify", {
      method: "POST",
      body,
      headers: { "content-type": "application/json", origin: "https://app.example.com", "sec-fetch-site": "same-origin", ...headers },
    }),
  );
}

describe("request rejections make zero provider calls", () => {
  it("rejects malformed JSON", async () => {
    const res = await post("{not json");
    expect(res.status).toBe(400);
    expect((await res.json()).status).toBe("rejected");
  });

  it("rejects oversized bodies", async () => {
    const res = await post(JSON.stringify({ ...good, message: "x".repeat(20_000) }));
    expect(res.status).toBe(413);
  });

  it("rejects client-supplied chatId", async () => {
    const res = await post(JSON.stringify({ ...good, chatId: "-1009999999999" }));
    expect(res.status).toBe(422);
    expect((await res.json()).fields).toContain("chatId");
  });

  it("rejects cross-site origins", async () => {
    const res = await post(JSON.stringify(good), { origin: "https://evil.example" });
    expect(res.status).toBe(403);
  });
});

That chatId test is the one I would keep forever. It is a direct assertion that the browser cannot redirect the notification, and it will fail the moment somebody relaxes .strict() or threads the parsed body into the adapter.

Cover Provider Failures and Partial Success

describe("telegram outcomes", () => {
  it("maps ok:false to a partial result", async () => {
    agent
      .get("https://api.telegram.org")
      .intercept({ path: /\/bot.*\/sendMessage$/, method: "POST" })
      .reply(400, { ok: false, error_code: 400, description: "Bad Request: chat not found" });

    const res = await post(JSON.stringify(good));
    expect(res.status).toBe(202);
    expect(await res.json()).toMatchObject({ status: "partial", reason: "notification_failed" });
  });

  it("reads retry_after from a 429", async () => {
    agent
      .get("https://api.telegram.org")
      .intercept({ path: /\/bot.*\/sendMessage$/, method: "POST" })
      .reply(429, { ok: false, error_code: 429, description: "Too Many Requests", parameters: { retry_after: 17 } });

    const res = await post(JSON.stringify(good));
    expect(await res.json()).toMatchObject({ status: "partial" });
  });

  it("treats a 200 with no message_id as invalid_response", async () => {
    agent
      .get("https://api.telegram.org")
      .intercept({ path: /\/bot.*\/sendMessage$/, method: "POST" })
      .reply(200, { ok: true, result: {} });

    const res = await post(JSON.stringify(good));
    expect(await res.json()).toMatchObject({ status: "partial" });
  });

  it("does not call telegram when knocket is not accepted", async () => {
    // no interceptors registered: any outbound call throws
    // force the mock to reject via a test double
    // …assert 502 and that no interceptor was consumed
  });
});

The last test needs the mock to be swappable — pass a KnocketClient through a factory or use vi.mock("@/server/knocket"). Either way, the assertion is the same: partial must not appear when the operation of record failed, and no Telegram request may be made.

Assert Redaction With Sentinel Credentials

// tests/redaction.test.ts



describe("redaction", () => {
  it("strips the bot token from URLs", () => {
    const out = redact("POST https://api.telegram.org/bot123456789:SENTINEL_TOKEN_0000000000000000/sendMessage");
    expect(out).not.toContain("SENTINEL_TOKEN");
  });

  it("never logs sentinel values through logEvent", () => {
    const spy = vi.spyOn(console, "log").mockImplementation(() => {});
    logEvent("telegram_failed", { url: "https://api.telegram.org/bot123456789:SENTINEL_TOKEN_0000000000000000/sendMessage" });
    const line = spy.mock.calls[0][0] as string;
    expect(line).not.toContain("SENTINEL_TOKEN");
    expect(line).toContain("telegram_failed");
  });
});

Use a distinctive sentinel string — SENTINEL_TOKEN_… — rather than a plausible-looking token. A realistic fake token is exactly what someone will later paste into a real environment.

Prove Server-Only Modules Cannot Enter a Client Graph

// tests/import-graph.test.ts


describe("server modules", () => {
  it("refuses to import from a client environment", async () => {
    vi.stubEnv("NODE_ENV", "production");
    // server-only resolves to an error module when the react-server condition is absent
    await expect(import("server-only")).rejects.toThrow();
    vi.unstubAllEnvs();
  });
});

This is a weak proxy for the real check, which is the build itself: server-only throws during next build when the module is pulled into a client bundle. The build is the authoritative test; this unit test is a faster failure.

Run the Boundary Test Suite

npx vitest run

Expected output (illustrative — this is the shape Vitest produces for the tests above, not a transcript from my run):

 ✓ tests/notify.test.ts (12 tests) 388ms
 ✓ tests/telegram.test.ts (6 tests) 145ms
 ✓ tests/redaction.test.ts (2 tests) 19ms
 ✓ tests/import-graph.test.ts (1 test) 24ms

 Test Files  4 passed (4)
      Tests  21 passed (21)
   Duration  1.24s

I am labeling that as expected rather than observed, because I ran these against a mock and a partially written suite, and reporting a number I did not measure is exactly the failure mode this whole post is arguing against.

Verify Production Builds and Run a Controlled Live Smoke Test

Build With Sentinel Credentials and Search the Client Artifacts

NEXT_TELEMETRY_DISABLED=1 \
KNOCKET_MODE=mock \
KNOCKET_BASE_URL=https://api.knocket.invalid \
KNOCKET_API_KEY=knocket_sentinel_buildtime \
TELEGRAM_BOT_TOKEN=123456789:BUILD_SENTINEL_0000000000000000 \
TELEGRAM_CHAT_ID=-1001234567890 \
npx next build

Then search only the browser-served artifacts:

grep -rl "BUILD_SENTINEL" .next/static || echo "clean: sentinel absent from .next/static"
grep -rl "knocket_sentinel_buildtime" .next/static || echo "clean: knocket key absent from .next/static"
clean: sentinel absent from .next/static
clean: knocket key absent from .next/static

A clean grep is supporting evidence, not proof. Here is what it does and does not establish:

ObservationEstablishesDoes not establish
Sentinel absent from .next/staticThe literal string was not inlined into client chunksThat no secret reaches the browser by another path
Sentinel absent from the HTML responseNot in the rendered RSC payload for that requestThat no other route serializes it
Sentinel absent from the API responseNot in that handler's outputThat error paths never echo it

To get closer, add a runtime test that fetches the page HTML and the API response for a known request, then greps both for the sentinel. That covers the rendered-props path, which is the one a static grep cannot see.

Run a Manual Smoke Test, Deliberately Separate From CI

This is a manual procedure. It does not run in npm test, it needs credentials you must not print, and it should be documented in a runbook rather than a spec file.

  1. Deploy to a staging environment with real secrets from the platform's secret store.
  2. Point TELEGRAM_CHAT_ID at a private test chat you control, not the production channel.
  3. Submit one application through the UI.
  4. Capture the requestId from the response and the structured log lines for that identifier.
  5. Check the test chat for the message.

For the curl step, keep the credential out of the command line — shell history and process listings are both logs:

curl -s -X POST "$APP_ORIGIN/api/notify" \
  -H 'content-type: application/json' \
  -H "origin: $APP_ORIGIN" \
  -H "sec-fetch-site: same-origin" \
  -b "$SESSION_COOKIE" \
  -d '{"name":"Smoke","email":"[email protected]","message":"smoke test"}'
{"status":"complete","requestId":"3c9e5f42-a063-4baa-9d4e-99f2a7c4d536"}

Compare Four Observations and Say What Each Proves

ObservationWhat it establishes
Browser received {"status":"complete"}The handler ran to the end without an exception
Redacted server events show knocket_not_accepted absentKnocket did not report a definitive failure
Provider acknowledgment (message id in the event log)Telegram returned ok: true with a message_id
Message visible in the test chatThat chat received a message matching that text

Only the fourth is evidence of human-visible delivery, and even it does not generalize: it is one message to one chat on one day. If the message appears but the log has no message_id, something is wrong with your response parsing and you should not trust the complete status.

If any observation is missing, do not upgrade the status. A missing log line is not a pass.

Check Deployment Prerequisites Before Enabling Real Users

  • Secret availability — does the runtime actually see TELEGRAM_BOT_TOKEN, or does your platform inject secrets only into a build step?
  • Outbound connectivity — a VPC with egress restrictions will fail at ENOTFOUND or ECONNREFUSED, and your unknown category will mask it as an ambiguous provider failure.
  • Function duration — the Knocket call plus the Telegram call plus a retry budget must fit inside your platform's timeout with margin.
  • Shared rate-limit storage — the in-memory Map above does not survive a second instance. Wire a real store before launch.
  • Credential rotation — the Telegram token can be regenerated via BotFather; anything currently deployed keeps working until it does not. Know your rotation path before you need it.
  • Queue requirement — if notification delivery must be reliable, you need a durable queue. That is a different architecture, and it should be a decision, not a discovery.

Ship the Boundary, Not Just the Happy Path

Acceptance Criteria for the Integration Boundary

I would not consider this integration done until all of the following hold:

  • No credential appears in .next/static, rendered HTML, or any API response.
  • Every provider contract used by the adapters is verified against that provider's own documentation, and anything unverified is labeled a mock in code.
  • The handler enforces a bounded strict schema, an authorization check, an origin policy, rate limiting, and a request identifier.
  • Destination, provider URL, and operation selection are unreachable from browser input, with a test that proves it.
  • Partial failure and ambiguous timeout are distinct outcomes, with documented HTTP statuses for each.
  • Every log line passes through redaction, with tests using distinctive sentinel values.
  • Boundary tests fail closed: no unexpected outbound request can succeed in the suite.

Remaining Limits of Mock Tests and Provider Acceptance

  • Mock tests do not establish live Knocket compatibility. They establish that my orchestration handles the outcomes I anticipated. If Knocket's actual response differs, every classification downstream is wrong.
  • Provider acceptance is not delivery. ok: true and a message_id mean Telegram accepted the message for the chat. It does not mean a human read it, and it does not cover whatever Knocket does after it returns 200.
  • Application deduplication is not exactly-once execution. A unique constraint on my side prevents me from processing one submission twice. It cannot undo a provider-side effect from an attempt whose response I never saw.

The boundary is the deliverable. The credentials are the easy part.

Further Reading and Verification Sources

On the Source Material

The context for this post is a HackerNoon tutorial, "How to Integrate Knocket and Telegram With Next.js 15," which the feed entry reports as published 2026-11-25T03:51:24Z. The link I was given is a Google News RSS redirect, not a canonical article URL, so I have not linked it — I would rather cite nothing than send you to an unverified destination. Once the canonical URL is resolved and the article's claims are checked against provider documentation, it belongs here as a secondary source, not as an API reference.

On Telegram

On Next.js and Node

Share this post

More posts

Loading comments…