-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextjs-middleware.js
More file actions
57 lines (50 loc) · 1.7 KB
/
Copy pathnextjs-middleware.js
File metadata and controls
57 lines (50 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Next.js App Router — edge/server middleware example.
*
* Place this file at the root of your Next.js project as `middleware.js`.
* It fires on every matched request and logs one entry to the ingestor.
*
* Required env vars: STREAMLOGIA_API_KEY, STREAMLOGIA_PROJECT_ID
*
* Note: Next.js middleware runs on the Edge Runtime, so use `fetch` directly
* (the SDK's built-in fetch works fine there).
*/
import { NextResponse } from "next/server";
const INGESTOR_URL = 'https://api.streamlogia.com';
const API_KEY = process.env.STREAMLOGIA_API_KEY;
const PROJECT_ID = process.env.STREAMLOGIA_PROJECT_ID;
export async function middleware(request) {
const start = Date.now();
const response = NextResponse.next();
// We can't hook into response.finish in edge middleware, so we log the
// incoming request here and attach timing in the header for the client.
const entry = {
projectId: PROJECT_ID,
level: "INFO",
message: `${request.method} ${request.nextUrl.pathname}`,
source: "nextjs-edge",
timestamp: new Date().toISOString(),
tags: ["http", "nextjs"],
meta: {
method: request.method,
path: request.nextUrl.pathname,
durationMs: Date.now() - start,
userAgent: request.headers.get("user-agent"),
},
};
// Fire-and-forget — don't block the response
fetch(`${INGESTOR_URL}/v1/ingest`, {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify([entry]),
}).catch(() => {
// Silently swallow — never let logging break the request
});
return response;
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};