Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 32 ยท Quality

Forms, Validation and Auth Flows

Build Nuxt forms that submit to server routes, validate input on both client and server, show field errors, and protect pages and APIs with session cookies.

Forms are where users meet your server, and where bad data and bad actors meet it too. A sign-up form that checks nothing lets garbage into your database. A form that checks only in the browser lets anyone skip the browser and send whatever they like straight to your API. The reliable pattern has three parts: validate on the server (the one check nobody can bypass), validate in the browser too (for fast, friendly feedback), and return errors in a shape the form can show next to each field.

This lesson follows that pattern in Nuxt: a form posting to a server route, one shared schema checked on both sides, field-level error messages, and a small login flow with a session cookie that protects both pages and APIs. Real Nuxt cannot run on this site, so the Nuxt and library code is read-only. The runnable stand-ins use plain Node.js to show the logic that matters: validating a request body and signing a session cookie. Each one says what it simplifies.

One form, two checks

Browser Instant feedback while typing. Easy to skip.
Server The real gate. Every request passes through it.
One schema Write the rules once and use them in both places.

Browser checks are for comfort. Server checks are for safety.

1 / 2

A schema both sides can use

A schema describes valid data. Libraries such as Zod and Valibot let you write one in TypeScript and give you a parse function plus matching types. Put the schema where both the app and the server can import it, for instance in shared/ (Nuxt 4) or a folder in utils/:

TypeScript
// shared/schemas/signup.ts (read-only)
import { z } from "zod";

export const signupSchema = z.object({
  name: z.string().trim().min(2, "Enter at least 2 characters."),
  email: z.string().trim().email("Enter a valid email address."),
  password: z.string().min(10, "Use at least 10 characters."),
});

export type SignupInput = z.infer<typeof signupSchema>;

z.infer gives you the TypeScript type from the same definition, so the form state, the server handler and the validation rules cannot drift apart. The exact method names for turning an error into a per-field map differ a little between library versions, which is why the examples below read the list of issues (error.issues, each with a path and a message) that every version provides.

The server route is the real gate

A server route receives the request. h3, the HTTP layer behind Nuxt's server, offers readValidatedBody, which reads the body and runs your validator in one step (more on server routes in Server routes and the Nitro engine):

TypeScript
// server/api/signup.post.ts (read-only)
import { signupSchema } from "~~/shared/schemas/signup";

export default defineEventHandler(async (event) => {
  const result = await readValidatedBody(event, (body) => signupSchema.safeParse(body));

  if (!result.success) {
    const fields: Record<string, string> = {};
    for (const issue of result.error.issues) {
      const key = String(issue.path[0] ?? "form");
      fields[key] ??= issue.message;
    }
    throw createError({
      statusCode: 422,
      statusMessage: "Validation failed",
      data: { fields },
    });
  }

  const user = await createUser(result.data); // your own helper
  setResponseStatus(event, 201);
  return { id: user.id };
});

Four details deserve attention:

  • Never trust the browser. Even if your form validates, the route validates again.
  • Use status 422 (or 400) for invalid input, so clients and monitoring tools can tell it from a server failure (500).
  • Return errors keyed by field, as in data.fields, so the form can place each message under the right input. Use createError for failures; see how Nitro handles it in Server routes and the Nitro engine.
  • Keep the first message per field (??= above) so users see one clear problem at a time.

A stand-in for validating a body

The following code has no libraries. A tiny rules table plays the role of the schema, and handleSignup has the same shape as the route above: it returns a status and either an id or a fields map. Zod does much more (types, transforms, nested data); this keeps only the contract.

Node.js Validating a request body: status codes and field errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first request fails on all three fields and gets a 422 with one message per field. The second succeeds and is stored with a cleaned-up email. The third is rejected as a duplicate with 409, a business rule that no schema can know. A body that is not an object at all gets the same 422 as any other bad input, instead of crashing the handler.

The form in the app

On the page, keep the form state in a reactive object, run the same schema before sending, and put server errors in the same errors object so the template needs only one place to read:

VUE
<script setup lang="ts">
// pages/signup.vue (read-only)
import { signupSchema } from "~~/shared/schemas/signup";

const form = reactive({ name: "", email: "", password: "" });
const errors = ref<Record<string, string>>({});
const pending = ref(false);

function collect(issues: { path: PropertyKey[]; message: string }[]) {
  const out: Record<string, string> = {};
  for (const issue of issues) out[String(issue.path[0])] ??= issue.message;
  return out;
}

async function submit() {
  errors.value = {};
  const check = signupSchema.safeParse(form);
  if (!check.success) {
    errors.value = collect(check.error.issues);
    return;
  }

  pending.value = true;
  try {
    await $fetch("/api/signup", { method: "POST", body: check.data });
    await navigateTo("/welcome");
  } catch (error: any) {
    errors.value = error?.data?.data?.fields ?? { form: "Something went wrong. Try again." };
  } finally {
    pending.value = false;
  }
}
</script>

<template>
  <form novalidate @submit.prevent="submit">
    <label>Name <input v-model="form.name" autocomplete="name" /></label>
    <p v-if="errors.name" role="alert">{{ errors.name }}</p>

    <label>Email <input v-model="form.email" type="email" autocomplete="email" /></label>
    <p v-if="errors.email" role="alert">{{ errors.email }}</p>

    <label>Password <input v-model="form.password" type="password" autocomplete="new-password" /></label>
    <p v-if="errors.password" role="alert">{{ errors.password }}</p>

    <p v-if="errors.form" role="alert">{{ errors.form }}</p>
    <button :disabled="pending">{{ pending ? "Saving..." : "Create account" }}</button>
  </form>
</template>

Notes on this page:

  • A form submission is an action, so it uses $fetch, not useFetch. useFetch is for data the page needs when it renders (see Data fetching with useFetch and useAsyncData).
  • When $fetch fails, the error carries the server's response. The data we passed to createError ends up at error.data.data, hence the nested path in the catch block.
  • novalidate turns off the browser's own bubbles, so your messages are the only ones shown. The role="alert" makes screen readers announce new errors.
  • Disable the button while pending to prevent double submissions, and always use autocomplete values so password managers work.

Login, sessions and cookies

After a successful login the server must remember who the user is. The standard tool is a session cookie: a small value the server sets once and the browser sends back with every request. It must be httpOnly (JavaScript cannot read it, which limits the damage of an XSS bug), secure in production, sameSite: "lax", and signed or random, so users cannot forge one. h3 has setCookie, getCookie and deleteCookie. Many projects use a module such as nuxt-auth-utils, which provides setUserSession, getUserSession and requireUserSession on the server and a useUserSession composable in the app, and handles the sealing of the cookie for you. The lesson uses plain h3 calls to show what happens underneath:

TypeScript
// server/api/login.post.ts (read-only)
export default defineEventHandler(async (event) => {
  const { email, password } = await readBody(event);
  const user = await verifyCredentials(email, password); // your own helper
  if (!user) {
    throw createError({ statusCode: 401, statusMessage: "Wrong email or password" });
  }
  setCookie(event, "session", signSession({ userId: user.id }), {
    httpOnly: true,
    secure: !import.meta.dev,
    sameSite: "lax",
    maxAge: 60 * 60 * 24 * 7,
    path: "/",
  });
  return { ok: true };
});

Use the same error message for "no such user" and "wrong password", so attackers cannot learn which emails are registered.

Protecting pages and APIs

There are two layers of protection, and you need both.

TypeScript
// middleware/auth.ts (read-only)
export default defineNuxtRouteMiddleware((to) => {
  const { loggedIn } = useUserSession();
  if (!loggedIn.value) {
    return navigateTo(`/login?return=${encodeURIComponent(to.fullPath)}`);
  }
});
TypeScript
// server/api/me.get.ts (read-only)
export default defineEventHandler(async (event) => {
  const session = await requireUserSession(event); // throws 401 when missing
  return { id: session.user.id };
});

A page needs definePageMeta({ middleware: "auth" }) to use the first one (Navigation and route middleware explains how). That middleware is user experience: it spares guests from seeing a page that cannot load its data. It is not security, because it runs in the browser and anyone can call your API directly. The real check is the one inside the server route, which runs for every request regardless of how it arrived. Security and common mistakes returns to this point.

A stand-in for a signed session

Real cookie handling needs a server. This stand-in shows the one idea that makes session cookies safe: the value is signed with a secret, so any change to it is detected. It uses Node's crypto module with a fixed demo secret (in a real app, the secret comes from runtime config and is long and random).

Node.js Signing and checking a session cookie value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The valid cookie passes, and the other three requests are rejected with 401. Changing the user id to 1 invalidates the signature, because the attacker does not know the secret. The last line is a warning: a signed cookie is tamper-proof but still readable, so keep secrets out of the payload, or use a sealed (encrypted) cookie as dedicated libraries do.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the server validate input even when the form already did?

    Browser checks only improve the experience. A script, a curl command or a modified page can send any data directly to your route, so the server is the check that counts.
  2. 2. A signup request has an invalid email. Which response is the best fit?

    422 (or 400) tells clients that the input was the problem. Returning field-keyed messages lets the form show each one under the right input.
  3. 3. Which flags should a session cookie have?

    httpOnly hides the cookie from scripts, secure restricts it to HTTPS, sameSite reduces cross-site sending, and signing prevents forging. Passwords never belong in a cookie.
  4. 4. Your page uses a route middleware that redirects guests to /login. Is the API behind the page protected?

    Route middleware controls navigation in the app. Requests sent straight to /api/... never pass through it, so every protected server route needs its own session check.
  5. 5. Why use $fetch rather than useFetch inside a submit handler?

    useFetch is designed to load data during rendering and share it with the browser. Form submissions happen in response to a user event, so a plain $fetch call is right.

Summary

  • Validate on the server always, and in the browser for comfort; share one schema (Zod, Valibot or similar) between both.
  • Use readValidatedBody in the route, answer invalid input with 422 and a field-keyed error object, and use 409 for business-rule conflicts.
  • In the page, keep form state reactive, collect errors in one object, submit with $fetch, and show messages with role="alert".
  • Session cookies must be httpOnly, secure in production, sameSite, and signed or random; modules such as nuxt-auth-utils handle the details.
  • Route middleware improves navigation; only checks inside server routes actually protect data.

Next: Testing Nuxt apps