Skip to content

Commit

Permalink
docs: middleware metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
Tymek committed Oct 17, 2024
1 parent 63536cb commit 9b0cd19
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,21 @@ export default async function Page() {
}
```

## Next.js middleware

In `middleware.ts` you can use [`event.waitUntil()`](https://nextjs.org/docs/app/building-your-application/routing/middleware#waituntil-and-nextfetchevent) to reliably send metrics without delaying the response.

```tsx
export async function middleware(req: NextRequest, event: NextFetchEvent) {
// ...
const evaluated = evaluateFlags(definitions, context);
const flags = flagsClient(evaluated.toggles)
const isEnabled = flags.isEnabled("example-flag")

event.waitUntil(flags.sendMetrics())
// ...
}
```

## `setInterval` support (e.g. long-running Node process or AWS lambda)

Expand Down Expand Up @@ -436,5 +451,4 @@ npx @unleash/nextjs generate-types ./unleash.ts

# Known limitation

- In current interation **server-side SDK does not support metrics**.
- When used server-side, this SDK does not support the "Hostname" and "IP" strategies. Use custom context fields and constraints instead.
10 changes: 6 additions & 4 deletions example/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from "next/server";
import { type NextFetchEvent, type NextRequest, NextResponse } from "next/server";
import { UNLEASH_API_PROXY_DEFINITIONS, UNLEASH_COOKIE_NAME } from "./utils";
import { addBasePath } from "next/dist/client/add-base-path";
import { flagsClient, evaluateFlags, randomSessionId } from "@unleash/nextjs";
Expand All @@ -7,7 +7,7 @@ export const config = {
runtime: "experimental-edge",
};

export async function middleware(req: NextRequest) {
export async function middleware(req: NextRequest, event: NextFetchEvent) {
const sessionId =
req.cookies.get(UNLEASH_COOKIE_NAME)?.value || randomSessionId();
let res: NextResponse;
Expand All @@ -26,18 +26,20 @@ export async function middleware(req: NextRequest) {

// Evaluate based on provided context
const evaluated = evaluateFlags(definitions, context);
const variant = flagsClient(evaluated.toggles).getVariant("example-flag")
const flags = flagsClient(evaluated.toggles)
const variant = flags.getVariant("example-flag")
?.payload?.value;

const newUrl = req.nextUrl.clone();
// Redirect to variant
newUrl.pathname = `/ab/${variant === "a" ? "a" : "b"}`;
res = NextResponse.rewrite(newUrl);

event.waitUntil(flags.sendMetrics()) // Experimental, since 1.5.0-beta.3
}
else {
res = NextResponse.next();
}
res.cookies.set(UNLEASH_COOKIE_NAME, sessionId);
return res;
}

0 comments on commit 9b0cd19

Please sign in to comment.