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.

44 lines (40 loc) 1.71 kB
/*! * ==================================================== * Rzl Utils-JS. * ---------------------------------------------------- * Version: 3.11.0. * Author: Rizalvin Dwiky. * Repository: https://github.com/rzl-zone/utils-js. * ==================================================== */ 'use strict'; var chunkSYHPSOUU_cjs = require('../../chunk-SYHPSOUU.cjs'); require('server-only'); var server = require('next/server'); var getClientIpOrUrl = (request, includeFullUrl = true) => { if (!chunkSYHPSOUU_cjs.isFunction(server.NextRequest)) { throw new Error( "Function `getClientIpOrUrl` is designed to be used in a `NextJS` environment." ); } if (!(request instanceof server.NextRequest)) { throw new TypeError( "First parameter (`request`) must be an `instance of NextRequest` from `NextJS`." ); } chunkSYHPSOUU_cjs.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}`; }; exports.getClientIpOrUrl = getClientIpOrUrl;