Zod

Some good practises related to using Zod in your Nuxt app

Auto imports

There is no official zod @nuxt module, so to provide imports you need to do it manually.

app.config.ts
export default defineAppConfig({
  imports: {
    presets: [
      {
        from: 'zod',
        imports: [
          { as: 'z', name: '*' },
          {
            name: 'infer',
            as: 'zInfer',
            type: true,
          },
        ],
      },
    ],
  },
})

And then you can use z and zInfer in your app without importing them.

Reusing fields

Sometimes you may want to reuse certain fields across multiple forms. For example your password, email or address fields.

Easiest way to do that is to create a utils file

utils/zod.ts
export function zPassword(errorMessage?: string) {
  return z.string({ error: errorMessage || 'Password is required' })
    .min(8, 'Password must be at least 8 characters')
}

export function zTeamName() {
  return z.string({ error: 'Team name is required' })
    .min(5, 'Team name must be at least 5 characters')
}

export function zUsername() {
  return z.string({ error: 'Username is required' })
    .min(3, 'Username must be at least 3 characters')
}

Nonempty

Instead of using min(1) on arrays or strings you can use nonempty() method. It is just a better practice and more readable.

z.string({ error: 'This field is required' }).nonempty()