Next.js course ยท Module 1: Next.js Configuration

Development Environment - Tools and Practices

18 min read ยท
In this lesson4

In Quantum Metropolis, quantum engineers need advanced workstations, precise tools, and optimized processes to efficiently design and maintain the city's advanced systems. Similarly, as a Next.js 16 developer, your development environment is the foundation of your productivity and code quality.

Quantum Metropolis Command Center

Let's start by configuring the ideal development environment - your personal Command Center for Next.js 16 projects.

Basic Tools

1. Code Editor - Quantum Terminal

The heart of every quantum engineer's workstation is the Quantum Terminal. For Next.js 16 developers, Visual Studio Code (VS Code) with extensions is the best choice:

# Install basic extensions
code --install-extension dbaeumer.vscode-eslint
code --install-extension esbenp.prettier-vscode
code --install-extension bradlc.vscode-tailwindcss
code --install-extension ms-vscode.vscode-typescript-next
code --install-extension dsznajder.es7-react-js-snippets

VSCode configuration for Next.js 16 projects - file .vscode/settings.json:

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "tailwindCSS.includeLanguages": {
    "typescript": "javascript",
    "typescriptreact": "javascript"
  },
  "tailwindCSS.experimental.classRegex": [
    ["cn\\(([^)]*)\\)", "'([^']*)'"]
  ],
  "files.associations": {
    "*.css": "tailwindcss"
  }
}

2. Version Control System - Quantum Archives

In Quantum Metropolis, every change to city systems is carefully recorded and stored in the Quantum Archives. In our world, we use Git:

# Initialize a Git repository for the project
git init

# Create a .gitignore file for Next.js projects
curl -fsSL https://raw.githubusercontent.com/github/gitignore/main/Nextjs.gitignore -o .gitignore

The .gitignore file for a Next.js 16 project:

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

This is the .gitignore that create-next-app generates in Next.js 16. Note the .env* line: since Next.js 15 all environment files are ignored, not only .env*.local, so secrets do not end up in the repository by accident. If you want to commit a file with example values, add an exception such as !.env.example.

3. Package Management - Quantum Resource Matrix

Engineers in Quantum Metropolis use the Quantum Resource Matrix to obtain exactly the components they need. We use npm, yarn, or pnpm:

# Initialize a Next.js 16 project with Tailwind CSS and TypeScript
npx create-next-app@latest quantum-project
# Choose "Yes, use recommended defaults": TypeScript, ESLint,
# Tailwind CSS, App Router and AGENTS.md in one step

Optionally, you can configure pnpm for better performance:

# Install pnpm
npm install -g pnpm

# Initialize project with pnpm
pnpm dlx create-next-app@latest quantum-project

Productivity Tools

1. ESLint - Quantum Anomaly Detector

In Quantum Metropolis, advanced scanners constantly monitor code looking for potential bugs and suboptimal patterns. In the world of Next.js 16, ESLint serves this function:

npm install --save-dev eslint-plugin-jsx-a11y

The eslint-config-next package already includes the recommended rules of the react and react-hooks plugins and registers the jsx-a11y plugin with a few accessibility rules, so we only install eslint-plugin-jsx-a11y to turn on its full recommended set. ESLint configuration in eslint.config.mjs:

// eslint.config.mjs
import { defineConfig, globalIgnores } from 'eslint/config';
import nextVitals from 'eslint-config-next/core-web-vitals';
import nextTs from 'eslint-config-next/typescript';
import jsxA11y from 'eslint-plugin-jsx-a11y';

const eslintConfig = defineConfig([
  ...nextVitals,
  ...nextTs,
  {
    rules: {
      ...jsxA11y.flatConfigs.recommended.rules,
      'react/react-in-jsx-scope': 'off',
      'react/prop-types': 'off',
      '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
      'jsx-a11y/anchor-is-valid': ['error', {
        components: ['Link'],
        specialLink: ['hrefLeft', 'hrefRight'],
        aspects: ['invalidHref', 'preferButton'],
      }],
    },
  },
  globalIgnores(['.next/**', 'out/**', 'build/**', 'next-env.d.ts']),
]);

export default eslintConfig;

Rules listed after the spread recommended set override its settings, which is why anchor-is-valid understands the Next.js Link component. The React version setting (settings.react.version) is no longer needed, because eslint-config-next detects it automatically.

2. Prettier - Quantum Code Harmonizer

Just as in Quantum Metropolis all structures must be perfectly harmonized, your code should be consistently formatted:

npm install --save-dev prettier eslint-config-prettier

Prettier configuration in .prettierrc:

{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "printWidth": 100,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "arrowParens": "avoid"
}

And add the eslint-config-prettier config at the end of the array in eslint.config.mjs to switch off ESLint rules that clash with formatting:

// eslint.config.mjs (fragment)
import prettier from 'eslint-config-prettier/flat';

const eslintConfig = defineConfig([
  ...nextVitals,
  ...nextTs,
  // ...rest of the configuration
  prettier,
  globalIgnores(['.next/**', 'out/**', 'build/**', 'next-env.d.ts']),
]);

3. Husky and lint-staged - Automatic Quantum Guards

In Quantum Metropolis, before any code is introduced to city systems, it goes through a series of automatic tests and validations. Similarly, we can configure Husky and lint-staged:

npm install --save-dev husky lint-staged
npx husky init
echo "npx lint-staged" > .husky/pre-commit

lint-staged configuration in package.json:

{
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{json,css,md}": [
      "prettier --write"
    ]
  }
}

4. TypeScript - Quantum Type System

In Quantum Metropolis, all components must strictly follow their specifications to ensure the safety of the entire system. TypeScript provides similar safety for your code:

# TypeScript is already installed in a Next.js 16 project
# Let's configure stricter TypeScript rules

tsconfig.json configuration:

{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts", "**/*.mts"],
  "exclude": ["node_modules"]
}

This is tsconfig.json in a Next.js 16 project, extended with the noUncheckedIndexedAccess option (noImplicitAny and strictNullChecks are already enabled by "strict": true). create-next-app sets "jsx": "react-jsx" and "moduleResolution": "bundler", and adds the .next/dev/types directory to include, because next dev now writes its files separately to .next/dev.

Testing Tools - Quantum Simulations

Engineers in Quantum Metropolis run thousands of simulations before every change to ensure city systems will work flawlessly. The equivalent in the Next.js 16 world are testing tools:

1. Jest and React Testing Library - Basic Simulations

npm install --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom

Configuration file jest.config.js:

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  // Folder where next.config.js and node_modules are located
  dir: './',
});

// Jest configuration
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
};

// Export the configuration
module.exports = createJestConfig(customJestConfig);

Setup file jest.setup.js:

// Jest extensions
import '@testing-library/jest-dom';

Test scripts in package.json:

{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch"
  }
}

2. Cypress - Advanced Simulations

npm install --save-dev cypress

Initialize Cypress:

npx cypress open

Add scripts to package.json:

{
  "scripts": {
    "cypress": "cypress open",
    "cypress:headless": "cypress run"
  }
}

3. Storybook - Quantum Component Library

npm create storybook@latest

The wizard asks whether to use the Vite-based or the Webpack-based version. Configure Storybook for Next.js 16 in .storybook/main.ts:

// .storybook/main.ts
import type { StorybookConfig } from '@storybook/nextjs-vite';

const config: StorybookConfig = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: ['@storybook/addon-docs'],
  framework: '@storybook/nextjs-vite',
  staticDirs: ['../public'],
};

export default config;

The @storybook/nextjs-vite framework understands Next.js specifics such as next/image, next/font and routing, which is why the Storybook documentation recommends it for most Next.js projects. Choose the Webpack-based version (@storybook/nextjs) only when you need a custom Webpack or Babel configuration.

Optimized Development Practices

In Quantum Metropolis, every engineer follows strictly defined standards and procedures. Let's look at the best practices for Next.js 16 developers.

1. Project Structure - Metropolis Blueprint

Just as Quantum Metropolis is divided into precisely designed sectors, your Next.js 16 project should have a clear structure:

quantum-voyages/
  โ”œโ”€โ”€ .husky/                # Husky configuration
  โ”œโ”€โ”€ .vscode/               # VS Code configuration
  โ”œโ”€โ”€ public/                # Static assets
  โ”œโ”€โ”€ src/
  โ”‚   โ”œโ”€โ”€ app/               # App Router - routes and pages
  โ”‚   โ”‚   โ”œโ”€โ”€ (auth)/        # Logical grouping for authorization
  โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ login/
  โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ register/
  โ”‚   โ”‚   โ”œโ”€โ”€ destinations/  # Route for destinations
  โ”‚   โ”‚   โ”œโ”€โ”€ bookings/      # Route for bookings
  โ”‚   โ”‚   โ”œโ”€โ”€ api/           # API endpoints
  โ”‚   โ”‚   โ””โ”€โ”€ layout.tsx     # Main layout
  โ”‚   โ”œโ”€โ”€ components/        # React components
  โ”‚   โ”‚   โ”œโ”€โ”€ ui/            # UI elements
  โ”‚   โ”‚   โ””โ”€โ”€ features/      # Feature-specific components
  โ”‚   โ”œโ”€โ”€ hooks/             # Custom React hooks
  โ”‚   โ”œโ”€โ”€ lib/               # Utility functions and business logic
  โ”‚   โ”œโ”€โ”€ styles/            # Global styles and themes
  โ”‚   โ”œโ”€โ”€ types/             # TypeScript type definitions
  โ”‚   โ””โ”€โ”€ utils/             # Utility functions
  โ”œโ”€โ”€ tests/                 # Integration and end-to-end tests
  โ”‚   โ”œโ”€โ”€ e2e/               # Cypress tests
  โ”‚   โ””โ”€โ”€ integration/       # Integration tests
  โ”œโ”€โ”€ .env.example           # Example environment variables file
  โ”œโ”€โ”€ .gitignore             # Git ignored files
  โ”œโ”€โ”€ .prettierrc            # Prettier configuration
  โ”œโ”€โ”€ eslint.config.mjs      # ESLint configuration (flat config)
  โ”œโ”€โ”€ jest.config.js         # Jest configuration
  โ”œโ”€โ”€ next.config.ts         # Next.js configuration
  โ”œโ”€โ”€ package.json           # Dependencies and scripts
  โ”œโ”€โ”€ postcss.config.mjs     # PostCSS configuration (for Tailwind CSS 4)
  โ””โ”€โ”€ tsconfig.json          # TypeScript configuration

2. Naming Conventions - Quantum Protocols

In Quantum Metropolis, every element has a precise name that reflects its function. Similarly in code:

// Components: PascalCase, .tsx files
// components/ui/QuantumButton.tsx
export default function QuantumButton() {
  return <button className="bg-blue-500 text-white px-4 py-2 rounded">Quantum</button>;
}

// Utility functions: camelCase, .ts files
// utils/formatDate.ts
export function formatDate(date: Date): string {
  return new Intl.DateTimeFormat('en-US').format(date);
}

// Hooks: name starts with 'use', camelCase, .ts files
// hooks/useQuantumState.ts
export function useQuantumState(initialValue: number) {
  const [state, setState] = useState(initialValue);
  //
  return { state, increment, decrement };
}

// Contexts: name ends with 'Context', PascalCase
// contexts/QuantumContext.tsx
export const QuantumContext = createContext<QuantumContextType | null>(null);

3. Git Workflows - Metropolis Version Control Protocols

In Quantum Metropolis, every change to city systems must go through a precise approval and deployment process. In the programming world, it's worth following Gitflow:

# Creating a new feature
git checkout -b feature/quantum-navigation

# Commits with descriptive messages
git commit -m "feat: Add quantum navigation component"
git commit -m "fix: Repair positioning in quantum nav"
git commit -m "docs: Add JSdoc comments to navigation functions"

# Completing the feature and merging to develop
git checkout develop
git merge feature/quantum-navigation

Commit message standards (Conventional Commits):

  1. feat: new feature
  2. fix: bug fix
  3. docs: documentation changes
  4. style: code formatting
  5. refactor: code refactoring
  6. test: adding or updating tests
  7. chore: build task updates, tools, etc.

4. Component Approach - Designing Quantum Modules

Atomic Design

In Quantum Metropolis, all systems are built from basic quantum particles that combine into increasingly complex structures. A similar model - Atomic Design - can be applied to UI design:

  1. Atoms - basic components: buttons, inputs, labels
  2. Molecules - groups of atoms: search forms, navigation
  3. Organisms - complex UI sections: headers, footers, sidebars
  4. Templates - page layouts
  5. Pages - specific instances of templates with data
components/
  โ”œโ”€โ”€ atoms/
  โ”‚   โ”œโ”€โ”€ Button.tsx
  โ”‚   โ”œโ”€โ”€ Input.tsx
  โ”‚   โ””โ”€โ”€ Label.tsx
  โ”œโ”€โ”€ molecules/
  โ”‚   โ”œโ”€โ”€ SearchForm.tsx
  โ”‚   โ””โ”€โ”€ NavLink.tsx
  โ”œโ”€โ”€ organisms/
  โ”‚   โ”œโ”€โ”€ Header.tsx
  โ”‚   โ””โ”€โ”€ Footer.tsx
  โ””โ”€โ”€ templates/
      โ”œโ”€โ”€ DashboardLayout.tsx
      โ””โ”€โ”€ AuthLayout.tsx

Components Based on the "Composition and API" Pattern

Just as in Quantum Metropolis every module has its interface and can be combined with other modules, our components should be designed modularly:

// Example component with composition pattern
import { ReactNode } from 'react';

interface CardProps {
  className?: string;
  children: ReactNode;
}

export function Card({ className, children }: CardProps) {
  return <div className={`rounded-lg shadow ${className}`}>{children}</div>;
}

Card.Header = function CardHeader({ className, children }: CardProps) {
  return <div className={`p-4 border-b ${className}`}>{children}</div>;
};

Card.Body = function CardBody({ className, children }: CardProps) {
  return <div className={`p-4 ${className}`}>{children}</div>;
};

Card.Footer = function CardFooter({ className, children }: CardProps) {
  return <div className={`p-4 border-t ${className}`}>{children}</div>;
};

// Usage
<Card className="bg-white">
  <Card.Header>Quantum Navigation</Card.Header>
  <Card.Body>Card content</Card.Body>
  <Card.Footer>Actions</Card.Footer>
</Card>

5. Task Automation - Quantum Automatic Systems

In Quantum Metropolis, many processes are automated so engineers can focus on innovation. Similarly in a Next.js 16 project:

// package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint",
    "format": "prettier --write .",
    "test": "jest",
    "test:watch": "jest --watch",
    "e2e": "cypress open",
    "storybook": "storybook dev -p 6006",
    "build-storybook": "storybook build",
    "prepare": "husky",
    "type-check": "tsc --noEmit",
    "validate": "npm-run-all --parallel lint type-check test"
  }
}

The validate script runs several commands at once with the npm-run-all tool, which you need to install: npm install --save-dev npm-run-all2 (the npm-run-all2 package provides the npm-run-all command).

6. State Management - Quantum Data Management

In Quantum Metropolis, data flows through the city via a complex quantum system. In a Next.js 16 application, we also need efficient state management:

Local State Management

// Using useState and useReducer for simple state management
"use client";

import { useState } from 'react';

export default function QuantumCounter() {
  const [count, setCount] = useState(0);

  return (
    <div className="flex items-center gap-4">
      <button
        onClick={() => setCount(c => c - 1)}
        className="px-3 py-1 bg-red-500 text-white rounded"
      >
        -
      </button>
      <span className="text-xl">{count}</span>
      <button
        onClick={() => setCount(c => c + 1)}
        className="px-3 py-1 bg-green-500 text-white rounded"
      >
        +
      </button>
    </div>
  );
}

Application-Level State Management

// Context API - for medium-sized applications
// contexts/QuantumStateContext.tsx
"use client";

import { createContext, useContext, useReducer, ReactNode } from 'react';

type State = {
  destinations: string[];
  selectedDestination: string | null;
};

type Action =
  | { type: 'ADD_DESTINATION'; payload: string }
  | { type: 'SELECT_DESTINATION'; payload: string };

const initialState: State = {
  destinations: ['Mars', 'Europa', 'Titan'],
  selectedDestination: null,
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'ADD_DESTINATION':
      return {
        ...state,
        destinations: [...state.destinations, action.payload],
      };
    case 'SELECT_DESTINATION':
      return {
        ...state,
        selectedDestination: action.payload,
      };
    default:
      return state;
  }
}

const QuantumStateContext = createContext<{
  state: State;
  dispatch: React.Dispatch<Action>;
} | undefined>(undefined);

export function QuantumStateProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <QuantumStateContext.Provider value={{ state, dispatch }}>
      {children}
    </QuantumStateContext.Provider>
  );
}

export function useQuantumState() {
  const context = useContext(QuantumStateContext);
  if (context === undefined) {
    throw new Error('useQuantumState must be used within a QuantumStateProvider');
  }
  return context;
}

For larger applications, consider state management libraries such as Zustand, Jotai, or Redux Toolkit.

7. API Strategy - Quantum Communication Protocols

In Quantum Metropolis, systems communicate using precise protocols. In Next.js 16, we have several options for implementing APIs:

Route Handlers

// app/api/destinations/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  // Fetching data from a database or external API
  const destinations = [
    { id: 1, name: 'Mars', distance: '54.6M km' },
    { id: 2, name: 'Europa', distance: '628.3M km' },
    { id: 3, name: 'Titan', distance: '1.2B km' },
  ];

  return NextResponse.json(destinations);
}

export async function POST(request: Request) {
  const body = await request.json();

  // Validation and business logic
  if (!body.name) {
    return NextResponse.json(
      { error: 'Name is required' },
      { status: 400 }
    );
  }

  // Saving to database...

  return NextResponse.json(
    { id: 4, name: body.name, distance: body.distance },
    { status: 201 }
  );
}

Server Actions

// app/destinations/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';

export async function addDestination(formData: FormData) {
  const name = formData.get('name') as string;
  const distance = formData.get('distance') as string;

  if (!name || !distance) {
    return { error: 'Name and distance are required' };
  }

  // Saving to database...

  // Refresh data
  revalidatePath('/destinations');
  redirect('/destinations');
}

React Query for API State Management

npm install @tanstack/react-query @tanstack/react-query-devtools
// app/providers.tsx
'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { useState, ReactNode } from 'react';

export function Providers({ children }: { children: ReactNode }) {
  const [queryClient] = useState(() => new QueryClient());

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}
// components/DestinationsList.tsx
'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

async function fetchDestinations() {
  const res = await fetch('/api/destinations');
  if (!res.ok) throw new Error('Failed to fetch destinations');
  return res.json();
}

export default function DestinationsList() {
  const queryClient = useQueryClient();

  const { data: destinations, isLoading, error } = useQuery({
    queryKey: ['destinations'],
    queryFn: fetchDestinations,
  });

  const mutation = useMutation({
    mutationFn: async (newDestination) => {
      const res = await fetch('/api/destinations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newDestination),
      });
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['destinations'] });
    },
  });

  if (isLoading) return <div>Loading destinations...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h2 className="text-2xl font-bold mb-4">Available destinations</h2>
      <ul className="space-y-2">
        {destinations.map((dest) => (
          <li key={dest.id} className="p-3 bg-gray-100 rounded">
            {dest.name} - {dest.distance}
          </li>
        ))}
      </ul>
    </div>
  );
}

8. Continuous Integration and Deployment (CI/CD) - Quantum Production Pipeline

In Quantum Metropolis, new technologies are systematically tested and deployed through a fully automated process. Similarly, we can configure CI/CD for our project:

GitHub Actions for CI/CD

File .github/workflows/ci.yml:

name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v7

    - name: Setup Node.js
      uses: actions/setup-node@v7
      with:
        node-version: '24'
        cache: 'npm'

    - name: Install dependencies
      run: npm ci

    - name: Lint
      run: npm run lint

    - name: Type check
      run: npm run type-check

    - name: Test
      run: npm test

    - name: Build
      run: npm run build

Deploying to Vercel

Configure Vercel integration so every push to the main branch automatically deploys the application:

  1. Connect your repository to Vercel
  2. Configure environment variables
  3. Use Preview Deployments for pull requests
  4. Automatic deployment to production after merging with the main branch

Advanced Developer Techniques

1. Performance Monitoring - Quantum Telemetry

In Quantum Metropolis, engineers constantly monitor the performance of all systems. In our Next.js 16 application:

// app/layout.tsx
import { SpeedInsights } from '@vercel/speed-insights/next';
import { Analytics } from '@vercel/analytics/react';

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

2. Progressive Enhancements and Accessibility - Universal Quantum Adaptation

In Quantum Metropolis, every citizen must have access to city systems, regardless of their limitations. Similarly, our application should be accessible to everyone:

// components/ui/QuantumButton.tsx with enhanced accessibility
"use client";

import { ButtonHTMLAttributes, forwardRef } from 'react';

interface QuantumButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'secondary' | 'danger';
  size?: 'sm' | 'md' | 'lg';
  isLoading?: boolean;
}

export const QuantumButton = forwardRef<HTMLButtonElement, QuantumButtonProps>(
  ({
    variant = 'primary',
    size = 'md',
    className = '',
    isLoading = false,
    disabled,
    children,
    ...props
  }, ref) => {
    // Map variants to classes
    const variantClasses = {
      primary: 'bg-blue-600 hover:bg-blue-700 text-white',
      secondary: 'bg-gray-200 hover:bg-gray-300 text-gray-800',
      danger: 'bg-red-600 hover:bg-red-700 text-white',
    };

    // Map sizes to classes
    const sizeClasses = {
      sm: 'text-sm px-2 py-1',
      md: 'text-base px-4 py-2',
      lg: 'text-lg px-6 py-3',
    };

    return (
      <button
        ref={ref}
        className={`rounded font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 ${variantClasses[variant]} ${sizeClasses[size]} ${isLoading || disabled ? 'opacity-70 cursor-not-allowed' : ''} ${className}`}
        disabled={isLoading || disabled}
        {...props}
      >
        {isLoading ? (
          <span className="flex items-center justify-center">
            <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-current" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            Loading...
          </span>
        ) : children}
      </button>
    );
  }
);
QuantumButton.displayName = 'QuantumButton';

3. Code Documentation - Quantum Archivist

In Quantum Metropolis, every system is thoroughly documented so future engineers can easily understand it. In our project:

/**
 * Navigation component for space travel.
 *
 * @component
 * @example
 * ~~~tsx
 * <QuantumNavigation
 *   destinations={['Mars', 'Europa', 'Titan']}
 *   onSelectDestination={(dest) => console.log(`Selected ${dest}`)}
 * />
 * ~~~
 */
export interface QuantumNavigationProps {
  /** List of available destinations */
  destinations: string[];
  /** Callback invoked when a destination is selected */
  onSelectDestination: (destination: string) => void;
  /** Currently selected destination (optional) */
  selectedDestination?: string;
}

export function QuantumNavigation({
  destinations,
  onSelectDestination,
  selectedDestination
}: QuantumNavigationProps) {
  return (
    <nav className="p-4 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-lg text-white">
      <h2 className="text-xl font-semibold mb-2">Quantum Navigation</h2>
      <ul className="space-y-1">
        {destinations.map((dest) => (
          <li key={dest}>
            <button
              className={`w-full text-left px-3 py-2 rounded hover:bg-white/20 ${
                selectedDestination === dest ? 'bg-white/30 font-medium' : ''
              }`}
              onClick={() => onSelectDestination(dest)}
            >
              {dest}
            </button>
          </li>
        ))}
      </ul>
    </nav>
  );
}

4. Team Collaboration - Quantum Collective

In Quantum Metropolis, engineers work in synchronized teams to achieve maximum efficiency. Similarly, a Next.js 16 development team should have clear collaboration processes:

  1. Code Reviews - every pull request should be reviewed by at least one other developer
  2. Pair Programming - solve harder problems in pairs
  3. Standups - short daily meetings for work synchronization
  4. Sprint Planning - planning tasks for the next sprint
  5. Retrospectives - regular meetings to discuss what works and what can be improved

Summary

Just as Quantum Metropolis engineers need advanced tools and optimal processes, Next.js 16 developers need a well-configured development environment. With the tools and practices presented, you can:

  1. Increase productivity - automation of repetitive tasks
  2. Improve code quality - linting, testing, typing
  3. Facilitate collaboration - consistent conventions, CI/CD, clear structure
  4. Speed up development - fast feedback, efficient debugging
  5. Ensure high quality - automated tests, code reviews

Remember that just as Quantum Metropolis is constantly evolving, your development environment should evolve along with the project and team. Regularly review and update your tools and processes to maintain maximum efficiency and code quality.

All the knowledge and tools presented in this module will enable you to effectively create advanced applications using Next.js 16 - just as quantum engineers in the Metropolis use their tools to design tomorrow's technologies.

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 tool is responsible for automatically formatting code on file save?

  2. 2. What are Husky and lint-staged used for in a project?

  3. 3. Which package manager saves disk space using a shared content-addressable package store?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the order of working with a feature in the Gitflow workflow

  1. QuestionCode Formatting Tool
  2. QuestionHusky and lint-staged
  3. QuestionDisk-Saving Package Manager
  4. Put in orderGit Flow for a New Feature

Useful articles