Skip to content
Qyubie Learn
Web Development courseLesson 15 of 20 · tap to see all lessons

Web Development · Beginner

API Integration and Application Data: Fetching in React and Next.js, App States, and Route Handlers

Fetch API data in React and Next.js, handle JSON with loading, error, and empty states, and build your own REST endpoints with Next.js Route Handlers.

  • Qyubie Learn Editorial Team
  • Published
  • 22 min read

Includes 1 exercise and 2 quick checks you can do right here.

The final topics of this course turn your Next.js pages into a real application: one that reads and saves data. This lesson connects the pieces you already know. From lesson 10 you know how APIs, JSON, and fetch work; from lesson 13, how React shows changing data; from lesson 14, how Next.js organizes pages. Now you'll load API data into React and Next.js pages, show every state a user can see while data loads, and build your own API inside a Next.js app.

By the end of this lesson you will be able to:

  • design REST endpoints for a resource,
  • fetch and show API data in client components and server components,
  • handle the loading, error, empty, and success states of every request, and
  • create API endpoints with Next.js Route Handlers, and test them.

REST, reviewed

A REST API (lesson 10) gives each resource a URL and uses HTTP methods for actions. For the student records in the class portal from lesson 14, the endpoints are:

Method and URLActionSuccess status
GET /api/studentslist students (optionally ?course=BSCS)200
GET /api/students/2get one student200 (or 404 if missing)
POST /api/studentscreate a student from a JSON body201
PUT /api/students/2replace a student's details200
DELETE /api/students/2delete a student204

Invalid data gets 400 (the body isn't JSON) or 422 (it's JSON but fails validation), with a JSON body that says what's wrong. Every response, success or failure, is JSON, so the client can always read it the same way.

The four states of every request

Any time a page loads data, the user can see one of four states, and a good page designs all of them:

StateWhat the user should see
Loadinga message or skeleton, so the page doesn't look broken
Errorwhat went wrong, in plain words, and a way to try again
Emptythat there's nothing yet, and what to do next ("No students yet. Add the first one.")
Successthe data

Beginners usually build only the success state. Real networks are slow and fail, and new apps start empty, so users see the other three a lot.

Exercise · JavaScript

Show every state

Complete show(course): print Loading <course>..., then get the students with fetchStudents. Print their names joined with , ; or No students found. if the list is empty; or Error: <message> if it fails. The calls at the bottom should print six lines.

Expected output
Loading BSCS...
Ana, Cara
Loading BSIT...
No students found.
Loading BSBA...
Error: Server error 500
Hint

Wrap the await in try/catch. Inside try: if (list.length === 0) print the empty message, else print list.map((s) => s.name).join(", "). In catch, print Error: ${error.message}.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const data = [
  { name: "Ana", course: "BSCS" },
  { name: "Cara", course: "BSCS" },
];

async function fetchStudents(course) {
  await wait(100);
  if (course === "BSBA") throw new Error("Server error 500");
  return data.filter((s) => s.course === course);
}

async function show(course) {
  console.log(`Loading ${course}...`);
  try {
    const list = await fetchStudents(course);
    if (list.length === 0) {
      console.log("No students found.");
    } else {
      console.log(list.map((s) => s.name).join(", "));
    }
  } catch (error) {
    console.log(`Error: ${error.message}`);
  }
}

await show("BSCS");
await show("BSIT");
await show("BSBA");

Fetching in a React client component

In plain React (lesson 13), a component loads data in useEffect and keeps the state in useState. This version handles all four states and reloads when the selection changes. Pick User 11 to see the empty state (the test API has no posts for that user), and click the broken-URL button to see the error state:

Try it · HTML & CSS

Preview (index.html, updates as you type)

Three details worth copying:

  • One status value ("loading", "error", "done") instead of separate true/false flags, so the page can never be "loading" and "error" at once.
  • The ignore flag in the cleanup. If the user switches from User 1 to User 2 quickly, the first request might finish last; the flag stops it from replacing the newer data.
  • response.ok: fetch only throws when the network fails. A 404 or 500 still "succeeds", so check the status yourself.

Fetching in a Next.js server component

In Next.js you often don't need useEffect at all. A server component can be async and await the data directly; the server fetches it and sends finished HTML. The browser never sees the API URL or any key you use.

With the recommended Next.js defaults (Cache Components, lesson 14), a component that fetches fresh data must sit inside a <Suspense> boundary. The fallback is your loading state: Next.js sends the rest of the page right away, shows the fallback, and streams the list in when it's ready.

// app/users/page.tsx
import { Suspense } from "react";

type User = { id: number; name: string; email: string };

async function UserList() {
  const response = await fetch("https://jsonplaceholder.typicode.com/users");
  if (!response.ok) {
    throw new Error(`Could not load users (status ${response.status})`);
  }
  const users: User[] = await response.json();

  if (users.length === 0) {
    return <p className="text-gray-500">No users yet.</p>;
  }

  return (
    <ul className="mt-4 space-y-2">
      {users.map((u) => (
        <li key={u.id} className="rounded-lg bg-white p-3 shadow">
          <span className="font-semibold">{u.name}</span>{" "}
          <span className="text-sm text-gray-500">{u.email}</span>
        </li>
      ))}
    </ul>
  );
}

export default function UsersPage() {
  return (
    <section>
      <h1 className="text-2xl font-bold">Users</h1>
      <Suspense fallback={<p className="mt-4 text-gray-500">Loading users...</p>}>
        <UserList />
      </Suspense>
    </section>
  );
}

That covers loading (the fallback), empty, and success. For the error state, the component throws, and Next.js shows the nearest error.tsx file instead of crashing the page. An error file must be a client component, and it receives the error and a retry function:

// app/users/error.tsx
"use client";

export default function UsersError({
  error,
  retry,
}: {
  error: unknown;
  retry: () => void;
}) {
  console.error(error);

  return (
    <div role="alert" className="rounded-lg bg-red-50 p-4 text-red-700">
      <p>Something went wrong while loading this page.</p>
      <button onClick={() => retry()} className="mt-2 font-semibold underline">
        Try again
      </button>
    </div>
  );
}

Which to use?

Fetch in a server component whenFetch in a client component when
the data is needed to show the pagethe data changes with what the user does on the page (a filter, a search box)
you use a secret key or a databasethe data must update without a page navigation
you want the content in the HTML (good for search engines)

Building your own API with Route Handlers

Next.js can also be the API. A file named route.ts inside the app folder is a Route Handler: instead of a page, it exports functions named after HTTP methods (GET, POST, PUT, DELETE), and each returns a Response. Put them under app/api/ so they're easy to tell apart from pages.

First, two helper modules. Every endpoint that accepts data must validate it on the server (never trust what a client sends), so the rules live in one place, to be reused in lessons 16 to 18:

// lib/validate.ts
export const COURSES = ["BSCS", "BSIT"];

export type StudentInput = {
  studentNo: string;
  fullName: string;
  course: string;
  year: number;
  email: string;
};

export type FieldErrors = Partial<Record<keyof StudentInput, string>>;

export type ValidationResult =
  | { ok: true; data: StudentInput }
  | { ok: false; errors: FieldErrors };

export function validateStudent(raw: Record<string, unknown>): ValidationResult {
  const data: StudentInput = {
    studentNo: String(raw.studentNo ?? "").trim(),
    fullName: String(raw.fullName ?? "").trim(),
    course: String(raw.course ?? "").trim(),
    year: Number(raw.year),
    email: String(raw.email ?? "").trim().toLowerCase(),
  };
  const errors: FieldErrors = {};

  if (!/^\d{4}-\d{4}$/.test(data.studentNo)) {
    errors.studentNo = "Use the format 2024-0001.";
  }
  if (data.fullName.length < 3) {
    errors.fullName = "Enter the full name.";
  }
  if (!COURSES.includes(data.course)) {
    errors.course = "Choose BSCS or BSIT.";
  }
  if (!Number.isInteger(data.year) || data.year < 1 || data.year > 4) {
    errors.year = "Year must be 1 to 4.";
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
    errors.email = "Enter a valid email address.";
  }

  return Object.keys(errors).length === 0 ? { ok: true, data } : { ok: false, errors };
}

For now the students are stored in memory, in a plain array. That's enough to build and test the API; lesson 16 replaces it with a real database:

// lib/students-store.ts
import type { StudentInput } from "@/lib/validate";

export type Student = StudentInput & { id: number };

// In memory: resets whenever the server restarts. Lesson 16 uses a database instead.
const students: Student[] = [
  { id: 1, studentNo: "2023-0001", fullName: "Ana Reyes", course: "BSCS", year: 3, email: "ana@example.com" },
  { id: 2, studentNo: "2024-0002", fullName: "Ben Cruz", course: "BSIT", year: 2, email: "ben@example.com" },
];
let nextId = 3;

export function listStudents(course: string | null) {
  return course ? students.filter((s) => s.course === course) : students;
}

export function findStudent(id: number) {
  return students.find((s) => s.id === id);
}

export function addStudent(input: StudentInput) {
  const student = { id: nextId++, ...input };
  students.push(student);
  return student;
}

export function replaceStudent(id: number, input: StudentInput) {
  const index = students.findIndex((s) => s.id === id);
  if (index === -1) return undefined;
  students[index] = { id, ...input };
  return students[index];
}

export function removeStudent(id: number) {
  const index = students.findIndex((s) => s.id === id);
  if (index === -1) return false;
  students.splice(index, 1);
  return true;
}

Now the endpoints. app/api/students/route.ts answers /api/students:

// app/api/students/route.ts
import { addStudent, listStudents } from "@/lib/students-store";
import { validateStudent } from "@/lib/validate";

export async function GET(request: Request) {
  const course = new URL(request.url).searchParams.get("course");
  return Response.json(listStudents(course));
}

export async function POST(request: Request) {
  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return Response.json({ error: "Send the student as JSON." }, { status: 400 });
  }

  const result = validateStudent(body);
  if (!result.ok) {
    return Response.json({ errors: result.errors }, { status: 422 });
  }

  const student = addStudent(result.data);
  return Response.json(student, { status: 201 });
}
  • Response.json(data, { status }) turns the data into JSON, sets the Content-Type header, and sets the status code.
  • await request.json() reads the JSON body. It throws when the body isn't valid JSON, so that becomes a 400.
  • Failed validation returns 422 with an errors object: one message per field, ready to show next to each input.

A dynamic folder gives the ID, exactly like pages: in a Route Handler, params is the second argument, and it's a Promise:

// app/api/students/[id]/route.ts
import { findStudent, removeStudent, replaceStudent } from "@/lib/students-store";
import { validateStudent } from "@/lib/validate";

type Context = { params: Promise<{ id: string }> };

export async function GET(_request: Request, { params }: Context) {
  const { id } = await params;
  const student = findStudent(Number(id));
  if (!student) {
    return Response.json({ error: "Student not found." }, { status: 404 });
  }
  return Response.json(student);
}

export async function PUT(request: Request, { params }: Context) {
  const { id } = await params;
  const result = validateStudent(await request.json().catch(() => ({})));
  if (!result.ok) {
    return Response.json({ errors: result.errors }, { status: 422 });
  }
  const student = replaceStudent(Number(id), result.data);
  if (!student) {
    return Response.json({ error: "Student not found." }, { status: 404 });
  }
  return Response.json(student);
}

export async function DELETE(_request: Request, { params }: Context) {
  const { id } = await params;
  if (!removeStudent(Number(id))) {
    return Response.json({ error: "Student not found." }, { status: 404 });
  }
  return new Response(null, { status: 204 });
}

(_request starts with an underscore by convention: the function must accept it to reach the second argument, but doesn't use it.)

Testing the endpoints

Start the app with npm run dev. A GET is easy: open http://localhost:3000/api/students?course=BSIT in the browser and you'll see the JSON. For other methods, open the browser's DevTools Console (F12) on any page of your app and use fetch:

const response = await fetch("/api/students", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    studentNo: "2025-0003",
    fullName: "Cara Santos",
    course: "BSCS",
    year: 1,
    email: "Cara@Example.com",
  }),
});
console.log(response.status, JSON.stringify(await response.json()));
201 {"id":3,"studentNo":"2025-0003","fullName":"Cara Santos","course":"BSCS","year":1,"email":"cara@example.com"}

The email came back in lowercase, because the server cleaned it. Now send bad data (an empty name, year 7) and you get the errors instead:

422 {"errors":{"fullName":"Enter the full name.","year":"Year must be 1 to 4."}}

If you prefer the terminal, curl does the same (on Windows, type curl.exe in PowerShell):

curl -i http://localhost:3000/api/students/99
HTTP/1.1 404 Not Found
content-type: application/json
...
{"error":"Student not found."}

Using your API from a client component

A client component calls your API with the same fetch code as any other API, using a path that starts with /. This one filters by course and shows all four states:

// app/students/StudentFinder.tsx
"use client";

import { useEffect, useState } from "react";
import type { Student } from "@/lib/students-store";

export default function StudentFinder() {
  const [course, setCourse] = useState("");
  const [students, setStudents] = useState<Student[]>([]);
  const [status, setStatus] = useState<"loading" | "error" | "done">("loading");

  useEffect(() => {
    let ignore = false;
    async function load() {
      setStatus("loading");
      try {
        const response = await fetch(`/api/students?course=${course}`);
        if (!response.ok) throw new Error(`Status ${response.status}`);
        const data: Student[] = await response.json();
        if (!ignore) {
          setStudents(data);
          setStatus("done");
        }
      } catch {
        if (!ignore) setStatus("error");
      }
    }
    load();
    return () => {
      ignore = true;
    };
  }, [course]);

  return (
    <div className="mt-4">
      <select
        value={course}
        onChange={(e) => setCourse(e.target.value)}
        className="rounded-lg border px-3 py-2"
      >
        <option value="">All courses</option>
        <option value="BSCS">BSCS</option>
        <option value="BSIT">BSIT</option>
      </select>

      {status === "loading" && <p className="mt-4 text-gray-500">Loading students...</p>}
      {status === "error" && (
        <p role="alert" className="mt-4 text-red-700">Could not load students. Refresh to try again.</p>
      )}
      {status === "done" && students.length === 0 && (
        <p className="mt-4 text-gray-500">No students in this course yet.</p>
      )}
      {status === "done" && students.length > 0 && (
        <ul className="mt-4 space-y-2">
          {students.map((s) => (
            <li key={s.id} className="rounded-lg bg-white p-3 shadow">
              {s.fullName} <span className="text-sm text-gray-500">{s.course} {s.year}</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
// app/students/page.tsx
import StudentFinder from "./StudentFinder";

export default function StudentsPage() {
  return (
    <section>
      <h1 className="text-2xl font-bold">Students</h1>
      <StudentFinder />
    </section>
  );
}

Inside your own Next.js app, a server component doesn't need to call your own API over HTTP; it can import the data function (or, from lesson 16, query the database) directly. Your API is for client components, mobile apps, and other programs.

Quick check

A client sends { "fullName": "" } to POST /api/students. Which response fits the API in this lesson?

Quick check

In a Next.js app with the recommended defaults, a server component fetches fresh data. What gives users a loading state while it loads?

Common mistakes

  • Only building the success state. Design loading, error, and empty too.
  • Not checking response.ok, so a 404 page gets parsed as if it were data.
  • Trusting the client. Validate on the server, even if the form also validates in the browser.
  • Returning 200 for everything. Clients rely on the status code.
  • Forgetting await params in a Route Handler, or putting params in the first argument instead of the second.
  • Keeping important data in memory. It disappears on restart, and on hosting platforms each server copy has its own memory. That's why lesson 16 adds a database.

Summary

  • REST endpoints pair resource URLs with methods; responses use status codes and JSON for both success and errors.
  • Every request has four states: loading, error, empty, and success. Design all of them.
  • Client components fetch in useEffect (with an ignore flag); server components await data inside <Suspense>, and error.tsx handles failures with retry.
  • app/api/.../route.ts files are Route Handlers: export GET, POST, PUT, DELETE; read JSON with request.json(); answer with Response.json(data, { status }); dynamic params is a Promise in the second argument.
  • Validate every input on the server.

Next: a real database. You'll replace the in-memory array with Supabase PostgreSQL and build complete create, read, update, and delete pages.

References and further reading