UNPKG

@rzl-zone/utils-js

Version:

A modern, lightweight set of JavaScript utility functions with TypeScript support for everyday development, crafted to enhance code readability and maintainability.

42 lines (39 loc) 1.64 kB
/*! * ==================================================== * Rzl Utils-JS. * ---------------------------------------------------- * Version: 3.11.0. * Author: Rizalvin Dwiky. * Repository: https://github.com/rzl-zone/utils-js. * ==================================================== */ import { isFunction, assertIsBoolean } from '../../chunk-MSUW5VHZ.js'; import 'server-only'; import { NextRequest } from 'next/server'; var getClientIpOrUrl = (request, includeFullUrl = true) => { if (!isFunction(NextRequest)) { throw new Error( "Function `getClientIpOrUrl` is designed to be used in a `NextJS` environment." ); } if (!(request instanceof NextRequest)) { throw new TypeError( "First parameter (`request`) must be an `instance of NextRequest` from `NextJS`." ); } assertIsBoolean(includeFullUrl, { message: ({ currentType, validType }) => `Second parameter (\`includeFullUrl\`) must be of type \`${validType}\`, but received: \`${currentType}\`.` }); const forwardedIps = (request.headers.get("x-forwarded-for") ?? "127.0.0.1").trim().split(","); if (forwardedIps[0] === "::ffff:127.0.0.1" || forwardedIps[0] === "::1") { forwardedIps[0] = "127.0.0.1"; } const clientIp = forwardedIps.length > 1 ? forwardedIps[forwardedIps.length - 1].trim() : forwardedIps[0]; if (!includeFullUrl) { return clientIp; } const protocol = request.headers.get("x-forwarded-proto") || "http"; const port = request.headers.get("x-forwarded-port") || "3000"; return `${process.env.NODE_ENV === "production" ? protocol : "http"}://${clientIp}:${port}`; }; export { getClientIpOrUrl };