Udemy Note logo

Next.js by Example 's note

App Route vs Pages Route

⇒ 2 different ways to implement Next.js

Recommend: App Router

Block Image

Project Overview

Use cases when using NextJs: * As a Static Site * As a full-stack framework
Block Image
Block Image

Creating a Next.js Project

npx create-next-app@latest // Not recommend, can be overwhelmed
// Recommend install mannually Step 1. Create folder next-reviews Step 2. Access folder then create package.json mannually // I suggest use command: "npm init" insteady of that Step 3. Install required packacges npm install next@latest react@latest react-dom@latest
  • Start server
  • npx next dev // Start server on local => next will create folder.next => Should ignore this folder via .gitignore
    Block Image
    Above issue comes from NexJs required: 'pages' or 'app' directory Fix: create empty 'pages' directory or empty 'app' directory 'pages' ~ Page Route 'app' ~ App Route This course we use App Route => create 'app' directory then start again
    Block Image
    Block Image
    Can customize script in package.json to start serve npm run dev
    Block Image

    Create Homepage

  • Create page.jsx
  • app/page.jsx Requirement: Name of file: page.jsx // Why ??? I try with other name then it doesn't work
    Block Image
    When start project, file: layout.tsx | layout.js is generated automatically layout.tsx || layout.js depend on your programing language use for project ( typescript or javascript )
    Block Image
    layout.tsx || layout.js ~ template, it apply to all pages
    Block Image
    Block Image

    App Routes

    => Create new child page - New folder // Eg: /app/reviews - New page file // Eg: /app/reviews/page.jsx Access page: http://localhost:3000/reviews
    Block Image
  • Nested page
  • - New folder // Eg: /app/reviews/stardew-valley - New page file // Eg: /app/reviews/stardew-valley/page.jsx Access page: http://localhost:3000/reviews/stardew-valley
    Block Image
    Block Image
    Block Image
    Block Image

    Nested Layout

    Custom to specify route: * Navigate to route folder * Create layout.jsx Eg: reviews route * Navigate to 'reviews' folder * Create layout.jsx => Every pages inside 'reviews' folder is follow layout.jsx template
    Block Image
    Block Image

    Pre-rendering

    To verify NextJs render page to HTML on server or browser ? => Add log into component, log just show in server, not show in browser * Note: ReactJs just log into browser
    Block Image
    When disable javascript in dev tool: - Browser [ReactJs]: You need to enable javascript to run this app - Browser [NextJs]: Still render like normal
    Block Image
    Block Image
    Pre-rendering: a feature of Next.js Next.js has pre-rendered the app into static HTML, allowing you to see the app UI without running JavaScript

    React Server Components

    ⇒ Only render in server

    without sending any Js

    code to browser

  • Page Routes
  • Render in both server and browser

    Block Image
  • App Routes
  • App Routes just render component into server

    Default component in App Routes is Server Component

    Client Side functions not working into Server Component ( Client side function in example is side effect function via useEffect() )
    Block Image
    Fix by add "use client"; at the top => Convert Server Component into Client Component ( Can render on Client side ReactJs )
    Block Image
    Block Image

    Dev vs Production Server

    Block Image
    npx next build || npm run build => Generate an optimize production build (generate static html files, etc ) npx next start || npm run start => Start server * Dev Server Every request a page in browser => Server will regenerate page each time * Production Server When start server in production, Next.js not regenerate files after build (npx next build) All components have been pre-rendered to HTML during build process Every request a page in browser => Server returns the index.html file not generate new files => Optimized for speed
  • Log from dev server when reload page in browser
  • Block Image
  • Log from Prod server when build, have no log in browser
  • Block Image

    Link component

    To enable client-side navigation: => Use 'Link' component from 'next/link' insteady of Anchor Element ( a tag ) to have behaviour like SPA ( Single Page Application )
    Block Image

    Prefetching

    From this course: In Dev env, NextJs fetch data when mouse over on the link without click But as I know: from document, Prefetching is only enalbed in Production env
    Block Image
    In Production env, NextJs fetch all links right after loading the initial page => All requests excute in background => Users still feel the page loading fast
    Block Image

    ⇒ Execute 3 request to fetch data from 3 route

    Block Image

    ⇒ Just load single HTML document

  • Disable prefetching
  • Block Image

    Layout and Navigation

    NextJs only re-render page-specific elements not the layout elements => Users can interact with layout elements even while a page transition is in progress
    Block Image
    Inside body tag, header/ footer not changed main section is changed head section change because of metadata of each pages are different

    Install tailwind CSS

    npm install -D tailwindcss postcss autoprefixer npx tailwindcss init --postcss //Create tailwind.config.js & postcss.config.js
    Block Image
    Block Image
    Block Image

    Import Alias

    Block Image
    Create new file to store alias config jsconfig.json || tsconfig.json // depend on programming language javascript | typescript @ ~ top of our project
    Block Image
    Block Image

    Static Assets

    Create 'public' folder Any files in public folder, will be returned exactly as it is.
    Block Image

    Font Optimization

    Block Image
  • Import font
  • Block Image
    Font files were servered by Next.Js, not excute request to Google server Font files stored in .next/static/media
    Block Image
    Block Image
    Block Image

    Custom Tailwind

    Declare font variable

    Block Image

    Import variable in top of HTML

    Block Image

    Create util class with custom font in Tailwind configuration

    Block Image
    theme: { extend: { fontFamily: { orbitron: ['var(--font-orbitron)', 'sans-serif'], }, }, }, //sans-serif: backup font when custom font (--font-orbitron) is broken
    Block Image

    Custom default font

    Export new font with custom varialbe

    Block Image

    Import font variable into top of HTML

    Block Image

    Apply font to default ‘sans’

    Block Image
    Block Image

    Reading files

    Server Component Component: - async/ await - server side functionility (read file, etc)
    Block Image

    Dynamic Route

    Block Image
    [slug] ~ match any path segment in the URL Base on that value ( name of segment ) we can handle logic to navigate user to proper page
    Block Image

    Static Generation for Dynamic Routes

    ⇒ Without static files, server always generate static files then return to Client ( browser ) on every requests from users

    Block Image
    Block Image

    ⇒ With static files, users just need execute a request to server. NextJs will load initial page then prefetching all link to get data. ( don’t need execute another request to fetch data )

  • Generate static files from Dynamic Page
  • Requirement: name of fuction is 'generateStaticParams' Doc: https://nextjs.org/docs/app/api-reference/functions/generate-static-params
    Block Image
    Block Image

    Title and meta tags

    Block Image
    Block Image

    https://nextjs.org/docs/app/api-reference/functions/generate-metadata#basic-fields

    Block Image
    export const metadata into specific page can overwrite metadata from layout template

    Metadata from layout template

    Block Image

    Metadata from specific page

    Block Image

    Title template

    Set default title to every page

    Block Image

    When specific page declare title, it overwrite default title from template

    Block Image

    Dynamic Metadata

    Declare metadata to dynamic pages

    Block Image
    Block Image

    Icon and metadata files

    Block Image
    Put image into folder which includes page file NextJs converts that image into icon
    Block Image

    https://nextjs.org/docs/app/api-reference/file-conventions/metadata

    Client Component

  • Hydration process
  • Step 1

    . Browser init HTML page, component in page can’t interact ( HTML page was render on server )

    Block Image

    Step2

    . Browser load js file

    ReactJs render components on client-side (same HTML rendered by server) from js file then make components interactive ( eg: attach event handlers to button )

    Block Image
    Block Image

    https://nextjs.org/learn/foundations/how-nextjs-works/rendering

    Step3

    . Merge elements on page ( rendered by server ) to elements which are rendered on client-side

    Nested Client Components

    Block Image
    When apply 'use client' to parent compenent => Convert all child components into Client Component And will throw error if apply 'use client' into file execute logic from server's functionality
    Block Image
    Block Image
    Block Image

    Static Export

    Deploy to any server

    Step1: Create configuration to export static next.config.js Step2: Build files => npm run build
    Block Image
    Block Image
    Testing static export: npx serve@latest out Requirement: install serve package
    Block Image

    Static Hosting

    https://www.netlify.com/

    Block Image
    Upload "out" folder to deploy

    This course has another part about Page Route, please get the course to see more

    https://www.udemy.com/course/nextjs-by-example/

    Thank you for reading