본문 바로가기
Personal-Study/Next.js

[Next.js 13 공식 문서 App Router] - Routing

by Aaron-Kim 2023. 8. 24.

Routing

 

Routing Fundamentals

Terminology

- Tree

- Subtree

- Root

- Leaf

- URL Segment

- URL Path

The app Router

- The App Router takes priority over the Pages Router

Roles of Folders and Files

Route Segments

Nested Routes

File Conventions

- layout: Shared UI

- page

- loading: React Suspense boundary

- not-found: React Error boundary

- error: React Error boundary

- global-error

- route

- template: Specialized re-rendered Layout UI

- default: Fallback UI for Parallel Routes

Component Hierarchy

Colocation

- Only the contents retunred by page.js or route.js are publicly addressable for routes

Advanced Routing Patterns

- Parallel Routes

  - Show two or more pages in the same view that can be navigated independently

- Intercepting Routes

  - Intercept a route and show it in the context of another route

  - We can use these when keeping the context for the current page is important

Next Steps


Defining Routes

Creating Routes

- file-system based router 

Creating UI

Next Steps


Pages and Layouts

Pages

- UI that is unique to a route

- Pages are Server Components by default but can be set to a Client Component

Layouts

- UI that is shared between multiple pages

- On navigation, layouts preserve state, remain interactive, and do not re-render

- Passing data between a parent layout and its children is not possible

- Layouts do not have access to the current route segments

 

- Root Layout (Required)

  - Root layouts must contain html and body tags

  - Root layout is a Server Component by default and cannot be set to a Client Component

- Nesting Layouts

Templates

  - Templates create a new instance for each of their children on navigation

  - DOM elements are recreated, state is not preserved, and effects are re-synchronized

Modifying <head>

  - We can modify the <head> HTML elements such as title and meta


Linking and Navigating

<Link> Component

- Examples

  - Linking to Dynamic Segments: template literals and interpolation

  - Checking Active Links: usePathname() to determine if a link is active

  - Scrolling to an id: # append

  - Disabling scroll restoration: scroll: false

useRouter() hook

- This hook can only be used inside Client Components

How Routing and Navigation Works

1. Prefetching

  - <Link>

    - Static Routes

    - Dynamic Routes
  - router.prefetch()

  - Prefetching is not enabled in development, only in production

2. Caching

  - Next.js has an in-memory client-side cache called Router Cache

3. Partial Rendering

  - Only the route segments that change on navigation re-render on the client,
     and any shared segements are preserved

4. Soft Navigation

  - React only renders the segments that have changed
     while preserving React and browser state, and there is no full page reload

5. Back and Forward Navigation

  - Next.js will maintain the scroll position for backwards and forwards navigation by default.


Route Groups

Convention

- (folderName)

Examples

- Organize routes without affecting the URL path

  - Create a group to keep related routes together

  - We can create a different layout for each group by adding a layout

- Opting specific segments into a layout

- Creating multiple root layouts

  - Remove the top-level layout, and add a layout file inside each route groups

  - Navigating across multiple root layouts will cause a full page load


Dynamic Routes

Convention

- [folderName]

Example

Generating Static Params

- Dynamic route segments to statically generate routes at build time instead of on-demand at request time

- the requests are automatically memoized

Catch-all Segments

- [...folderName]

Optional Catch-all Segments

- [[...folderName]]

- the route without the parameter is also matched

TypeScript

Next Steps


Loading UI and Streaming

Instant Loading States

  - Fallback UI that is shown immediately upon navigation

  - Automatically wrap the page.js file below in a <Suspense> boundary

Streaming with Suspense

- What is Streaming?

  - Streaming allows us to break down the page's HTML into smaller chunks

     and progressively send those chunks from the server to the client

- Example

SEO

Status Codes


Error Handling

  - Automatically wrap a route and its nest children in a React Error Boundary

  - Error Components must be Client Components

How error.js Works

  - When the fallback error component is active,
     the error boundary maintain their state and remain interactive

Recovering From Errors

  - reset() function to prompt the user to attempt to recover from the error

     -> re-render the Error boundary's contents

Nested Routes

  - Error bubble up to the nearest parent error boundary

Handling Errors in Layouts

  - To handle errors within a specific layout or template,
     place an error.js file in the layouts parent segment

  - To handle errors within the root layout or template, use global-error.js

Handing Errors in Root Layouts

  - global-error.js error boundary wraps the entire application
     and its fallback component replaces the root layout when active

  - global-error.js must define its own <htnl. and <body> tags

Handing Server Errors

  - During product, error message security precaution


Parallel Routes

  - Allow us to simultaneously or conditionally render one or more pages in the same layout

  - Allow us to define independent error and loading states as they're being streamed in independently

Convention

  - Parallel routes are created using named slots

  - @folder

Unmatched Routes

- default.js

  - Render as a fallback when Next.js cannot recover a slot's active state based on the current URL

- useSelectedLayoutSegment(s)

  - Both accpet a parallelRoutesKey

Examples

- Modals

  - Catch-all routes take precedence over default.js

- Conditional Routes


Intercepting Routes

  - Allow us to load a route from another part of our application within the current layout

Convention

  - (..): one level above

  - (...): root app directory

Examples

- Modals

  - Intercepting Routes can be used together with Paralle Routes to create modals


Route Handlers

Convention

- Supported HTTP Methods

  - GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS

- Extended NextRequest and NextResponse APIs

Behavior

- Caching

  - Cached by default when using the GET method with the Response object

- Opting out of caching

- Route Resolution

Examples

- Revalidating Cached Data

  - next.revalidate option

  - export const revalidate = 60

- Dynamic Functions

  - Cookies

  - Headers

- Redirects

- Dynamic Route Segments

- Streaming

- Request Body

- Request Body FormData

- CORS

- Edge and Node.js Runtimes

- Non-UI Responses

- Segment Config Options

API Reference


Middleware

  - Allow us to run code before a request is completed

  - Middleware runs before cached content and routes are matched

Convention

Example

Matching Paths

- Matcher

- Conditional Statements

NextResponse

Using Cookies

Setting Headers

Producing a Response

Advanced Middleware Flags

Version History


Project Organization and File Colocation

Safe colocation by default

  - Only the content returned by page.js or route.js is sent to the client

Project organization features

- Private Folders

  - _folderName

- Route Groups

  - (folderName)

- src Directory

- Module Path Aliases

Project organization strategies

- Store project files outside of app

- Store project files in top-level folders inside of app

- Split project files by feature or route


Internationalization

Terminology

  - Locale: An identifier for a set of language and formatting perferences

Routing Overview

Localization

  - Only run on the server

Static Generation

  - generateStaticParams

반응형

댓글