Next.js course Β· Module 1: Next.js Configuration

First "Hello World" Application - Step by Step - A Simple Page for a Space Company

15 min read Β·
In this lesson16

In Quantum Metropolis, every engineer remembers their first project - the moment they first launched their own quantum system. In the world of Next.js developers, that first step is creating a "Hello World" application. In this lesson, we'll walk you through the process of creating a simple website for the fictional space company "Quantum Voyages", using the latest features of Next.js 16 and App Router.

Project Setup

First, we need to create a new Next.js project. Open your terminal and run the following command:

npx create-next-app@latest quantum-voyages

During the initialization process, answer the configuration questions:

Would you like to use the recommended Next.js defaults? No, customize settings
Would you like to use TypeScript? Yes
Which linter would you like to use? ESLint
Would you like to use React Compiler? No
Would you like to use Tailwind CSS? Yes
Would you like your code inside a `src/` directory? Yes
Would you like to use App Router? (recommended) Yes
Would you like to customize the import alias (`@/*` by default)? No (the default @/* alias is enough)
Would you like to include AGENTS.md to guide coding agents to write up-to-date Next.js code? Yes

When the installation process is complete, navigate to the project directory:

cd quantum-voyages

Project Structure

After creating the project, you'll see a directory structure similar to this:

quantum-voyages/
β”œβ”€β”€ node_modules/
β”œβ”€β”€ public/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ favicon.ico
β”‚   β”‚   β”œβ”€β”€ globals.css
β”‚   β”‚   β”œβ”€β”€ layout.tsx
β”‚   β”‚   └── page.tsx
β”œβ”€β”€ AGENTS.md
β”œβ”€β”€ CLAUDE.md
β”œβ”€β”€ eslint.config.mjs
β”œβ”€β”€ next-env.d.ts
β”œβ”€β”€ next.config.ts
β”œβ”€β”€ package.json
β”œβ”€β”€ postcss.config.mjs
└── tsconfig.json

Creating the Home Page

Let's start by modifying the home page. Open the src/app/page.tsx file and replace its content with the following code:

// src/app/page.tsx
import Link from 'next/link';

export default function HomePage() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-center p-24">
      <h1 className="text-6xl font-bold text-center bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-8">
        Quantum Voyages
      </h1>
      <p className="text-xl text-center max-w-2xl mb-8">
        We explore the universe using the latest quantum technologies.
        Join our interstellar journey and let's push the boundaries of possibility together.
      </p>
      <div className="flex gap-4">
        <Link
          href="/offer"
          className="px-6 py-3 rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors"
        >
          Our offer
        </Link>
        <Link
          href="/contact"
          className="px-6 py-3 rounded-full bg-purple-600 text-white hover:bg-purple-700 transition-colors"
        >
          Contact
        </Link>
      </div>
    </main>
  );
}

Global Styles and Layout

Next, let's modify the global layout of our application. Open the src/app/layout.tsx file and update it:

// src/app/layout.tsx
import './globals.css';
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';

const inter = Inter({ subsets: ['latin'] });

export const metadata: Metadata = {
  title: 'Quantum Voyages - Interstellar Travel',
  description: 'A space company specializing in interstellar quantum travel',
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        {children}
      </body>
    </html>
  );
}

Creating the Header Component

Now let's create a shared header that will be displayed on all pages. First, we'll create a directory for shared components:

mkdir -p src/components/ui

Then create the file src/components/ui/Header.tsx:

// src/components/ui/Header.tsx
"use client";

import Link from 'next/link';
import { useState } from 'react';

export default function Header() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  return (
    <header className="fixed w-full bg-black/80 backdrop-blur-md text-white z-10">
      <div className="container mx-auto px-4 py-4 flex justify-between items-center">
        <Link href="/" className="text-2xl font-bold">
          Quantum Voyages
        </Link>

        {/* Mobile Menu Button */}
        <button
          className="md:hidden"
          onClick={() => setIsMenuOpen(!isMenuOpen)}
        >
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-6 h-6">
            {isMenuOpen
              ? <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              : <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16m-7 6h7" />
            }
          </svg>
        </button>

        {/* Desktop Navigation */}
        <nav className="hidden md:flex gap-6">
          <Link href="/" className="hover:text-blue-400 transition-colors">
            Home
          </Link>
          <Link href="/offer" className="hover:text-blue-400 transition-colors">
            Our offer
          </Link>
          <Link href="/about" className="hover:text-blue-400 transition-colors">
            About us
          </Link>
          <Link href="/contact" className="hover:text-blue-400 transition-colors">
            Contact
          </Link>
        </nav>
      </div>

      {/* Mobile Navigation */}
      {isMenuOpen && (
        <nav className="flex flex-col md:hidden bg-black/90 py-4">
          <Link
            href="/"
            className="px-4 py-2 hover:bg-blue-900/30"
            onClick={() => setIsMenuOpen(false)}
          >
            Home
          </Link>
          <Link
            href="/offer"
            className="px-4 py-2 hover:bg-blue-900/30"
            onClick={() => setIsMenuOpen(false)}
          >
            Our offer
          </Link>
          <Link
            href="/about"
            className="px-4 py-2 hover:bg-blue-900/30"
            onClick={() => setIsMenuOpen(false)}
          >
            About us
          </Link>
          <Link
            href="/contact"
            className="px-4 py-2 hover:bg-blue-900/30"
            onClick={() => setIsMenuOpen(false)}
          >
            Contact
          </Link>
        </nav>
      )}
    </header>
  );
}

Note that we used the "use client" directive at the top of the file, because this component uses React hooks and handles user events.

Now let's create a footer that will also be present on all pages. Create the file src/components/ui/Footer.tsx:

// src/components/ui/Footer.tsx
import Link from 'next/link';

export default function Footer() {
  const currentYear = new Date().getFullYear();

  return (
    <footer className="bg-black/80 backdrop-blur-md text-white py-8">
      <div className="container mx-auto px-4">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
          <div>
            <h3 className="text-xl font-bold mb-4">Quantum Voyages</h3>
            <p className="text-gray-300">
              We explore the universe using the latest quantum technologies.
            </p>
          </div>

          <div>
            <h3 className="text-xl font-bold mb-4">Navigation</h3>
            <ul className="space-y-2">
              <li><Link href="/" className="text-gray-300 hover:text-white transition-colors">Home</Link></li>
              <li><Link href="/offer" className="text-gray-300 hover:text-white transition-colors">Our offer</Link></li>
              <li><Link href="/about" className="text-gray-300 hover:text-white transition-colors">About us</Link></li>
              <li><Link href="/contact" className="text-gray-300 hover:text-white transition-colors">Contact</Link></li>
            </ul>
          </div>

          <div>
            <h3 className="text-xl font-bold mb-4">Contact</h3>
            <address className="not-italic text-gray-300">
              <p>Alpha Orbital Station</p>
              <p>Geostationary orbit, Earth</p>
              <p>contact@quantum-voyages.space</p>
            </address>
          </div>
        </div>

        <div className="border-t border-gray-800 mt-8 pt-8 text-center">
          <p className="text-gray-400">&copy; {currentYear} Quantum Voyages. All rights reserved.</p>
        </div>
      </div>
    </footer>
  );
}

Updating the Main Layout

Now let's update the main application layout to include our header and footer:

// src/app/layout.tsx
import './globals.css';
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import Header from '@/components/ui/Header';
import Footer from '@/components/ui/Footer';

const inter = Inter({ subsets: ['latin'] });

export const metadata: Metadata = {
  title: 'Quantum Voyages - Interstellar Travel',
  description: 'A space company specializing in interstellar quantum travel',
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className + " bg-gradient-to-b from-gray-900 to-black text-white min-h-screen"}>
        <Header />
        <div className="pt-20">
          {children}
        </div>
        <Footer />
      </body>
    </html>
  );
}

Updating the Home Page

Now let's adjust the home page to better fit our new layout:

// src/app/page.tsx
import Link from 'next/link';
import Image from 'next/image';

export default function HomePage() {
  return (
    <>
      {/* Hero Section */}
      <section className="h-[90vh] flex flex-col items-center justify-center text-center p-4 relative overflow-hidden">
        <div className="absolute inset-0 z-0">
          <div className="absolute inset-0 bg-black/60 z-10"></div>
          <Image
            src="/space.jpg"
            alt="Outer space"
            fill
            className="object-cover"
            preload
          />
        </div>

        <div className="relative z-20 max-w-4xl mx-auto">
          <h1 className="text-6xl font-bold mb-6 bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
            Quantum Voyages
          </h1>
          <p className="text-xl mb-8 text-gray-200">
            We break the boundaries of space and time through quantum technology.
            We are pioneers in the field of interstellar exploration.
          </p>
          <div className="flex flex-wrap gap-4 justify-center">
            <Link
              href="/offer"
              className="px-8 py-3 rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors"
            >
              Discover our missions
            </Link>
            <Link
              href="/contact"
              className="px-8 py-3 rounded-full bg-purple-600 text-white hover:bg-purple-700 transition-colors"
            >
              Join the crew
            </Link>
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="py-20 px-4">
        <div className="container mx-auto">
          <h2 className="text-4xl font-bold text-center mb-16">Our quantum advantages</h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-10">
            <div className="p-6 bg-gradient-to-br from-blue-900/30 to-blue-800/10 rounded-xl backdrop-blur-sm">
              <div className="w-16 h-16 bg-blue-600 rounded-lg flex items-center justify-center mb-4">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
              </div>
              <h3 className="text-xl font-semibold mb-2">Quantum drive</h3>
              <p className="text-gray-300">
                Our spaceships use the latest quantum drive technology,
                enabling travel at speeds exceeding the speed of light.
              </p>
            </div>

            <div className="p-6 bg-gradient-to-br from-purple-900/30 to-purple-800/10 rounded-xl backdrop-blur-sm">
              <div className="w-16 h-16 bg-purple-600 rounded-lg flex items-center justify-center mb-4">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                </svg>
              </div>
              <h3 className="text-xl font-semibold mb-2">Quantum shields</h3>
              <p className="text-gray-300">
                Advanced shields based on quantum mechanics provide
                the highest level of safety during interstellar travel.
              </p>
            </div>

            <div className="p-6 bg-gradient-to-br from-teal-900/30 to-teal-800/10 rounded-xl backdrop-blur-sm">
              <div className="w-16 h-16 bg-teal-600 rounded-lg flex items-center justify-center mb-4">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" />
                </svg>
              </div>
              <h3 className="text-xl font-semibold mb-2">Quantum laboratories</h3>
              <p className="text-gray-300">
                Our ships are equipped with state-of-the-art quantum laboratories,
                enabling scientific research in outer space.
              </p>
            </div>
          </div>
        </div>
      </section>

      {/* Call to Action */}
      <section className="py-16 px-4 bg-gradient-to-r from-blue-900/40 to-purple-900/40">
        <div className="container mx-auto text-center">
          <h2 className="text-3xl font-bold mb-4">Ready for an interstellar adventure?</h2>
          <p className="text-xl text-gray-300 mb-8 max-w-2xl mx-auto">
            Join the community of quantum explorers and be part of
            humanity's next great step in space exploration.
          </p>
          <Link
            href="/contact"
            className="px-8 py-3 rounded-full bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:from-blue-700 hover:to-purple-700 transition-colors"
          >
            Learn more
          </Link>
        </div>
      </section>
    </>
  );
}

Preparing Assets

To make our page look attractive, we need a background image for the hero section. Download a space photo (or use your own) and place it in the public/ directory as space.jpg.

Creating the "Offer" Subpage

Now let's create the offer subpage. Create the directory src/app/offer and the file page.tsx inside:

// src/app/offer/page.tsx
import Image from 'next/image';

interface MissionProps {
  title: string;
  description: string;
  image: string;
  destination: string;
  duration: string;
  price: string;
}

function Mission({ title, description, image, destination, duration, price }: MissionProps) {
  return (
    <div className="bg-gradient-to-br from-gray-800/50 to-gray-900/50 rounded-xl overflow-hidden backdrop-blur-sm">
      <div className="relative h-64">
        <Image
          src={image}
          alt={title}
          fill
          className="object-cover"
        />
      </div>
      <div className="p-6">
        <h3 className="text-2xl font-bold mb-2">{title}</h3>
        <p className="text-gray-300 mb-4">{description}</p>
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <p className="text-gray-400">Destination</p>
            <p className="font-medium">{destination}</p>
          </div>
          <div>
            <p className="text-gray-400">Duration</p>
            <p className="font-medium">{duration}</p>
          </div>
          <div className="col-span-2">
            <p className="text-gray-400">Cost</p>
            <p className="font-bold text-xl text-blue-400">{price}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function OfferPage() {
  const missions = [
    {
      title: "Orbital Tour",
      description: "Perfect for beginner space explorers. Experience weightlessness and admire Earth from orbit.",
      image: "/mission-orbit.jpg",
      destination: "Low Earth Orbit",
      duration: "3 days",
      price: "250,000 credits"
    },
    {
      title: "Moon Weekend",
      description: "Spend an unforgettable weekend at the luxury complex on the Moon's surface.",
      image: "/mission-moon.jpg",
      destination: "Moon",
      duration: "5 days",
      price: "750,000 credits"
    },
    {
      title: "Mars Expedition",
      description: "Discover the red planet and be one of the first humans to set foot on it.",
      image: "/mission-mars.jpg",
      destination: "Mars",
      duration: "3 months",
      price: "5,000,000 credits"
    },
    {
      title: "Journey to Proxima Centauri",
      description: "An interstellar expedition to the nearest star beyond our Solar System.",
      image: "/mission-proxima.jpg",
      destination: "Proxima Centauri",
      duration: "5 years (onboard time: 6 months)",
      price: "25,000,000 credits"
    }
  ];

  return (
    <div className="container mx-auto px-4 py-16">
      <div className="text-center mb-16">
        <h1 className="text-5xl font-bold mb-4">Our space missions</h1>
        <p className="text-xl text-gray-300 max-w-3xl mx-auto">
          Choose your space journey from our offerings. From a short orbital tour
          to interstellar expeditions - each one will forever change your perception of the universe.
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
        {missions.map((mission, index) => (
          <Mission key={index} {...mission} />
        ))}
      </div>

      <div className="mt-16 p-8 bg-gradient-to-r from-blue-900/30 to-purple-900/30 rounded-xl backdrop-blur-sm">
        <h2 className="text-3xl font-bold mb-4">Custom missions</h2>
        <p className="text-gray-300 mb-6">
          Looking for something unique? We offer exclusive, custom missions
          tailored to your specific expectations and research needs.
        </p>
        <button className="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 rounded-full hover:from-blue-700 hover:to-purple-700 transition-colors">
          Contact us
        </button>
      </div>
    </div>
  );
}

For this subpage, you'll also need images. You can add your own files to the public/ directory or use existing images.

Creating the "Contact" Subpage

Now let's create a contact subpage with a form. Create the directory src/app/contact and the file page.tsx inside:

// src/app/contact/page.tsx
import ContactForm from './ContactForm';

export default function ContactPage() {
  return (
    <div className="container mx-auto px-4 py-16">
      <div className="text-center mb-16">
        <h1 className="text-5xl font-bold mb-4">Get in touch</h1>
        <p className="text-xl text-gray-300 max-w-3xl mx-auto">
          Have questions about our space missions or want to join the crew?
          Use the form below or visit our office.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-16">
        <div>
          <h2 className="text-3xl font-semibold mb-6">Send a message</h2>
          <ContactForm />
        </div>

        <div>
          <h2 className="text-3xl font-semibold mb-6">Contact details</h2>

          <div className="space-y-6">
            <div className="flex items-start">
              <div className="bg-blue-600 p-3 rounded-lg mr-4">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
              </div>
              <div>
                <h3 className="text-xl font-medium mb-1">Address</h3>
                <address className="not-italic text-gray-300">
                  <p>Alpha Orbital Station</p>
                  <p>Geostationary orbit, Earth</p>
                </address>
              </div>
            </div>

            <div className="flex items-start">
              <div className="bg-blue-600 p-3 rounded-lg mr-4">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
              <div>
                <h3 className="text-xl font-medium mb-1">Email</h3>
                <p className="text-gray-300">contact@quantum-voyages.space</p>
              </div>
            </div>

            <div className="flex items-start">
              <div className="bg-blue-600 p-3 rounded-lg mr-4">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" />
                </svg>
              </div>
              <div>
                <h3 className="text-xl font-medium mb-1">Phone</h3>
                <p className="text-gray-300">+0 (123) 456-7890</p>
              </div>
            </div>
          </div>

          <div className="mt-10">
            <h2 className="text-3xl font-semibold mb-6">Working hours</h2>
            <div className="bg-gradient-to-br from-gray-800/50 to-gray-900/50 rounded-xl p-6 backdrop-blur-sm">
              <div className="flex justify-between py-2 border-b border-gray-700">
                <span>Monday - Friday:</span>
                <span>09:00 - 18:00</span>
              </div>
              <div className="flex justify-between py-2 border-b border-gray-700">
                <span>Saturday:</span>
                <span>10:00 - 15:00</span>
              </div>
              <div className="flex justify-between py-2">
                <span>Sunday:</span>
                <span>Closed</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Now let's create the contact form component in the file src/app/contact/ContactForm.tsx:

// src/app/contact/ContactForm.tsx
"use client";

import { useState } from 'react';

export default function ContactForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    subject: '',
    message: ''
  });

  const [formStatus, setFormStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prevData => ({
      ...prevData,
      [name]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setFormStatus('loading');

    // In a real application, this would handle the form, e.g., send data to an API
    try {
      // Simulating server response delay
      await new Promise(resolve => setTimeout(resolve, 1500));

      // Simulating success
      setFormStatus('success');
      setFormData({
        name: '',
        email: '',
        subject: '',
        message: ''
      });
    } catch (error) {
      setFormStatus('error');
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div>
        <label htmlFor="name" className="block text-sm font-medium mb-1">
          Full name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
          required
          className="w-full px-4 py-2 bg-gray-800/60 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>

      <div>
        <label htmlFor="email" className="block text-sm font-medium mb-1">
          Email <span className="text-red-500">*</span>
        </label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          required
          className="w-full px-4 py-2 bg-gray-800/60 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>

      <div>
        <label htmlFor="subject" className="block text-sm font-medium mb-1">
          Subject <span className="text-red-500">*</span>
        </label>
        <select
          id="subject"
          name="subject"
          value={formData.subject}
          onChange={handleChange}
          required
          className="w-full px-4 py-2 bg-gray-800/60 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="">Select a subject</option>
          <option value="booking">Mission booking</option>
          <option value="info">Mission information</option>
          <option value="career">Joining the crew</option>
          <option value="other">Other</option>
        </select>
      </div>

      <div>
        <label htmlFor="message" className="block text-sm font-medium mb-1">
          Message <span className="text-red-500">*</span>
        </label>
        <textarea
          id="message"
          name="message"
          value={formData.message}
          onChange={handleChange}
          required
          rows={5}
          className="w-full px-4 py-2 bg-gray-800/60 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        ></textarea>
      </div>

      <button
        type="submit"
        disabled={formStatus === 'loading'}
        className="w-full px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-colors disabled:opacity-70"
      >
        {formStatus === 'loading' ? 'Sending...' : 'Send message'}
      </button>

      {formStatus === 'success' && (
        <div className="p-4 bg-green-900/40 border border-green-500 rounded-lg text-green-200">
          Thank you for your message! We will respond as soon as possible.
        </div>
      )}

      {formStatus === 'error' && (
        <div className="p-4 bg-red-900/40 border border-red-500 rounded-lg text-red-200">
          An error occurred while sending the message. Please try again later.
        </div>
      )}
    </form>
  );
}

Creating the 404 (Not Found) Page

Let's add a 404 page that will be displayed when a user navigates to a non-existent path. Create the file src/app/not-found.tsx:

// src/app/not-found.tsx
import Link from 'next/link';

export default function NotFound() {
  return (
    <div className="min-h-[80vh] flex flex-col items-center justify-center p-4 text-center">
      <h1 className="text-9xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
        404
      </h1>
      <h2 className="text-4xl font-bold mt-4 mb-6">Lost in space</h2>
      <p className="text-xl text-gray-300 mb-8 max-w-xl">
        It looks like you've wandered into deep space. Unfortunately, the page you're
        looking for is beyond our quantum range.
      </p>
      <Link
        href="/"
        className="px-8 py-3 rounded-full bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:from-blue-700 hover:to-purple-700 transition-colors"
      >
        Return to Earth
      </Link>
    </div>
  );
}

Running the Application

Now we can run our application locally using the command:

npm run dev

After starting the development server, navigate to http://localhost:3000 in your browser to see your "Hello World" page for the space company.

Building and Deploying

When you're satisfied with the application running locally, you can build and prepare it for deployment:

npm run build

This command will generate an optimized production version of the application in the .next/ directory. You can also test this version locally by running:

npm run start

Deploying to Vercel

Next.js is created and maintained by Vercel, so deploying on this platform is extremely simple:

  1. Create an account on Vercel (if you don't have one yet)
  2. Connect your repository to Vercel (GitHub, GitLab, or Bitbucket)
  3. Select your project and click "Import"
  4. Vercel will automatically detect that it's a Next.js application and configure the deployment
  5. Click "Deploy" and wait for the process to complete

After deployment, Vercel will provide you with a URL where your application is publicly accessible.

What's Next?

We've created a simple but elegant and functional website for a space company using Next.js 16 and App Router. Here are some suggestions for further development:

  1. Add an "About Us" subpage with the company's history and mission
  2. Implement animations using libraries like Framer Motion
  3. Add real form handling using Server Actions
  4. Integrate a CMS (e.g., Contentful, Sanity) for content management
  5. Add internationalization (i18n) for multiple language support
  6. Implement an authentication system for customers and crew members

As you expand the application, remember the principles and best practices learned in previous lessons, especially about proper separation into Server and Client Components.

Congratulations! You've just created your first Next.js 16 application using the App Router.

Code for this lesson: App.tsx
// State Management - Metropolis Quantum
import React, { useState, createContext, useContext } from 'react';

console.log("State Management in React");
console.log("Context API & Lifting State Up\n");

// ==========================================
// 1. Lifting State Up
// ==========================================

function TemperatureInput({ scale, temperature, onTemperatureChange }: any) {
  return (
    <div style={{ marginBottom: '15px' }}>
      <label style={{ display: 'block', marginBottom: '5px', color: '#64ffda' }}>
        Temperature in {scale === 'celsius' ? 'Celsius' : 'Fahrenheit'}:
      </label>
      <input
        type="number"
        value={temperature}
        onChange={(e) => onTemperatureChange(e.target.value)}
        style={{
          width: '100%',
          padding: '10px',
          borderRadius: '6px',
          border: '1px solid #64ffda',
          background: 'rgba(255, 255, 255, 0.1)',
          color: 'white',
          fontSize: '1rem'
        }}
      />
    </div>
  );
}

function TemperatureCalculator() {
  const [temperature, setTemperature] = useState('');
  const [scale, setScale] = useState('celsius');

  const handleCelsiusChange = (temp: string) => {
    setTemperature(temp);
    setScale('celsius');
  };

  const handleFahrenheitChange = (temp: string) => {
    setTemperature(temp);
    setScale('fahrenheit');
  };

  const toCelsius = (fahrenheit: number) => (fahrenheit - 32) * 5 / 9;
  const toFahrenheit = (celsius: number) => (celsius * 9 / 5) + 32;

  const celsius = scale === 'fahrenheit' ? toCelsius(parseFloat(temperature)) : parseFloat(temperature);
  const fahrenheit = scale === 'celsius' ? toFahrenheit(parseFloat(temperature)) : parseFloat(temperature);

  return (
    <div style={{
      background: 'rgba(255, 255, 255, 0.1)',
      padding: '20px',
      borderRadius: '12px',
      border: '2px solid #7c4dff'
    }}>
      <h3 style={{ color: '#7c4dff' }}>Temperature Converter (Lifting State Up)</h3>

      <TemperatureInput
        scale="celsius"
        temperature={scale === 'celsius' ? temperature : isNaN(celsius) ? '' : celsius.toFixed(1)}
        onTemperatureChange={handleCelsiusChange}
      />

      <TemperatureInput
        scale="fahrenheit"
        temperature={scale === 'fahrenheit' ? temperature : isNaN(fahrenheit) ? '' : fahrenheit.toFixed(1)}
        onTemperatureChange={handleFahrenheitChange}
      />

      <div style={{
        marginTop: '15px',
        padding: '15px',
        background: celsius >= 100 ? 'rgba(244, 67, 54, 0.3)' : 'rgba(33, 150, 243, 0.3)',
        borderRadius: '8px',
        textAlign: 'center'
      }}>
        {celsius >= 100 ? 'Water is boiling!' : 'Water is not boiling'}
      </div>
    </div>
  );
}

// ==========================================
// 2. Context API
// ==========================================

interface ThemeContextType {
  theme: 'dark' | 'light';
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType>({
  theme: 'dark',
  toggleTheme: () => {}
});

function ThemeButton() {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <button
      onClick={toggleTheme}
      style={{
        background: theme === 'dark'
          ? 'linear-gradient(45deg, #7c4dff, #e91e63)'
          : 'linear-gradient(45deg, #ff9800, #ffeb3b)',
        color: 'white',
        border: 'none',
        padding: '12px 24px',
        borderRadius: '8px',
        cursor: 'pointer',
        fontWeight: 'bold',
        fontSize: '1rem'
      }}
    >
      {theme === 'dark' ? 'Dark Mode' : 'Light Mode'}
    </button>
  );
}

function ThemedPanel() {
  const { theme } = useContext(ThemeContext);

  return (
    <div style={{
      background: theme === 'dark'
        ? 'rgba(255, 255, 255, 0.1)'
        : 'rgba(255, 152, 0, 0.2)',
      padding: '20px',
      borderRadius: '12px',
      border: `2px solid ${theme === 'dark' ? '#64ffda' : '#ff9800'}`,
      marginTop: '20px'
    }}>
      <h3 style={{ color: theme === 'dark' ? '#64ffda' : '#ff9800' }}>
        Themed Panel
      </h3>
      <p style={{ color: theme === 'dark' ? '#b0bec5' : '#5d4037' }}>
        This panel automatically adjusts to the current theme thanks to Context API!
      </p>
      <p style={{ color: theme === 'dark' ? '#b0bec5' : '#5d4037' }}>
        Current theme: <strong>{theme === 'dark' ? 'Dark' : 'Light'}</strong>
      </p>
    </div>
  );
}

// ==========================================
// 3. User Context Example
// ==========================================

interface User {
  name: string;
  role: string;
  level: number;
}

interface UserContextType {
  user: User | null;
  login: (user: User) => void;
  logout: () => void;
}

const UserContext = createContext<UserContextType>({
  user: null,
  login: () => {},
  logout: () => {}
});

function UserProfile() {
  const { user, logout } = useContext(UserContext);

  if (!user) return null;

  return (
    <div style={{
      background: 'rgba(76, 175, 80, 0.2)',
      padding: '15px',
      borderRadius: '10px',
      border: '2px solid #4caf50',
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center'
    }}>
      <div>
        <h4 style={{ color: '#4caf50', margin: '0 0 5px 0' }}>{user.name}</h4>
        <p style={{ margin: '5px 0', color: '#b0bec5' }}>Role: {user.role}</p>
        <p style={{ margin: '5px 0', color: '#ff9800' }}>Level: {user.level}</p>
      </div>
      <button
        onClick={logout}
        style={{
          background: 'linear-gradient(45deg, #f44336, #e91e63)',
          color: 'white',
          border: 'none',
          padding: '8px 16px',
          borderRadius: '6px',
          cursor: 'pointer',
          fontWeight: 'bold'
        }}
      >
        Logout
      </button>
    </div>
  );
}

function LoginForm() {
  const { login } = useContext(UserContext);
  const [name, setName] = useState('');

  const handleLogin = () => {
    if (name.trim()) {
      login({
        name: name,
        role: 'Quantum Engineer',
        level: Math.floor(Math.random() * 50) + 1
      });
    }
  };

  return (
    <div style={{
      background: 'rgba(33, 150, 243, 0.2)',
      padding: '20px',
      borderRadius: '12px',
      border: '2px solid #2196f3'
    }}>
      <h3 style={{ color: '#2196f3' }}>Login to Quantum System</h3>
      <input
        type="text"
        placeholder="Enter your name..."
        value={name}
        onChange={(e) => setName(e.target.value)}
        style={{
          width: '100%',
          padding: '12px',
          marginTop: '15px',
          borderRadius: '6px',
          border: '1px solid #2196f3',
          background: 'rgba(255, 255, 255, 0.1)',
          color: 'white',
          fontSize: '1rem'
        }}
      />
      <button
        onClick={handleLogin}
        style={{
          marginTop: '15px',
          width: '100%',
          background: 'linear-gradient(45deg, #2196f3, #21cbf3)',
          color: 'white',
          border: 'none',
          padding: '12px',
          borderRadius: '6px',
          cursor: 'pointer',
          fontWeight: 'bold',
          fontSize: '1rem'
        }}
      >
        Login
      </button>
    </div>
  );
}

// ==========================================
// Main App with Providers
// ==========================================
function App() {
  const [theme, setTheme] = useState<'dark' | 'light'>('dark');
  const [user, setUser] = useState<User | null>(null);

  const toggleTheme = () => {
    setTheme(prev => prev === 'dark' ? 'light' : 'dark');
    console.log(`Theme changed to: ${theme === 'dark' ? 'light' : 'dark'}`);
  };

  const login = (newUser: User) => {
    setUser(newUser);
    console.log(`User logged in: ${newUser.name}`);
  };

  const logout = () => {
    setUser(null);
    console.log("User logged out");
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <UserContext.Provider value={{ user, login, logout }}>
        <div style={{
          padding: '20px',
          background: theme === 'dark'
            ? 'linear-gradient(135deg, #0f0f23 0%, #1a1a2e 100%)'
            : 'linear-gradient(135deg, #fafafa 0%, #e0e0e0 100%)',
          minHeight: '100vh',
          color: theme === 'dark' ? 'white' : '#333',
          transition: 'all 0.3s ease'
        }}>
          <h1 style={{
            textAlign: 'center',
            color: theme === 'dark' ? '#64ffda' : '#ff9800'
          }}>
            State Management Demo
          </h1>

          <div style={{ display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
            <ThemeButton />
          </div>

          <div style={{ marginTop: '30px' }}>
            <TemperatureCalculator />
          </div>

          <ThemedPanel />

          <div style={{ marginTop: '30px' }}>
            {user ? <UserProfile /> : <LoginForm />}
          </div>

          <div style={{
            marginTop: '30px',
            background: theme === 'dark'
              ? 'rgba(100, 255, 218, 0.1)'
              : 'rgba(255, 152, 0, 0.2)',
            padding: '20px',
            borderRadius: '10px',
            borderLeft: `4px solid ${theme === 'dark' ? '#64ffda' : '#ff9800'}`
          }}>
            <h3>State Management Patterns:</h3>
            <ul style={{ lineHeight: '1.8' }}>
              <li><strong>Lifting State Up</strong>: Move state to common parent</li>
              <li><strong>Context API</strong>: Global state without prop drilling</li>
              <li><strong>Custom Hooks</strong>: Reusable state logic</li>
              <li><strong>Redux/Zustand</strong>: For larger applications</li>
            </ul>
          </div>
        </div>
      </UserContext.Provider>
    </ThemeContext.Provider>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which of the following is a correct method for rendering a list in React?

  2. 2. The 'key' attribute in React is needed when:

  3. 3. What does the npm run build (next build) command do in a Next.js project?

Hands-on tasks in the game

  • Code editor

    Create a LoginStatus component that takes an isLoggedIn prop (true or false) and displays "Logged in" when isLoggedIn is true, or "Not logged in" when it is false. Use conditional rendering (the ? : operator or if).

  • Code editor

    In the App component, create a <button> that shows an alert with the message 'Button was clicked!' when it is clicked (onClick).

  • Click in order

    Arrange the syntax for declaring a Client Component in Next.js

  • Code editor

    Create a DroneControlPanel component (export default) with an <h1> heading "Drone panel" and a <nav> element with three <Link> links from next/link: "Map" (/map), "Status" (/status) and "Settings" (/settings).

  • Vertical ordering

    Arrange the path to a Route Handler file in Next.js, followed by the function the file exports

  1. QuestionAdvanced: Rendering Lists in React
  2. QuestionAdvanced: The key Attribute in React
  3. Coding taskAdvanced: Practice: Conditional Rendering
  4. QuestionThe npm run build Command
  5. Coding taskAdvanced: Practice: Handling onClick Events
  6. Click in orderSyntax of the 'use client' Directive
  7. Coding taskPractice: Drone Control Panel
  8. Put in orderPath to a Route Handler

Useful articles