Last active
February 16, 2023 00:02
-
-
Save yanickrochon/76a9abfb8e48153c3102dbabd3780c87 to your computer and use it in GitHub Desktop.
Get server side page full URL for Next.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { IncomingMessage } from "http"; | |
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; | |
export type RequestURL = URL & { | |
basePath: string; | |
}; | |
const getFromMeta = (req: IncomingMessage) => { | |
const meta = Object.getOwnPropertySymbols(req).find( | |
({ description }) => description === "NextRequestMeta" | |
); | |
return meta ? (req as any)[meta]?.__NEXT_INIT_URL ?? null : null; | |
}; | |
export const getRequestURL = (req: IncomingMessage) => { | |
const referer = req.headers.referer ?? getFromMeta(req); | |
if (referer) { | |
const url = new URL(referer); | |
const matchBasePathPrefix = | |
basePath.length && url.pathname.startsWith(basePath); | |
const pathname = matchBasePathPrefix | |
? url.pathname.substring(0, basePath.length) | |
: url.pathname; | |
const href = req.url | |
? url.href.substring(0, url.href.lastIndexOf(pathname)) + req.url | |
: url.href; | |
return { | |
href: href, | |
origin: url.origin, | |
protocol: url.protocol, | |
username: url.username, | |
password: url.password, | |
host: url.host, | |
basePath: matchBasePathPrefix ? basePath : "", | |
hostname: url.hostname, | |
port: url.port, | |
pathname: req?.url ?? pathname, | |
search: url.search, | |
searchParams: url.searchParams, | |
hash: url.hash, | |
}; | |
} else { | |
return null; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment