Skip to main content

Forms and Server Actions

Level: Beginner to Intermediate

ℹ️ What You'll Learn
  • Client-side forms with useState
  • Server actions with 'use server' directive
  • Form submission without JavaScript
  • Error handling and validation
  • Loading and pending states
  • Form libraries: React Hook Form, Zod
  • Submitting to ASP.NET Core API
  • SMS student registration form

Why This Matters

Forms and Server Actions is part of building production React applications with Next.js. You will use it when creating student dashboards, SEO-friendly pages, API-connected forms, route handlers, layouts, and deployments for .NET-backed systems.

Forms are a major part of school applications: student admission, attendance entry, marks entry, fee payments, and login screens.

The Problem

Beginners often treat Next.js like plain React and miss routing, rendering, server/client boundaries, environment variables, and deployment behavior. This lesson shows how Forms and Server Actions works in a real School Management System frontend that talks to ASP.NET Core APIs.

Client-Side Form

Use a Client Component for live validation and typing state.

app/students/NewStudentForm.jsx
"use client";

import { useState } from "react";

export default function NewStudentForm() {
const [name, setName] = useState("");
const [className, setClassName] = useState("");
const [message, setMessage] = useState("");

async function handleSubmit(event) {
event.preventDefault();

if (name.trim().length < 3) {
setMessage("Name must have at least 3 characters.");
return;
}

const response = await fetch("/api/students", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, className })
});

if (!response.ok) {
setMessage("Unable to save student.");
return;
}

setMessage("Student saved.");
setName("");
setClassName("");
}

return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={e => setName(e.target.value)} />
<input value={className} onChange={e => setClassName(e.target.value)} />
<button type="submit">Save</button>
<p>{message}</p>
</form>
);
}

Page Using the Form

app/students/new/page.jsx
import NewStudentForm from "../NewStudentForm";

export default function NewStudentPage() {
return (
<main>
<h1>Add Student</h1>
<NewStudentForm />
</main>
);
}

Server Actions

Server Actions let forms call server functions directly. They are useful in some Next.js-first apps.

async function createStudent(formData) {
"use server";

const name = formData.get("name");
const className = formData.get("className");

await fetch(`${process.env.ASP_NET_API_URL}/api/students`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, className })
});
}
export default function NewStudentPage() {
return (
<form action={createStudent}>
<input name="name" />
<input name="className" />
<button type="submit">Save</button>
</form>
);
}
💡 Beginner recommendation

Start with client-side forms that call /api/... route handlers. Learn Server Actions after you are comfortable with App Router basics.

Validation Rules

Validate in three places:

  • Browser for fast feedback
  • Next.js route handler or server action for request shaping
  • ASP.NET Core Web API for final security and correctness
⚠️ Backend validation is mandatory

Users can bypass browser validation. ASP.NET Core must validate every request before saving to SQL Server.

Interview Questions

🎯 Why do forms often need Client Components?

Forms need typing state, validation messages, button clicks, and submit handlers. These require browser-side interactivity.

🎯 What is a Server Action?

A Server Action is a server-side function that can be called from a form or component to perform mutations without manually creating a separate API route.

Quick Definitions

  • Forms and Server Actions - The main Next.js concept explained in this lesson.
  • App Router - The modern Next.js routing system based on the app folder.
  • Server/Client boundary - The decision of whether code runs on the server or in the browser.
  • ASP.NET Core integration - Calling or proxying backend APIs from a Next.js frontend.

Common Mistakes

  • Treating every component as a Client Component without a reason
  • Forgetting environment variables differ between local and production
  • Calling ASP.NET Core APIs from the browser without handling CORS
  • Putting secrets in NEXT_PUBLIC_ variables
  • Skipping npm run build before deployment

Practice Task

Create a small Next.js example using Forms and Server Actions. Keep it connected to a School Management System scenario.

Suggested practice:

  1. Create or update a route, layout, form, or data-fetching example.
  2. Use realistic student, teacher, attendance, or marks data.
  3. Connect the example to an ASP.NET Core-style API URL or route handler.
  4. Add one loading, empty, or error state where relevant.
  5. Explain what runs on the server and what runs in the browser.

Quick Revision

QuestionAnswer
What is the main idea?Use Forms and Server Actions correctly in a Next.js App Router project.
Where is it used?Pages, layouts, route handlers, forms, APIs, authentication, and deployment.
What should beginners watch carefully?Server/client boundaries, environment variables, CORS, and production builds.
What is the best debugging habit?Check terminal build output, browser console, network tab, and server logs.
🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

Use ChatGPT, Claude, or Copilot to go deeper on Forms and Server Actions. Try these prompts:

  • "Explain Forms and Server Actions with a Next.js and ASP.NET Core example"
  • "Give me 5 practice tasks for Forms and Server Actions in a School Management app"
  • "Show common Next.js mistakes in Forms and Server Actions and how to fix them"
  • "Quiz me on Forms and Server Actions with interview-style questions"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

Authentication Basics ->

nexcoding.in