LearnFrenzy
Sign in Take a free test

React interview · Set 6 of 8

Next.js Interview Questions (App Router)

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

Full-stack React with the App Router

Interviewers check that you understand the server/client boundary, rendering strategies and caching, and how to mutate data securely with Server Actions.

  • RoutingFolders, layouts, loading and error files.
  • RenderingServer vs client components, SSR/SSG/ISR.
  • DataFetching, caching, Server Actions and SEO.

Next.js is the most popular React framework, and many React job descriptions now ask for it. Interviewers focus on the App Router: what runs on the server, how pages are rendered and cached, and how data is mutated safely.

1. How does routing work in the App Router?

Folders inside app/ define routes; a page.tsx makes a route public, layout.tsx wraps child routes and keeps state across navigation, and special files handle loading.tsx, error.tsx and not-found.tsx. Dynamic segments use brackets: app/courses/[slug]/page.tsx.

app/
├── layout.tsx               // root layout: <html>, header, footer
├── page.tsx                 // /
├── courses/
│   ├── page.tsx             // /courses
│   └── [slug]/
│       ├── page.tsx         // /courses/react-basics
│       └── loading.tsx      // skeleton while it loads
└── api/health/route.ts      // GET /api/health

2. Server Components vs Client Components in Next.js?

Components are Server Components by default: they run on the server, can fetch data and read secrets directly, and send no JavaScript to the browser. Add 'use client' at the top of a file for components that need state, effects, event handlers or browser APIs. Keep client components small and push them to the leaves of the tree.

// app/courses/[slug]/page.tsx — Server Component
export default async function CoursePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const course = await db.course.findUnique({ where: { slug } });
  if (!course) notFound();
  return (
    <article>
      <h1>{course.title}</h1>
      <EnrollButton courseId={course.id} />   {/* 'use client' component */}
    </article>
  );
}

3. SSR vs SSG vs ISR — what is the difference?

SSG (static generation) builds HTML at build time — fastest, for content that rarely changes. ISR (incremental static regeneration) serves static pages but regenerates them in the background after a time or on demand. SSR renders on every request — for personalised or always-fresh data. In the App Router you choose per route through caching and revalidation settings.

// Revalidate this page at most once an hour (ISR)
export const revalidate = 3600;

// Or regenerate on demand after an admin edit
import { revalidatePath } from 'next/cache';
revalidatePath('/courses/react-basics');

4. What are Server Actions?

Async functions marked 'use server' that run on the server and can be called from forms or client components — mutations without writing API routes. Validate input on the server, check the user's permissions inside the action, and revalidate affected pages.

// app/actions.ts
'use server';
export async function addComment(formData: FormData) {
  const user = await requireUser();                      // auth check on the server
  const text = String(formData.get('text') ?? '').trim();
  if (text.length < 2) return { error: 'Comment is too short' };
  await db.comment.create({ data: { text, userId: user.id } });
  revalidatePath('/blog/[slug]', 'page');
}

// in a component
<form action={addComment}><textarea name="text" /><button>Post</button></form>

5. How does data fetching and caching work?

Fetch directly in Server Components with async/await. Next.js can cache fetch results and rendered output, deduplicates identical requests in one render, and lets you control freshness with revalidate times or tags (revalidateTag). Mark truly dynamic data as uncached. Caching defaults have changed between versions, so state them explicitly in code.


6. How do you handle SEO in Next.js?

Export metadata or generateMetadata from pages for titles, descriptions, canonical URLs and Open Graph tags; render content on the server so crawlers see it; add sitemap.ts and robots.ts route files; use next/image for optimised images and structured data in JSON-LD.

export async function generateMetadata({ params }) {
  const { slug } = await params;
  const course = await getCourse(slug);
  return {
    title: `${course.title} – Free Course`,
    description: course.summary,
    alternates: { canonical: `/courses/${slug}` },
    openGraph: { images: [course.coverUrl] },
  };
}

7. What is middleware used for?

Code that runs before a request is completed — redirects, rewrites, setting headers, simple auth checks, A/B testing or locale detection. Keep it fast and light; do real authorisation in the server code that reads the data.

// middleware.ts
export function middleware(req: NextRequest) {
  const token = req.cookies.get('session')?.value;
  if (!token && req.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
}
export const config = { matcher: ['/dashboard/:path*'] };

8. Next.js or a plain React single-page app — when to choose which?

Choose Next.js for public, SEO-sensitive sites, fast first loads, and when you want server rendering, routing and APIs in one framework. A plain client-side SPA (for example with Vite) is fine for internal dashboards behind login where SEO does not matter and you already have a separate backend.


Remember

Key points

  • Server by default

    'use client' only where interactivity is needed.

  • Choose freshness per route

    Static, revalidated or dynamic.

  • Actions run on the server

    Validate and authorise inside them.

  • Metadata API for SEO

    Titles, canonicals and Open Graph.

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 What is the difference between the Pages Router and the App Router? Basic

    The Pages Router uses pages/ with getServerSideProps/getStaticProps; the App Router uses app/ with Server Components, layouts, streaming and Server Actions. New projects use the App Router.

  2. 2 What is streaming in Next.js? Intermediate

    Sending HTML in chunks as parts become ready — with loading.tsx and Suspense boundaries — so users see content sooner instead of waiting for the slowest data.

  3. 3 How do you create an API endpoint in the App Router? Basic

    Add a route.ts file exporting functions named after HTTP methods (GET, POST) that return a Response.

  4. 4 Can a Client Component import a Server Component? Advanced

    Not directly, but it can receive one as children or a prop from a Server Component parent — the server part is rendered on the server and passed through.

  5. 5 How do environment variables work in Next.js? Intermediate

    Variables are server-only by default; only those prefixed NEXT_PUBLIC_ are exposed to the browser bundle. Never prefix secrets.

  6. 6 How does next/image improve performance? Basic

    It resizes and converts images to modern formats, lazy-loads by default, prevents layout shift with required dimensions, and supports priority loading for the main image.

Preparing with friends?

Share this page with your study group or placement batch.

Popular