Getting Started with Next.js 14

· 2 min read · Next.js, Tutorial, Web Development, React

Next.js 14 brings exciting new features and improvements that make building React applications even better. Let's explore what's new and how to get started.

What's New in Next.js 14

1. Turbopack (Stable)

Next.js 14 includes a stable version of Turbopack, which provides significantly faster local development.

# Enable Turbopack for development
npm run dev -- --turbo

2. Server Actions (Stable)

Server Actions are now stable, allowing you to run server-side code directly from your components.

async function createUser(formData) {
  'use server'
  
  const name = formData.get('name')
  const email = formData.get('email')
  
  // Save to database
  await db.user.create({ name, email })
}

export default function UserForm() {
  return (
    <form action={createUser}>
      <input name="name" placeholder="Name" />
      <input name="email" placeholder="Email" />
      <button type="submit">Create User</button>
    </form>
  )
}

3. Partial Prerendering (Preview)

Partial Prerendering allows you to combine static and dynamic content in a single route.

Getting Started

Installation

Create a new Next.js 14 project:

npx create-next-app@latest my-app
cd my-app
npm run dev

Project Structure

Next.js 14 uses the App Router by default:

app/
  layout.tsx      # Root layout
  page.tsx        # Home page
  about/
    page.tsx      # About page
  api/
    users/
      route.ts    # API route

Creating Pages

Pages are created by adding files to the app directory:

// app/about/page.tsx
export default function About() {
  return <h1>About Page</h1>
}

Layouts

Layouts wrap pages and can be nested:

// app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        <nav>Navigation</nav>
        {children}
        <footer>Footer</footer>
      </body>
    </html>
  )
}

Data Fetching

Server Components

Fetch data directly in Server Components:

async function getData() {
  const res = await fetch('https://api.example.com/data')
  return res.json()
}

export default async function Page() {
  const data = await getData()
  
  return <div>{data.title}</div>
}

Client Components

Use the 'use client' directive for interactive components:

'use client'

import { useState } from 'react'

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

Conclusion

Next.js 14 provides powerful tools for building modern React applications. With features like Turbopack, stable Server Actions, and improved performance, it's an excellent choice for your next project.