Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Getting Started with Next.js

Build React applications with Next.js framework. Learn server-side rendering, routing, API routes, and more with Next.js.

jiocoder TeamUpdated Jun 6, 20264 min readNext.js
Getting Started with Next.js

What is Next.js?#

Next.js is a React framework for production that provides a great developer experience with features like server-side rendering (SSR), static site generation (SSG), API routes, automatic code splitting, optimized performance, and more. It's built on top of React and Node.js, making it perfect for building full-stack React applications.

Next.js was created by Vercel and has become one of the most popular React frameworks. It handles many complex configurations automatically, allowing developers to focus on building features rather than configuring build tools.

Key Features#

  • Server-Side Rendering (SSR) - Render pages on the server
  • Static Site Generation (SSG) - Pre-render pages at build time
  • API Routes - Build API endpoints alongside your pages
  • Automatic Code Splitting - Optimize bundle sizes
  • File-based Routing - Simple, intuitive routing
  • Image Optimization - Automatic image optimization
  • CSS Support - Built-in CSS and Sass support
  • TypeScript Support - First-class TypeScript support

Installation#

Create a new Next.js project using create-next-app:

Code
# Using npx (recommended)
npx create-next-app@latest my-app

# With TypeScript
npx create-next-app@latest my-app --typescript

# With Tailwind CSS
npx create-next-app@latest my-app --tailwind

# With all options
npx create-next-app@latest my-app --typescript --tailwind --app

cd my-app
npm run dev

The app will be available at http://localhost:3000

Project Structure#

Code
my-app/
  ├── pages/          # Pages and API routes
  │   ├── api/       # API routes
  │   ├── _app.js    # Custom App component
  │   └── index.js    # Home page
  ├── public/         # Static files
  ├── styles/         # CSS files
  ├── components/     # React components
  └── package.json

Pages and Routing#

Next.js uses file-based routing. Files in the pages directory automatically become routes:

Code
// pages/index.js - Route: /
export default function Home() {
  return (
    <div>
      <h1>Home Page</h1>
      <p>Welcome to Next.js!</p>
    </div>
  );
}

// pages/about.js - Route: /about
export default function About() {
  return <h1>About Page</h1>;
}

// pages/blog/[slug].js - Dynamic route: /blog/:slug
import { useRouter } from 'next/router';

export default function BlogPost() {
  const router = useRouter();
  const { slug } = router.query;
  
  return <h1>Blog Post: {slug}</h1>;
}

// pages/products/[...params].js - Catch-all route
export default function Products() {
  const router = useRouter();
  const { params } = router.query;
  
  return <div>Products: {params?.join('/')}</div>;
}

Server-Side Rendering (SSR)#

Use getServerSideProps to fetch data on each request:

Code
// pages/posts.js
export default function Posts({ posts }) {
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export async function getServerSideProps(context) {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await res.json();
  
  return {
    props: { posts }
  };
}

Static Site Generation (SSG)#

Use getStaticProps to pre-render pages at build time:

Code
// pages/products.js
export default function Products({ products }) {
  return (
    <div>
      {products.map(product => (
        <div key={product.id}>
          <h2>{product.name}</h2>
          <p>{product.price}</p>
        </div>
      ))}
    </div>
  );
}

export async function getStaticProps() {
  const res = await fetch('https://api.example.com/products');
  const products = await res.json();
  
  return {
    props: { products },
    revalidate: 60 // Re-generate page every 60 seconds (ISR)
  };
}

API Routes#

Create API endpoints in the pages/api directory:

Code
// pages/api/users.js
export default function handler(req, res) {
  if (req.method === 'GET') {
    res.status(200).json({ users: [] });
  } else if (req.method === 'POST') {
    const { name, email } = req.body;
    // Create user logic
    res.status(201).json({ message: 'User created' });
  } else {
    res.setHeader('Allow', ['GET', 'POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

// pages/api/users/[id].js
export default function handler(req, res) {
  const { id } = req.query;
  
  if (req.method === 'GET') {
    res.status(200).json({ id, name: 'John' });
  } else if (req.method === 'PUT') {
    res.status(200).json({ message: 'User updated' });
  } else if (req.method === 'DELETE') {
    res.status(200).json({ message: 'User deleted' });
  }
}

Image Optimization#

Next.js provides an optimized Image component:

Code
import Image from 'next/image';

function MyComponent() {
  return (
    <Image
      src="/images/hero.jpg"
      alt="Hero image"
      width={800}
      height={600}
      priority // Load immediately
    />
  );
}

Use Next.js Link for client-side navigation:

Code
import Link from 'next/link';

function Navigation() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/blog/[slug]" as="/blog/my-post">Blog Post</Link>
    </nav>
  );
}

Environment Variables#

Code
// .env.local
NEXT_PUBLIC_API_URL=https://api.example.com
SECRET_KEY=your-secret-key

// Usage
const apiUrl = process.env.NEXT_PUBLIC_API_URL; // Available in browser
const secret = process.env.SECRET_KEY; // Server-side only

Deployment#

Code
# Build for production
npm run build

# Start production server
npm start

# Deploy to Vercel (recommended)
vercel

# Or deploy to other platforms
npm run build
# Upload .next folder to your hosting

Best Practices#

  • Use getStaticProps for static content
  • Use getServerSideProps for dynamic content
  • Optimize images with next/image
  • Use API routes for backend functionality
  • Implement ISR (Incremental Static Regeneration) for frequently updated content
  • Use dynamic imports for code splitting
  • Leverage Next.js middleware for authentication

Next.js is a powerful framework that makes building production-ready React applications easier. With its built-in optimizations, routing, and API capabilities, it's an excellent choice for modern web development.

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment