next js

Intermediate

Next.js Intermediate Preparation Study Guide

Focus: General (Conceptual, Coding, and Practical Scenarios)


1. Core Concepts Overview

1.1 Pages & Routing

Next.js uses File-Based Routing:

  • Each file in the pages directory becomes a route (pages/index.js/). Routes**:
    • pages/blog/[slug].js/blog/:slug
    • Catch-all routes: pages/blog/[...slug].js/blog/a/b/c

1.2 Data Fetching Strategies

MethodWhen to UseKey Features
getStaticPropsStatic content (pre-rendered at build)Returns props for the page; uses getStaticPaths for dynamic routes.
getServerSidePropsData that changes frequentlyRuns on every request; returns props or revalidate for ISR.
getStaticPathsPre-render dynamic routesSpecifies paths to pre-render at build time.
Client-Side FetchingUser-specific dataUse useEffect or libraries like swr/react-query.

1.3 API Routes

  • Located in pages/api/*.
  • Example: pages/api/hello.jsPOST /api/hello
export default function handler(req, res) {
  res.status(200).json({ message: "Hello from API!" });
}

1.4 Middleware

  • Run code before a request is completed.
  • Use for authentication, logging, A/B testing, etc.
export { default } from 'next-middlewares/with-clerk-auth';

1.5 App Router (Next.js 13+)

  • New App Directory structure (app/):
    • Segment Files: app/layout.js (root layout), app/page.js (main page).
    • Nested Routes: app/blog/[slug]/page.js/blog/:slug.
    • Loader/Action Functions: page.js exports loader and action for server-side logic.

2. Common Interview Questions & Ideal Answers

Q1: Explain the difference between SSR, SSG, and ISR.

Answer:

  • SSR (Server-Side Rendering):
    • HTML is generated on each request on the server.
    • Use when content changes frequently (e.g., user dashboards).
    • Example: getServerSideProps.
  • SSG (Static Site Generation):
    • HTML is generated at build time.
    • Use for static content (e.g., blogs, landing pages).
    • Example: getStaticProps + getStaticPaths.
  • ISR (Incremental Static Regeneration):
    • Re-generates static pages on-demand after build.
    • Set revalidate in getStaticProps (e.g., revalidate: 60 → re-generate every 60s).

Q2: How would you optimize a Next.js page for performance?

Answer:

  1. Use SSG/ISR to reduce server load.
  2. Code Splitting: Next.js automatically splits code via dynamic imports (next/dynamic).
  3. Image Optimization: Use next/image for automatic resizing, format conversion, and lazy loading.
  4. Enable Incremental Static Regeneration for frequently updated content.
  5. Prefetch Pages: Use prefetch in next/link to preload data.
  6. Leverage next/font: Self-hosted, optimized fonts.

Code Example:

import Image from 'next/image';

export default function Page() {
  return (
    <Image
      src="/path/to/image.jpg"
      alt="Description"
      width={500}
      height={300}
      priority // Loads immediately
    />
  );
}

Q3: How to handle authentication in Next.js?

Answer:
Approach 1: Middleware

  • Use next-auth.js or custom middleware to protect routes.
// middleware.js
import { withAuth } from 'next-auth/middleware';

export default withAuth({
  callbacks: {
    authorized: ({ token }) => !!token,
  },
});

Approach 2: Session-Based (Client-Side)

  • Store JWT/cookies and validate on each request in getServerSideProps:
export async function getServerSideProps(context) {
  const { req } = context;
  const session = await getSession({ req });
  if (!session) return { redirect: { destination: '/login' } };
  return { props: {} };
}

3. Real-World Examples

Example 1: Dynamic Routes with SSG + ISR

// pages/blog/[slug]/page.js
export async function getStaticProps({ params }) {
  const post = await fetch(`https://api.example.com/posts/${params.slug}`);
  return { props: { post }, revalidate: 3600 }; // Re-validate every hour
}

export async function getStaticPaths() {
  const posts = await fetch('https://api.example.com/posts');
  const paths = posts.map(post => ({ params: { slug: post.id } }));
  return { paths, fallback: 'blocking' }; // Show HTML while generating
}

Example 2: Using next/api for Simple CRUD

// app/api/todo/[id]/route.js (App Router)
import { NextResponse } from 'next/server';

export async function GET({ params }) {
  const todo = await db.todo.findUnique({ where: { id: params.id } });
  return NextResponse.json(todo);
}

export async function DELETE({ params }) {
  await db.todo.delete({ where: { id: params.id } });
  return NextResponse.json({ success: true });
}

4. Study Tips

  1. Build Projects:
    • Create a blog with SSG, a dashboard with SSR, and an e-commerce site with ISR.
  2. Review Official Docs:
  3. Practice Common Patterns:
    • Dynamic routes, middleware, client-side fetching with swr, and integration with CMS-headless (e.g., Strapi, Sanity).
  4. Understand Recent Updates:
    • Next.js 13+ App Router, Server Actions, and Turbopack for performance.
  5. Mock Interviews:
    • Practice explaining trade-offs (e.g., SSG vs. SSR) and debugging common issues (e.g., hydration mismatches).

Next Steps:

  • Ask for coding exercises (e.g., “Implement ISR for a product listing page”).
  • Request a mock interview on Next.js intermediate topics.
  • Clarify any concept above!

Ready for a new challenge?

Start a new session to explore different topics or increase the difficulty level.

Start New Session
next js Preparation Guide | Interview Preparation