iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Next.js Intro

Next.js is the default React framework for production - SSR, SSG, RSC, middleware, image and font optimisation.

Next.js essentials

EXAMPLE
// 1. Scaffold
// npx create-next-app@latest myapp --typescript --tailwind --eslint

// app/page.tsx - server component by default
export default async function Home() {
  const stats = await fetch('https://api.example.com/stats', {
    next: { revalidate: 60 },  // ISR: cache 60s
  }).then((r) => r.json());

  return (
    <main className='p-6'>
      <h1 className='text-2xl font-semibold'>Stats</h1>
      <p>Active users: {stats.activeUsers}</p>
    </main>
  );
}

// 2. Client component when you need state / effects
'use client';
import { useState } from 'react';

export function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + 1)}>count: {n}</button>;
}

// 3. Dynamic route - app/blog/[slug]/page.tsx
type Props = { params: { slug: string } };

export default async function Post({ params }: Props) {
  const post = await fetchPost(params.slug);
  return <article>{post.body}</article>;
}

export async function generateStaticParams() {
  const slugs = await listSlugs();
  return slugs.map((slug) => ({ slug }));
}

// 4. Middleware - middleware.ts at project root
import { NextResponse, type NextRequest } from 'next/server';

export function middleware(req: NextRequest) {
  if (!req.cookies.get('session')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/dashboard/:path*'] };

// 5. Optimised image
import Image from 'next/image';
<Image src='/hero.jpg' alt='hero' width={1200} height={600} priority />

// 6. Optimised fonts
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });
<html className={inter.className}>...</html>

// 7. Server actions for forms (RSC)
'use server';
export async function createPost(formData: FormData) {
  await db.posts.create({ data: { title: formData.get('title') as string } });
}

// In a server component:
<form action={createPost}>
  <input name='title' />
  <button type='submit'>Create</button>
</form>

// 8. Deploy
// Vercel: connect repo, push
// Self-host: docker build with node:20-alpine + standalone output
// Cloudflare Pages: works with adapter; reduce edge runtime usage
// next.config.js: output: 'standalone' for Docker images

Why it matters

Next.js wraps React with the answers most production teams reinvent badly - routing, data, images, fonts, middleware. Start with the App Router and React Server Components; reach for client components only where state lives. Vercel for fast prototypes, Docker standalone for self-hosted production.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Next.js app router
export default function Page() {
    return <h1>Hello from Next.js</h1>;
}
Try it Yourself »

Discussion

Loading…