Edge Authentication in DeskcommCRM: How Request IDs Are Handled

DeskcommCRM implements edge authentication in the proxy.ts middleware, which validates JWT tokens via Supabase and propagates Request IDs by checking for an incoming X-Request-Id header or generating a UUID via crypto.randomUUID(), then injecting it into response headers and downstream requests.

The DeskcommCRM repository by melgarafael uses a Next.js edge runtime architecture to secure all incoming requests before they reach route handlers or server actions. This article examines the specific implementation files where edge authentication occurs and traces how the Request ID flows through the system for logging and tracing purposes.

Where Edge Authentication Lives: The proxy.ts Middleware

All edge authentication logic resides in proxy.ts, the catch-all middleware that intercepts every request (except static assets). This file serves as the single security checkpoint for the entire application.

JWT Validation at the Edge

The middleware creates a Supabase server client using createServerClient from @supabase/ssr and immediately validates the user's JWT:

const supabase = createServerClient(
  env.NEXT_PUBLIC_SUPABASE_URL,
  env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
  { /* cookie handling omitted for brevity */ },
);

const { data: { user } } = await supabase.auth.getUser();

The supabase.auth.getUser() method reads the sb-deskcomm-auth cookie containing the JWT and verifies it against Supabase's auth service. According to the DeskcommCRM source code, this is the only location where JWT verification occurs; all downstream route handlers assume the user object is already validated.

Handling Unauthenticated Requests

When user is null, the middleware implements differentiated responses based on the request path:

  • API routes (/api/*): Returns a JSON envelope with error.code = "unauthenticated" and HTTP 401 status
  • UI routes: Redirects to /login while preserving the original path in the next query parameter

Additional Edge-Only Security Checks

Beyond JWT validation, proxy.ts performs two additional edge-specific verifications:

Impersonation Cookie Validation: For paths starting with /app, the middleware calls verifyImpersonateCookieEdge from lib/impersonate/cookie-edge.ts. This function uses Web-Crypto HMAC verification (via crypto.subtle.sign) to validate the impersonation token without Node.js-specific crypto modules.

Platform-Admin Guard: For /admin/* paths, the middleware queries Supabase via RPC fn_is_platform_admin to ensure only platform administrators access administrative functions.

How the Request ID Is Generated and Propagated

The Request ID lifecycle begins and ends within the same proxy.ts middleware, ensuring consistent tracing across the distributed edge runtime.

Request ID Generation in proxy.ts

The middleware first inspects the incoming headers for an existing X-Request-Id value. If absent, it generates a fresh UUID:

const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
response.headers.set("x-request-id", requestId);

This guarantees that every response exiting the edge carries the x-request-id header, whether the client provided one or the edge generated it.

Passing the Request ID Downstream

The Request ID propagates through the system via multiple channels:

  • Response headers: Set via response.headers.set("x-request-id", requestId) for client-side correlation
  • API payloads: Route handlers in app/api/v1/* include "x-request-id": requestId in JSON bodies sent to external services
  • Server Actions: Internal actions read the header via request.headers.get("x-request-id") and forward it to Supabase RPC calls for audit logging

Code Implementation Details

Here are the critical implementation sections from the DeskcommCRM source code that demonstrate these patterns in practice.

Complete Edge Middleware Pattern

// proxy.ts – main edge middleware
export async function proxy(request: NextRequest) {
  const response = NextResponse.next({ request: { headers: request.headers } });

  // ---- Request‑ID -------------------------------------------------
  const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
  response.headers.set("x-request-id", requestId);

  // ---- JWT validation ---------------------------------------------
  const supabase = createServerClient(
    env.NEXT_PUBLIC_SUPABASE_URL,
    env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
    { /* cookie handling omitted for brevity */ },
  );

  const { data: { user } } = await supabase.auth.getUser();

  if (!user) {
    // API → JSON error, UI → redirect to login
    if (pathname.startsWith("/api/")) {
      return new NextResponse(
        JSON.stringify({ error: { code: "unauthenticated", message: "Authentication required" } }),
        { status: 401, headers: { "content-type": "application/json", "x-request-id": requestId } },
      );
    }
    const loginUrl = new URL("/login", request.url);
    loginUrl.searchParams.set("next", pathname + search);
    return NextResponse.redirect(loginUrl);
  }

  // ---- Impersonate cookie (edge‑only) ----------------------------
  if (pathname.startsWith("/app")) {
    const impCookie = request.cookies.get(IMPERSONATE_COOKIE_NAME_EDGE)?.value;
    if (impCookie) {
      const result = await verifyImpersonateCookieEdge(impCookie, env.IMPERSONATE_COOKIE_SECRET ?? "");
      if (!result.valid) response.cookies.delete(IMPERSONATE_COOKIE_NAME_EDGE);
    }
  }

  // …additional admin checks…

  return response;
}

Edge-Runtime Impersonation Verification

The lib/impersonate/cookie-edge.ts file implements HMAC verification using the Web Crypto API, which is required for edge runtime compatibility:

// lib/impersonate/cookie-edge.ts
export async function verifyImpersonateCookieEdge(token: string, secret: string): Promise<EdgeVerifyResult> {
  if (!secret || secret.length < 32) return { valid: false, reason: "missing_secret" };

  const [payloadB64, sigB64] = token.split(".");
  if (!payloadB64 || !sigB64) return { valid: false, reason: "malformed" };

  const providedSig = b64urlToBytes(sigB64);
  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const expectedSig = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payloadB64)));

  if (!constantTimeEqual(providedSig, expectedSig)) return { valid: false, reason: "invalid_signature" };

  const payload = JSON.parse(new TextDecoder().decode(b64urlToBytes(payloadB64))) as ImpersonatePayload;
  if (payload.exp <= Math.floor(Date.now() / 1000)) return { valid: false, reason: "expired" };

  return { valid: true, payload };
}

Consuming the Request ID in Server Actions

Downstream handlers retrieve the propagated ID from request headers:

// app/actions/settings/updateProfile.ts
export async function updateProfile(_: any, request: Request) {
  const hdrs = new Headers(request.headers);
  const requestId = hdrs.get("x-request-id"); // <- propagated from proxy
  await supabase.rpc("fn_update_profile", { /* … */ }, { headers: { "x-request-id": requestId } });
}

Summary

  • Edge authentication is centralized in proxy.ts, which runs on every request and validates JWTs via supabase.auth.getUser() using the sb-deskcomm-auth cookie.
  • Unauthenticated requests receive differentiated treatment: API calls return JSON 401 errors, while UI routes redirect to /login.
  • Impersonation security uses lib/impersonate/cookie-edge.ts with Web-Crypto HMAC verification compatible with the edge runtime.
  • Request IDs are generated via crypto.randomUUID() if missing, then injected into response headers and forwarded to downstream services for correlation and audit logging.

Frequently Asked Questions

Where is the JWT actually verified in DeskcommCRM?

The JWT is verified exclusively in proxy.ts through the supabase.auth.getUser() method. This edge middleware creates a Supabase server client and validates the token from the sb-deskcomm-auth cookie. All other parts of the codebase assume the user object returned by this middleware is trustworthy.

How does the Request ID get passed to external APIs?

Route handlers in app/api/v1/* extract the Request ID from the incoming request headers and include it in JSON payloads sent to external services. For example, when calling third-party agenda APIs, the handler adds "x-request-id": requestId to the request body, ensuring external systems can correlate the edge request with their internal logs.

If verifyImpersonateCookieEdge in lib/impersonate/cookie-edge.ts determines the impersonation cookie has an invalid signature or is expired, the middleware immediately deletes the cookie from the response via response.cookies.delete(IMPERSONATE_COOKIE_NAME_EDGE). This prevents stale or tampered impersonation tokens from persisting across requests.

Can I rely on the x-request-id header being present in all responses?

Yes. The proxy.ts middleware guarantees that every response includes the x-request-id header. If the client does not provide one, the edge generates a fresh UUID using crypto.randomUUID() and sets it via response.headers.set("x-request-id", requestId) before the response leaves the edge runtime.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →