mirror of
https://github.com/vercel/flags.git
synced 2026-09-19 03:49:23 +08:00
28 lines
798 B
TypeScript
28 lines
798 B
TypeScript
import { randomBytes } from 'crypto';
|
|
import { dedupe } from 'flags/next';
|
|
import { cookies, headers } from 'next/headers';
|
|
import type { Entity } from './types';
|
|
|
|
export const identify = dedupe(async (): Promise<Entity> => {
|
|
const cookieStore = await cookies();
|
|
const headerStore = await headers();
|
|
const visitorId =
|
|
cookieStore.get('visitorId')?.value ??
|
|
headerStore.get('x-visitor-id') ??
|
|
generateRandomId();
|
|
|
|
return {
|
|
visitor: {
|
|
id: visitorId,
|
|
},
|
|
};
|
|
});
|
|
|
|
export function generateRandomId(length = 16) {
|
|
return randomBytes(length)
|
|
.toString('base64') // Convert to base64
|
|
.replace(/\+/g, '0') // Replace '+' with '0' to make it alphanumeric
|
|
.replace(/\//g, '1') // Replace '/' with '1'
|
|
.substring(0, length); // Trim to the desired length
|
|
}
|