Skip to content

Commit

Permalink
chre: added x-request-id
Browse files Browse the repository at this point in the history
  • Loading branch information
xgovernor committed Jan 30, 2024
1 parent d3147cf commit 9d5beac
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,37 @@
import { NextRequest, NextResponse } from "next/server";

function generateHybridId(request: any) {
// Timestamp:
const timestamp = Date.now();

// IP address (if available in request headers):
const ipAddress =
request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip");
const ipHash = ipAddress ? ipAddress.split(".").slice(0, 2).join("") : ""; // Use first two octets

// Device ID (using a custom random string generator):
const deviceId = generateRandomDeviceId();

return `${timestamp}${ipHash}${deviceId}`;
}

function generateRandomDeviceId() {
const characters = "abcdef0123456789";
let result = "";
for (let i = 0; i < 6; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}

export default function middleware(req: NextRequest) {
// User agent information
// const agent = userAgent(req);
// console.log(agent);

// Request ID
const requestId = generateHybridId(req); // Use your preferred ID generation method
req.headers.set("x-request-id", requestId);

return NextResponse.next();
}
5 changes: 5 additions & 0 deletions src/utils/id.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// import { v4 as uuidv4 } from "uuid"; // Import a reliable ID generation library

// export function generateHybridId() {
// return uuidv4(); // Generate a unique request ID
// }

1 comment on commit 9d5beac

@vercel
Copy link

@vercel vercel bot commented on 9d5beac Jan 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.