LearnFrenzy
Sign in Take a free test

Next.js interview · Set 5 of 6

Next.js Coding Interview Questions

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

End-to-end features, App Router style

Each task combines routing, server data, client interactivity, validation and states. Explain why each piece runs on the server or the client.

  • PagesStatic blog, search and pagination.
  • MutationsServer Actions with validation.
  • APIs & UXRoute Handlers, loading, errors and modals.

Next.js machine-coding rounds ask you to build a small feature end to end. Each task below shows a clean App Router solution — server-first, typed, with loading and error states — plus the reasoning to say out loud.

1. Build a blog post page with static generation and SEO metadata.

Pre-render known slugs, fetch the post on the server, generate metadata from it, and return 404 for unknown slugs.

// app/blog/[slug]/page.tsx
export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map(p => ({ slug: p.slug }));
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);
  return post ? { title: post.title, description: post.excerpt, alternates: { canonical: `/blog/${slug}` } } : {};
}

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  return (
    <article>
      <h1>{post.title}</h1>
      <time dateTime={post.date}>{new Date(post.date).toLocaleDateString('en-IN')}</time>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </article>
  );
}

2. Build a search page whose results live in the URL.

The server page reads searchParams and queries; a small client input updates the URL (debounced) with router.replace. Results are shareable and the back button works.

// app/jobs/page.tsx (server)
export default async function JobsPage({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
  const { q = '' } = await searchParams;
  const jobs = await searchJobs(q);
  return (
    <>
      <SearchBox defaultValue={q} />
      <Suspense key={q} fallback={<p>Searching…</p>}><JobList jobs={jobs} /></Suspense>
    </>
  );
}

// search-box.tsx
'use client';
export function SearchBox({ defaultValue }: { defaultValue: string }) {
  const router = useRouter();
  const pathname = usePathname();
  const timer = useRef<ReturnType<typeof setTimeout>>();
  return (
    <input defaultValue={defaultValue} placeholder="Search jobs" onChange={e => {
      clearTimeout(timer.current);
      const value = e.target.value;
      timer.current = setTimeout(() => router.replace(`${pathname}?q=${encodeURIComponent(value)}`), 300);
    }} />
  );
}

3. Protect a dashboard so only logged-in users can see it.

Redirect early in proxy for a fast response, and check the session again in the layout (and in every action) because proxy is not a security boundary.

// app/dashboard/layout.tsx
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
  const user = await getCurrentUser();            // redirects to /login if missing
  return (
    <div>
      <header>Welcome, {user.name}</header>
      {children}
    </div>
  );
}

4. Build a contact form with a Server Action, validation and success message.

Validate with Zod on the server, return field errors, and show pending state with useActionState.

// app/contact/actions.ts
'use server';
const Contact = z.object({
  name: z.string().min(2, 'Enter your name'),
  email: z.string().email('Enter a valid email'),
  message: z.string().min(10, 'Write at least 10 characters'),
});
export async function sendMessage(_: unknown, formData: FormData) {
  const parsed = Contact.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { ok: false, errors: parsed.error.flatten().fieldErrors };
  await db.message.create({ data: parsed.data });
  return { ok: true, errors: {} };
}

5. Create a JSON API endpoint with pagination.

A Route Handler reads query parameters, validates them, and returns data with paging info and cache headers.

// app/api/courses/route.ts
export async function GET(req: Request) {
  const url = new URL(req.url);
  const page = Math.max(1, Number(url.searchParams.get('page') ?? 1));
  const size = Math.min(50, Math.max(1, Number(url.searchParams.get('size') ?? 10)));
  const [items, total] = await Promise.all([
    db.course.findMany({ skip: (page - 1) * size, take: size, orderBy: { title: 'asc' } }),
    db.course.count(),
  ]);
  return Response.json({ items, page, size, total, pages: Math.ceil(total / size) },
    { headers: { 'Cache-Control': 's-maxage=60, stale-while-revalidate=300' } });
}

6. Add a loading skeleton and an error boundary to a route.

Drop loading.tsx and error.tsx next to the page; the error component must be a client component and can offer a retry.

// app/courses/loading.tsx
export default function Loading() {
  return <div className="grid">{Array.from({ length: 6 }).map((_, i) => <div key={i} className="card skeleton" />)}</div>;
}

// app/courses/error.tsx
'use client';
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <div role="alert">
      <p>Could not load courses.</p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Read the page from searchParams, query one page, and render Previous/Next as Links so pages are crawlable and shareable.

export default async function Page({ searchParams }: { searchParams: Promise<{ page?: string }> }) {
  const page = Math.max(1, Number((await searchParams).page ?? 1));
  const { items, pages } = await getCoursesPage(page, 12);
  return (
    <>
      <CourseGrid items={items} />
      <nav aria-label="Pagination">
        {page > 1 && <Link href={`?page=${page - 1}`}>Previous</Link>}
        <span>Page {page} of {pages}</span>
        {page < pages && <Link href={`?page=${page + 1}`}>Next</Link>}
      </nav>
    </>
  );
}

8. Open a product quick-view in a modal while keeping the URL (intercepting route).

Use a parallel @modal slot with an intercepting route (.)product/[id]: clicking from the list shows a modal; visiting the URL directly renders the full product page.

app/
├── layout.tsx                    // renders {children} and {modal}
├── @modal/
│   ├── default.tsx               // returns null when no modal
│   └── (.)product/[id]/page.tsx  // modal version
└── product/[id]/page.tsx         // full page version

Remember

Key points

  • State in the URL

    Search and pages are shareable.

  • Validate on the server

    Zod in Server Actions.

  • loading.tsx and error.tsx

    Free Suspense and error boundaries.

  • Check auth twice

    Proxy for speed, layout and actions for safety.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 How would you add infinite scroll instead of pages? Intermediate

    Render the first page on the server, then load more from a Route Handler or Server Action in a client component triggered by IntersectionObserver.

  2. 2 How do you make the search results update without a full reload? Intermediate

    router.replace with new searchParams triggers a server re-render of the page segment only; wrap results in Suspense keyed by the query.

  3. 3 How do you add a dark-mode toggle without a flash? Advanced

    Store the preference in a cookie read on the server to render the right class, or inject a tiny script before paint that sets the class from localStorage.

  4. 4 How do you show the active link in a nav? Basic

    Read usePathname in a client nav component and compare with each link's href.

  5. 5 How would you internationalise routes? Advanced

    Use a [lang] segment with dictionaries loaded on the server, generateStaticParams for each locale, and proxy to redirect to the preferred language.

  6. 6 How do you add JSON-LD structured data? Basic

    Render a <script type="application/ld+json"> with JSON.stringify of the schema object in the page.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links