get-host.ts 796 B

123456789101112131415161718192021222324252627282930
  1. import { headers } from "next/headers";
  2. /**
  3. * Returns the host of the current request.
  4. *
  5. * @returns The host of the current request.
  6. */
  7. export const getHost = async () => {
  8. const nextHeaders = await headers();
  9. const xfHost = nextHeaders.get("x-forwarded-host")?.split(",")[0]?.trim();
  10. const host = xfHost ?? nextHeaders.get("host") ?? undefined;
  11. if (host === undefined) {
  12. throw new NoHostError();
  13. } else {
  14. const proto =
  15. nextHeaders.get("x-forwarded-proto")?.split(",")[0]?.trim() ??
  16. (host.startsWith("localhost") ? "http" : "https");
  17. return `${proto}://${host}`;
  18. }
  19. };
  20. class NoHostError extends Error {
  21. constructor() {
  22. super(
  23. "Request had neither an `x-forwarded-host` header nor a `host` header",
  24. );
  25. this.name = "NoHostError";
  26. }
  27. }