Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Zod · Module

.ip

Zod provides separate schemas for IPv4 and IPv6 addresses. Use z.union() to accept either format.

How it works

The current Zod API replaces the older string .ip() refinement with dedicated z.ipv4() and z.ipv6() schemas. Combine them with z.union() when input may use either address family; parsing returns the original valid string or reports a validation error.

Syntax

z.ipv4();
z.ipv6();
z.union([z.ipv4(), z.ipv6()]);

Returns

A Zod schema that validates IP address strings; parsing a valid value returns the input string.

Key points

  • Create an IPv4 schema with z.ipv4().
  • A valid IPv4 address can be checked with .parse().
  • Create an IPv6 schema with z.ipv6().
  • A valid IPv6 address can be checked with .parse().
  • Combine the two schemas with z.union() when either address family is allowed.

Common mistakes

  • Do not use the older z.string().ip() form in the current API; use the dedicated IPv4 or IPv6 constructors.
  • Neither dedicated schema accepts both address families, so explicitly build a union for mixed input.

Example: Validate either IP address format

import { z } from "zod";

const ipAddress = z.union([z.ipv4(), z.ipv6()]);

console.log(ipAddress.parse("192.168.0.0"));
console.log(ipAddress.parse("2001:db8:85a3::8a2e:370:7334"));

Creates a schema accepting either an IPv4 or IPv6 address, then parses one value of each kind.

When to use it

IPv4 configuration

Validate an IPv4-only configuration value, such as a private network address.

IPv6 configuration

Validate an IPv6-only endpoint or network address.

Dual-stack input

Accept client addresses from systems that may provide either address family.

Interview questions

QHow does current Zod validate IP addresses?

Use z.ipv4() for IPv4 addresses and z.ipv6() for IPv6 addresses. These are separate schema constructors in the current API.

Follow-up: How would you accept either family? Create z.union([z.ipv4(), z.ipv6()]).

QWhat are the IPv4 and IPv6 constructors used for?

z.ipv4() validates IPv4 strings, while z.ipv6() validates IPv6 strings. A successful .parse() returns the validated input.

Follow-up: What should replace z.string().ip()? Use the appropriate dedicated constructor, or a union of both constructors.

QHow do you accept both IPv4 and IPv6?

Use a union containing both schemas when the application accepts either address family. This keeps the accepted formats explicit instead of relying on a single broad string refinement.

Follow-up: How would you restrict an endpoint to IPv6 only? Use z.ipv6() directly as the endpoint's input schema.

  • z.ipv4()
  • z.ipv6()
  • z.union()

Source: Defining schemas - Zod. Checked 2026-10-15.