Lesson 23-React Advanced Application Development

Server-Side Rendering (SSR)

Next.js Basic Configuration and Routing Management

Next.js Project Initialization:

npx create-next-app@latest my-ssr-app
# or
yarn create next-app my-ssr-app

File-Based Routing:

pages/
├── index.tsx         # /
├── about.tsx         # /about
├── blog/
│   ├── [id].tsx      # /blog/:id (dynamic route)
│   └── index.tsx     # /blog
└── api/
    └── hello.ts      # /api/hello (API route)

Custom Route Configuration:

// next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/old-path',
        destination: '/new-path'
      }
    ]
  }
}

Nested Routing Implementation:

// pages/dashboard/layout.tsx
import { Outlet } from 'next/navigation'

export default function DashboardLayout() {
  return (
    <div>
      <DashboardSidebar />
      <main>
        <Outlet /> {/* Child route content renders here */}
      </main>
    </div>
  )
}

// pages/dashboard/settings.tsx
// Automatically becomes /dashboard/settings

Data Prefetching and State Synchronization

getServerSideProps (Server-Side Fetching):

// pages/posts/[id].tsx
export async function getServerSideProps(context) {
  const { params, req, res } = context
  const postId = params.id
  const res = await fetch(`https://api.example.com/posts/${postId}`)
  const post = await res.json()

  return {
    props: { post } // Passed as props to the page component
  }
}

export default function PostPage({ post }) {
  // Directly use prefetched data
}

getStaticProps (Static Generation):

// pages/products.tsx
export async function getStaticProps() {
  const products = await fetchProducts()
  return {
    props: { products },
    revalidate: 60 // ISR: Revalidate every 60 seconds
  }
}

Client-Side Data Fetching:

// Using SWR or React Query
import useSWR from 'swr'

function UserProfile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>
  return <div>Hello {data.name}!</div>
}

SSR Performance Optimization

Incremental Static Regeneration (ISR):

// pages/blog/[slug].tsx
export async function getStaticProps({ params }) {
  const post = await getPostBySlug(params.slug)
  return {
    props: { post },
    revalidate: 3600 // Regenerate every hour
  }
}

Streaming SSR (React 18):

// Using Suspense boundaries to split rendering
import { Suspense } from 'react'

export default function Page() {
  return (
    <Suspense fallback={<HeaderSkeleton />}>
      <Header />
    </Suspense>
    <Suspense fallback={<MainSkeleton />}>
      <MainContent />
    </Suspense>
  )
}

Cache Strategy Optimization:

  1. Edge Caching: Configure CDN to cache static assets.
  2. Memory Caching: Use Redis to cache database query results.
  3. Browser Caching: Set appropriate Cache-Control headers.

SSR Security and Error Handling

Security Measures:

// Prevent XSS attacks
import sanitizeHtml from 'sanitize-html'

export async function getServerSideProps(context) {
  const rawData = await fetchUnsafeData()
  const safeData = {
    content: sanitizeHtml(rawData.content, {
      allowedTags: ['p', 'b', 'i', 'em', 'strong']
    })
  }
  return { props: safeData }
}

Error Boundary Handling:

// pages/_error.tsx
import ErrorComponent from '../components/ErrorComponent'

export default function CustomError({ statusCode }) {
  return <ErrorComponent statusCode={statusCode} />
}

// Fetch error information
CustomError.getInitialProps = ({ res, err }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404
  return { statusCode }
}

SSR Use Cases

SEO Optimization Example:

// pages/product/[id].tsx
export async function getServerSideProps({ params }) {
  const product = await fetchProduct(params.id)
  return {
    props: { 
      product,
      // Directly inject SEO metadata
      seo: {
        title: product.name,
        description: product.description
      }
    }
  }
}

export default function ProductPage({ product, seo }) {
  return (
    <>
      <Head>
        <title>{seo.title}</title>
        <meta name="description" content={seo.description} />
      </Head>
      {/* Product details */}
    </>
  )
}

First Screen Performance Optimization:

  1. Inline critical CSS.
  2. Preload fonts.
  3. Lazy-load images.
  4. Code splitting.

Static Site Generation (SSG)

Next.js Static Generation Mechanism

Build-Time Generation:

# Pre-generate all pages during build
npm run build
# Output to .out directory

Incremental Static Regeneration:

// pages/events/[id].tsx
export async function getStaticProps({ params }) {
  const event = await getEvent(params.id)
  return {
    props: { event },
    revalidate: 86400 // Revalidate daily
  }
}

export async function getStaticPaths() {
  const events = await getAllEventIds()
  return {
    paths: events.map(id => ({ params: { id } })),
    fallback: 'blocking' // Generate new pages on first access
  }
}

Content Management and Dynamic Routing

CMS Integration Example:

// lib/cms.js
export async function fetchCMSContent(slug) {
  const res = await fetch(`${CMS_API}/content/${slug}`)
  if (!res.ok) throw new Error('Failed to fetch content')
  return res.json()
}

// pages/blog/[slug].tsx
export async function getStaticProps({ params }) {
  const content = await fetchCMSContent(params.slug)
  return { props: { content } }
}

Dynamic Route Configuration:

// pages/articles/[category]/[slug].tsx
export async function getStaticPaths() {
  const articles = await getAllArticles()
  const paths = articles.map(article => ({
    params: {
      category: article.category,
      slug: article.slug
    }
  }))
  return { paths, fallback: false }
}

SSG Performance Optimization

Preloading Critical Resources:

// pages/_app.tsx
import Head from 'next/head'

export default function MyApp({ Component, pageProps }) {
  return (
    <>
      <Head>
        <link rel="preload" href="/fonts/example.woff2" as="font" />
        <link rel="preconnect" href="https://api.example.com" />
      </Head>
      <Component {...pageProps} />
    </>
  )
}

Image Optimization:

// Using Next.js Image component
import Image from 'next/image'

export default function Hero() {
  return (
    <Image
      src="/hero.jpg"
      alt="Hero image"
      width={1200}
      height={600}
      priority // Preload critical image
      placeholder="blur" // Blur placeholder
    />
  )
}

SSG and CMS Integration

Headless CMS Solutions:

  1. Contentful:
import { createClient } from 'contentful'

const client = createClient({
  space: process.env.CONTENTFUL_SPACE_ID,
  accessToken: process.env.CONTENTFUL_ACCESS_TOKEN
})

export async function getBlogPosts() {
  const entries = await client.getEntries({ content_type: 'blogPost' })
  return entries.items
}
  1. Strapi:
export async function getStaticProps() {
  const res = await fetch(`${process.env.STRAPI_API}/articles`)
  const articles = await res.json()
  return { props: { articles } }
}

SSG Use Cases

Documentation Website Optimization:

// pages/docs/[version]/[slug].tsx
export async function getStaticProps({ params }) {
  const { version, slug } = params
  const doc = await fetchDocByVersion(version, slug)
  return { props: { doc } }
}

export async function getStaticPaths() {
  const versions = await fetchVersions()
  const paths = []

  for (const version of versions) {
    const docs = await fetchDocsByVersion(version.id)
    paths.push(...docs.map(doc => ({
      params: { version: version.id, slug: doc.slug }
    })))
  }

  return { paths, fallback: 'blocking' }
}

Blog System Implementation:

  1. Use Markdown files as content source.
  2. Convert to HTML during build.
  3. Generate tag and category pages.
  4. Implement RSS subscription functionality.

Real-Time Application Development

WebSocket Integration with React

WebSocket Connection Management:

// hooks/useWebSocket.ts
import { useEffect, useRef, useState } from 'react'

export function useWebSocket(url) {
  const ws = useRef(null)
  const [messages, setMessages] = useState([])
  const [isConnected, setIsConnected] = useState(false)

  useEffect(() => {
    ws.current = new WebSocket(url)

    ws.current.onopen = () => {
      setIsConnected(true)
    }

    ws.current.onmessage = (event) => {
      setMessages(prev => [...prev, JSON.parse(event.data)])
    }

    ws.current.onclose = () => {
      setIsConnected(false)
    }

    return () => {
      ws.current?.close()
    }
  }, [url])

  const sendMessage = (data) => {
    if (ws.current?.readyState === WebSocket.OPEN) {
      ws.current.send(JSON.stringify(data))
    }
  }

  return { messages, isConnected, sendMessage }
}

Real-Time Data Display:

// components/StockPrice.tsx
export default function StockPrice({ symbol }) {
  const { messages } = useWebSocket(`wss://api.example.com/stocks/${symbol}`)

  const latestPrice = messages.length > 0 
    ? messages[messages.length - 1].price 
    : null

  return (
    <div>
      <h2>{symbol}</h2>
      <p>Price: {latestPrice?.toFixed(2) || 'Loading...'}</p>
    </div>
  )
}

GraphQL Integration with React

Apollo Client Configuration:

// lib/apollo.ts
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'

const client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.example.com/graphql',
    headers: {
      authorization: `Bearer ${localStorage.getItem('token')}`
    }
  }),
  cache: new InMemoryCache()
})

export default client

GraphQL Query Component:

// pages/user/[id].tsx
import { gql, useQuery } from '@apollo/client'

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
      posts {
        title
      }
    }
  }
`

export default function UserPage({ id }) {
  const { loading, error, data } = useQuery(GET_USER, {
    variables: { id }
  })

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error: {error.message}</p>

  return (
    <div>
      <h1>{data.user.name}</h1>
      <p>Email: {data.user.email}</p>
      <h2>Posts</h2>
      <ul>
        {data.user.posts.map(post => (
          <li key={post.title}>{post.title}</li>
        ))}
      </ul>
    </div>
  )
}

Real-Time Collaborative Editing

CRDT Implementation Principles:

  1. Data Structure: Use operation-based CRDTs (e.g., Yjs).
  2. Synchronization Mechanism: Broadcast operations via WebSocket.
  3. Conflict Resolution: Automatically merge concurrent edits.

Integration Example:

// components/CollaborativeEditor.tsx
import { WebsocketProvider } from 'y-websocket'
import * as Y from 'yjs'

export default function CollaborativeEditor({ room }) {
  const ydoc = new Y.Doc()
  const provider = new WebsocketProvider(
    'wss://collab.example.com',
    room,
    ydoc
  )

  const ys = ydoc.getText('document')
  const textarea = useRef(null)

  useEffect(() => {
    const binding = new Y.TextBinding(ys, textarea.current)
    return () => {
      provider.destroy()
      binding.destroy()
    }
  }, [room])

  return <textarea ref={textarea} />
}

Real-Time Communication Optimization

Bandwidth Optimization Strategies:

  1. Data Compression: Use gzip or Brotli compression.
  2. Throttling Control: Limit update frequency (e.g., 10 times per second).
  3. Incremental Updates: Send only changed data.

Connection Reliability Enhancement:

// WebSocket with auto-reconnect
function createReliableWebSocket(url) {
  let ws = new WebSocket(url)
  let reconnectAttempts = 0
  const maxReconnectAttempts = 5

  ws.onclose = () => {
    if (reconnectAttempts < maxReconnectAttempts) {
      const delay = Math.min(1000 * 2 ** reconnectAttempts, 30000)
      setTimeout(() => {
        reconnectAttempts++
        ws = createReliableWebSocket(url)
      }, delay)
    }
  }

  return ws
}

Real-Time Application Security

Authentication and Authorization:

// WebSocket connection authentication
const ws = new WebSocket('wss://api.example.com/ws')
ws.onopen = () => {
  ws.send(JSON.stringify({
    type: 'auth',
    token: localStorage.getItem('jwt')
  }))
}

// Server-side verification
wss.on('connection', (ws, req) => {
  ws.on('message', (message) => {
    const data = JSON.parse(message)
    if (data.type === 'auth') {
      jwt.verify(data.token, SECRET, (err, user) => {
        if (err) {
          ws.close(1008, 'Unauthorized')
        } else {
          ws.user = user
        }
      })
    }
  })
})

Data Validation:

  1. Input Validation: Use Joi or Yup to validate message structures.
  2. Rate Limiting: Prevent DoS attacks.
  3. Operation Auditing: Log all critical operations.

By applying these advanced application development techniques, you can build high-performance, real-time React applications that meet the demands of complex business scenarios.

Share your love