# WatchTower15 in Next.js

```sh
npm install @watchtower15/sdk next react react-dom
```

This recipe is the app in the SDK’s `examples/nextjs/`, which the SDK’s test suite builds with `next build` and runs on Node 24 against the test fakes. Use the SDK in **server code only**: route handlers, server actions and server components. A client component would ship your credentials to the browser, and the SDK refuses to be built where `window.document` exists.

```js
import { Aggregator, WatchTower15 } from '@watchtower15/sdk';

let shared;
const processMetrics = () => (shared ??= new Aggregator({ client: WatchTower15.fromEnvironment(), allowList: { 'orders.created': 'count' } }));

export function createHandler({ after, metrics = processMetrics() }) {
  return async function POST() {
    metrics.increment('orders.created');
    after(() => metrics.flush({ final: true }));
    return Response.json({ created: true }, { status: 201 });
  };
}
```

```js
import { after } from 'next/server';
import { createHandler } from '../../../lib/orders.mjs';

export const POST = createHandler({ after });
```

`after()` runs the flush once the response is sent, so the request is not slowed and a serverless instance does not freeze before the counts leave. One aggregator per process; `flush({ final: true })` sends the open minute too. See [Serverless](https://developer.watchtower15.com/sdks/node/serverless/).

Source: https://developer.watchtower15.com/sdks/node/nextjs/
