Skip to content

Instantly share code, notes, and snippets.

@Magnuti
Created August 6, 2025 13:08
Show Gist options
  • Select an option

  • Save Magnuti/833452f58f8afc3555998a6f2e7da89e to your computer and use it in GitHub Desktop.

Select an option

Save Magnuti/833452f58f8afc3555998a6f2e7da89e to your computer and use it in GitHub Desktop.
Zod utils

Zod utils

URL parsing

Note that https://hello is a valid URL according to the new URL() constructor. Should maybe check if value contains at least one dot.

import z from "zod";

export const zodUrlOrLocalhost = z.string().refine(
  (value) => {
    if (value === "localhost") {
      return true;
    }

    let valueWithProtocol = value;
    if (!value.startsWith("http://") && !value.startsWith("https://")) {
      // Prepend https:// for .url to work since zod hates URLs without protocol
      valueWithProtocol = `https://${value}`;
    }

    const urlSchema = z.string().url();
    const result = urlSchema.safeParse(valueWithProtocol);
    return result.success;
  },
  {
    message: "Host must be a valid URL",
  },
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment