- 전체
- HTML
- Web Design (웹디자인)
- XE 응용 개발
- wordpress plugin dev
- Javascript & JavaScript Application
- MEAN Stack : full stack javascript
- angular js & ionic framework
- bootstrap
- WebGL, Three.js and Babylon.js
- restful api design
- mobile web
- node.js 응용
- Cloud Service 응용
- 웹 어셈블리 개발 [WASM, WebAssembly]
- 마이크로서비스, MSA (microservice architecture)
- WebGL / WebGPU
- next.js 개발
- micro frontend (마이크로프론트앤드)
- 전자상거래/쇼핑몰
- 서버 클라우드 (aws, azure, google)
next.js 개발 [Next.js 개발] Using Next.js Version 13 : Next.js 버전 13 사용
2024.03.07 12:54
Using Next.js Version 13

Introduction:
- What Next.js is?
- Using Next.js version 13.4
- Understanding Next.js file structure
- Working with Next.js built-in files
Pre-requisites:
- Knowledge of JavaScript
- Knowledge of React
- Little Knowledge of Next.js ‘s previous Version (Not required but nice to have)
Table of Contents
- What NextJS is
- Why Next.js
- Previous Versions of Next.js
- What’s new in Next.js v13 is about
- Using the new features of Next.js V13
Introduction to Next.js ( What Next.js is )
Next.js is a popular open-source framework for building modern, server-side rendered, and search-engine optimized React applications. It’s built on top of React but provides more out-of-the-block features such as Server side rendering (SSR), and static site generation (SSG) than ReactJS, and this makes it a great choice to build a web application. The Next.js Compiler is written in Rust using SWC (Speedy web Compiler), which allows Next.js to transform and minify your JavaScript code for production faster, and also under the hood uses Node.js run time engine to execute server-side code. This is why Next.js is usually called a Full-stack React framework.
Why Next.js?
Here are some of the reasons why Next.js is preferred over React.js
- Server-side rendering (SSR): In React, we can only pre-generate the HTML for the index page. This is because React is a client-side rendering library. This means that the HTML for all other pages is generated on the client after the JavaScript bundle has been downloaded and executed. Next.js is a framework that builds on React and adds support for SSR. This means that Next.js can pre-generate the HTML for all pages in a website, including subsequent pages. This can improve website performance, accessibility, and search engine optimization (SEO).
- Static site generation (SSG) is a technique for generating HTML pages at build time. This means that the HTML for each page is generated once, and then served to users on subsequent requests. This can improve website performance and SEO, as search engines can index the pre-generated HTML. These are pages that do not contain any dynamic content.
- Routing: Next.js has built-in support for file-based routing, a powerful routing system that uses the directory or file name to denote the URL to access the content of the page. This makes it easy to create and manage complex routing schemes without having to use external routing libraries.
- File-based routing is different from traditional routing systems in that it does not require the use of route handlers. Instead, Next.js automatically generates routes for each file in the
pages/directory for version 12 and in theapp/directory for the latest version. This means that you can simply create a new file in thepages/orapp/directory to create a new route. - Data Fetching: Unlike React.js which only offers client-side data fetching, with Next.js you can fetch data before the page is loaded using Server side rendering, pre-generate pages at build time using static site generation, and also client-side data fetching that React.js offers.
- Next.js provides a way to create API endpoints using the same syntax as Express.js. This allows you to handle server-side logic that is not accessible to the client, while still being able to create a user interface for your application.
Previous Versions of Next.js
We’ve had different versions of Next.js over, but here are some notes about the previous versions of NextJS
- File Structure: In the previous versions of Next.js, we had each of our routes in the Pages folder as shown below. This folder contains the name of each of our URL endpoints as a filename with extensions of
js,jsx,ts, ortsx.

- Presence of Routes File and Document file: Before the latest versions of NextJS, we had the leisure of using the
_app.jsfile to work as a router file, to share resources from parent to child components, and to make resources available on a global scope.

- The Filename Structure: The filename structure of Next.js is simple and straightforward. Each page or component file is named using the route that it corresponds to. For example, the file
pages/index.jscorresponds to the route/, while the filepages/contactcorresponds to the route/contact. The filename extension can be.js,.jsx,.ts, or.tsx.

- Fetching of Data: in this version of Next.js, when we want to do server-side fetching, we mostly use functions like
getStaticProps,getServerSideProps,getInitialProps, These functions run on the server side and the code block here is not available to the client on the client side.
What’s New:
Starting from NextJS version 13, we have a very pleasant and interesting way of writing our web application using the best features. this latest version provides us so many features, a few of which will be listed below:
- File Structure: In the previous version we had the pages folder to contain each of our routes, we don’t have that again, now we have the
src/appfolder which houses every of the routes.

- Filename Structure: in the previous versions we just name the file what we want our route handle should be or create a folder with the name being the name of the route handle then create an index file in the folder to create our components, not that anymore.

- Presence of a Layout to define a general-based layout and makes sure each component of the page focuses on the business logic.

- Presence of error file and not found file: This error file is rendered if there is an error during the build process of a requested file or if there is an error during server-side rendering or server-side fetching of the page the error will be rendered, and the not-found file is rendered is the requested page is not defined in the route or can’t be found.

- Presence of loading file: This file is rendered while the building of the requested page is going on.

Getting Started With Version 13:
To install Nextjs version 13 make sure you have node installed. To install Nodejs Go tohttps://nodejs.org/en. After installing Node, then follow the following installation processes. There are two ways, using the NextJs Template (Recommended) or creating from scratch.
1. Creating from Scratch
To create Nextjs version 13 from scratch, you need to run the following commands in your preferred directory:
npm init -y
npm install react react-dom next@latest

After running these commands, open the directory in any code editor of yours and create a src folder, in the src folder, create app directory. which looks like this below.
After creating the folder in the above form, in the app folder create a layout.js file, a page.js file and a contact directory. Enter the following content into the layout.js file
Enter the below into the layout.js file
"use client";
// this content goes into the layout.js file
//this file can be used to set a common Navigation header
const Layout = ({ children }) => {
return (
<html>
<head></head>
<body>
<main>{children}</main>
</body>
</html>
);
};
export default Layout;
The below code into the page.js
"use client";
const HomePage = async (props) => {
return <> Homepage Component</>;
};
export default HomePage;
After doing all these, in your package.json file add a new script to the script blog which should look like this
"scripts": {
"dev": "next dev"
},
After creating a new entry into the script block in the package.json file, so we need to start our server, go to the terminal, navigate to your current directory, and run npm run dev so we should have something that looks like this when we run localhost:3000 on our preferred browser.

in your contact/ directory create a new page.js file, and add the following content to the page.js file in contact directory
const Contact = () => {
return <>Contact</>;
};
export default Contact;
Then go to your browser and navigate to localhost:3000/contact you should have something that looks like below

with these, we can see how the file-based routing of the latest version of Next.js works. Here is an image showing the file structure we just put together.

Using the Latest Features of NextJS
- Using Layout File: this file can be used to set a common navigation header. This is the place to define providers for React-Redux or React Context because it cuts across every page of the application. The Layout file can be used as below to define a common navigation or header. Add the following code to your
layout.jsfile,
"use client";
//this file can be used to set a common Navigation header
const Layout = ({ children }) => {
return (
<html>
<head></head>
<body
style={{
backgroundColor: "blue",
height: "100vh",
}}
>
<main>{children}</main>
</body>
</html>
);
};
export default Layout;
From the above, we can see we set the header for the application and this header will be visible as long as there’s no other sub-directory definedlayout.js file. For example, if we create a layout.js file in the contact directory and add the following code content below, if we start our development server by running npm run dev on the homepage, we should have a background color red with our content in it as shown below.

When we go to the contact page, we should see a page that looks different from the rest. This is because the original file in the directory has been replaced by a newly created one in the same directory. The resulting page should look something like this:

from the above we can see that there’s a level of precedence when defining the layout.js file, the one closest to the current route file will be loaded instead of a root one and with this implementation, we can define different headers for our application
2. Server-Side Fetching: You can fetch data from the server on any file located in the app folder, which will be displayed as a page in the browser. By default, these pages are server-based components and do not allow the use of react-based APIs without the need to specify at the top of the file that it is a client file. However, when working with client-based APIs, server-side fetching cannot be done. For example, let’s try to fetch data from this URL in our page.js file and try to set the fetched value into state using the react useState hook https://jsonplaceholder.typicode.com/users/1.
// this is the homepage: url/
// By default each of the pages of our application url file/folder are always server based component
// So it is easier to fetch data here from an api,
"use client";
import { useEffect, useState } from "react";
const fetchData = async () => {
const url = "https://jsonplaceholder.typicode.com/users/1";
const response_val = await fetch(url);
let fetch_result = await response_val.json();
return fetch_result;
};
const HomePage = async (props) => {
const [val, setVal] = useState({});
let result = await fetchData();
useEffect(() => {
if (result) {
setVal(val);
}
}, []);
console.log(val);
return <> Homepage Component</>;
};
export default HomePage;
If we start our development server, we will see we’re getting an error that looks something similar to this below async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding 'use client' to a module that was originally written for the server. It's clear from the error that page.js is primarily designed as a server-based component. However, we attempted to use it as a client-based project by adding the 'use client' tag and then tried to perform server-side fetching, which led to the error. The solution here is to split the page.js file into separate server and client-based components. This involves creating a client-based component and conditionally adding it to the page.js file, as demonstrated below. create a component/ directory in the src folder and add a new file called Homepage.jsand add the following content
"use client";
import { useEffect } from "react";
const HomeComponent = ({ email }) => {
useEffect(() => {
console.log("Testing " + email);
});
return <h2>{email}</h2>;
};
export default HomeComponent;
Then we can refactor our page.js file as this below
// this is the homepage: url/
import HomeComponent from "../component/home";
// By default each of the pages of our application url file/folder are always server based component
// So it is easier to fetch data here from an api,
const fetchData = async () => {
const url = "https://jsonplaceholder.typicode.com/users/1";
const response_val = await fetch(url);
let fetch_result = await response_val.json();
return fetch_result;
};
const HomePage = async () => {
let result = await fetchData();
return (
<>
{result ? (
<HomeComponent {...result} />
) : (
<h2>Something went wrong please try again later</h2>
)}
</>
);
};
export default HomePage;
The HomeComponent is imported from the page.js file and utilized as a React client component. The fetched data result is passed as props, as demonstrated. This approach enables us to retrieve data and serve client-side components simultaneously.
3. Using the error.JS file: To send customized error messages when there is a failure in generating the requested page or server-side fetching, we use the error.js file. To use this file, we create an error.js file in our directory, and its contents should appear as follows:
"use client";
const ErrorComponent = ({ error, reset }) => {
<div>
<h2>An Error occurred</h2>
{error.message && <h3>Reason: {error.message ? error.message : ""}</h3>}
<button onClick={() => reset()}>Reload Page</button>
</div>;
};
export default ErrorComponent;
The error.js file should be a client-based component, so we need to add our use client flag, From the above, we can see that we restructured the properties and extracted the error data and a reset method. The reset method helps us retry the process that led to the error.
4. Using the Loading file: As a client-based component, there is no need to add a flag at the top by default. The loading.js file should be placed in the app/ directory and is utilized to communicate with the client while the requested page is being fetched. It is important to note that this file cannot perform any server-side actions. Below is an example of what a loading file should look like.
export default () => {
return (
<div>
<div>Loading...</div>
</div>
);
};
5. Using the Not-found file: this is also a client-based component and this is used to send a custom 404 or not-found error page to the client. The not-found.js file is the replacement of the 404.js page from Next.js Version 12. The not-found.js file can contain anything client. A simple not-found.js page looks like this below:
import React from "react";
const NotFound = () => {
return <>Page not found</>;
};
export default NotFound;
6. Using the API directory: Within this directory, we must define all of our API endpoints alongside their respective business logic. It is important to note that we utilize a Node.js runtime environment, as previously discussed. To properly create an API endpoint within Next.js, we must adhere to the same folder structure convention as the client, but with a different file name. It is crucial to remember that for the API, we must utilize a route.js file instead of the page.js file that we've been using. To define an API route file for a specific path, follow this convention. Create a api folder within the app folder and then create a route.js file. Add the following code base.
import { NextResponse } from "next/server";
export async function GET(request) {
return NextResponse.json({ msg: "Testing Api" });
}
Looking at the above code, we can observe that it exports a function named GET which indicates the type of request being made and takes in a parameter that contains data about the request coming in. Similarly, we can define other request types such as POST, PUT, and DELETE. To create a response, we use the Next.js class NextResponse and call its static method json to convert our response to JSON, just like it's done using Node.js.
Other features of the latest version of Next.js include the use of template.js file, the introduction of next/navigation, next/legacy/image, etc. which will be talked about in coming articles.
Conclusion:
sub-topics covered in this article:
- Introduction to NEXTJS
- Why NextJS
- Previous Versions
- What’s new:
- Getting Started With Version 13
- Using the Latest Features of NextJS
About the Author
- Ademola Ade-akanfe is an experienced full-stack software engineer, with more than 3 years of experience in designing and developing both Web and mobile application
- LinkedIn: https://linkedin/in/ademola-ade-akanfe
- twitter: @dev demola
- portfolio: https://portfolio-vcpf.vercel.app
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! ????
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.
experienced full-stack software engineer, with over 3 years of experience in developing and designing responsive web applications and mobile application.
[출처] https://blog.stackademic.com/using-next-js-version-13-c9a74f204559
Next.js 버전 13 사용

소개:
- Next.js가 무엇인가요?
- Next.js 버전 13.4 사용
- Next.js 파일 구조 이해
- Next.js 내장 파일 작업
전제 조건:
- JavaScript에 대한 지식
- 반응에 대한 지식
- Next.js의 이전 버전에 대한 지식이 거의 없음(필수는 아니지만 있으면 좋음)
목차
- NextJS란 무엇인가
- 왜 Next.js인가?
- Next.js의 이전 버전
- Next.js v13의 새로운 기능은 다음과 같습니다.
- Next.js V13의 새로운 기능 사용하기
Next.js 소개(Next.js란 무엇인가)
Next.js는 현대적인 서버 측 렌더링 및 검색 엔진 최적화 React 애플리케이션을 구축하기 위한 인기 있는 오픈 소스 프레임워크입니다. React를 기반으로 구축되었지만 ReactJS보다 서버 측 렌더링(SSR) 및 정적 사이트 생성(SSG)과 같은 더 많은 기능을 제공하므로 웹 애플리케이션을 구축하는 데 탁월한 선택입니다. Next.js 컴파일러는 SWC(Speedy web Compiler)를 사용하여 Rust로 작성되었습니다 . 이를 통해 Next.js는 생산을 위해 JavaScript 코드를 더 빠르게 변환하고 축소할 수 있으며, 내부적으로는 Node.js 런타임 엔진을 사용하여 서버 측을 실행합니다. 암호. 이것이 Next.js를 일반적으로 Full-Stack React 프레임워크 라고 부르는 이유입니다 .
왜 Next.js인가?
React.js보다 Next.js가 선호되는 몇 가지 이유는 다음과 같습니다.
- 서버 측 렌더링(SSR) : React에서는 인덱스 페이지에 대한 HTML만 미리 생성할 수 있습니다. 이는 React가 클라이언트 측 렌더링 라이브러리이기 때문입니다. 이는 JavaScript 번들을 다운로드하고 실행한 후 클라이언트에서 다른 모든 페이지에 대한 HTML이 생성된다는 것을 의미합니다. Next.js 는 React를 기반으로 구축되고 SSR에 대한 지원을 추가하는 프레임워크입니다. 이는 Next.js가 후속 페이지를 포함하여 웹사이트의 모든 페이지에 대한 HTML을 미리 생성할 수 있음을 의미합니다. 이를 통해 웹사이트 성능, 접근성, 검색 엔진 최적화(SEO)를 향상할 수 있습니다.
- SSG(정적 사이트 생성)는 빌드 시 HTML 페이지를 생성하는 기술입니다. 즉, 각 페이지의 HTML이 한 번 생성된 다음 후속 요청 시 사용자에게 제공됩니다. 검색 엔진이 미리 생성된 HTML을 색인화할 수 있으므로 웹사이트 성능과 SEO가 향상될 수 있습니다. 동적 콘텐츠가 포함되지 않은 페이지입니다.
- 라우팅: Next.js 에는 페이지 콘텐츠에 액세스하기 위한 URL을 표시하기 위해 디렉터리나 파일 이름을 사용하는 강력한 라우팅 시스템인 파일 기반 라우팅이 내장되어 있습니다 . 이를 통해 외부 라우팅 라이브러리를 사용하지 않고도 복잡한 라우팅 구성표를 쉽게 만들고 관리할 수 있습니다.
- 파일 기반 라우팅은 경로 처리기를 사용할 필요가 없다는 점에서 기존 라우팅 시스템과 다릅니다. 대신 Next.js는
pages/버전 12의 디렉터리와app/최신 버전의 디렉터리에 있는 각 파일에 대한 경로를 자동으로 생성합니다.pages/즉, 또는app/디렉터리에 새 파일을 만들어 새 경로를 만들 수 있다는 뜻입니다 . - 데이터 가져오기: 클라이언트 측 데이터 가져오기만 제공하는 React.js와 달리 Next.js를 사용하면 서버 측 렌더링을 사용하여 페이지가 로드되기 전에 데이터를 가져올 수 있고, 정적 사이트 생성을 사용하여 빌드 시 페이지를 미리 생성할 수 있으며, 클라이언트 측 데이터 가져오기도 가능합니다. React.js가 제공하는 부가 데이터 가져오기.
- Next.js는 Express.js와 동일한 구문을 사용하여 API 엔드포인트를 생성하는 방법을 제공합니다. 이를 통해 클라이언트가 액세스할 수 없는 서버측 로직을 처리하는 동시에 애플리케이션에 대한 사용자 인터페이스를 생성할 수 있습니다.
Next.js의 이전 버전
다양한 버전의 Next.js가 있었지만 다음은 이전 버전의 NextJS에 대한 몇 가지 참고 사항입니다.
- 파일 구조: 이전 버전의 Next.js에서는 아래와 같이 Pages 폴더에 각 경로가 있었습니다.
js이 폴더에는 확장자가 ,jsx,ts또는 인 파일 이름으로 각 URL 끝점의 이름이 포함되어 있습니다tsx.

- 경로 파일 및 문서 파일의 존재: NextJS 최신 버전 이전에는 파일을 사용하여
_app.js라우터 파일로 작동하고, 상위 구성 요소에서 하위 구성 요소로 리소스를 공유하고, 전역 범위에서 리소스를 사용할 수 있게 만드는 여유가 있었습니다.

- 파일 이름 구조: Next.js의 파일 이름 구조는 간단하고 간단합니다. 각 페이지 또는 구성 요소 파일의 이름은 해당 경로를 사용하여 지정됩니다. 예를 들어 파일은
pages/index.js경로에 해당/하고 파일은pages/contact경로에 해당합니다/contact. 파일 이름 확장자는.js,.jsx,.ts또는 일 수 있습니다..tsx.

- 데이터 가져오기: 이 버전의 Next.js에서는 서버 측 가져오기를 원할 때 주로
getStaticProps,getServerSideProps, 와 같은 기능을 사용합니다getInitialProps. 이러한 기능은 서버 측에서 실행되며 여기의 코드 블록은 클라이언트에서 사용할 수 없습니다. 고객 입장에서.
새로운 기능:
NextJS 버전 13부터 우리는 최고의 기능을 사용하여 웹 애플리케이션을 작성하는 매우 즐겁고 흥미로운 방법을 갖게 되었습니다. 이 최신 버전은 매우 많은 기능을 제공하며 그 중 몇 가지가 아래에 나열되어 있습니다.
- 파일 구조: 이전 버전에는 각 경로를 포함하는 페이지 폴더가 있었지만 다시는 그런 것이 없습니다. 이제
src/app모든 경로를 저장하는 폴더가 있습니다.

- 파일 이름 구조: 이전 버전에서는 경로 핸들이 원하는 파일 이름을 지정하거나 경로 핸들 이름으로 폴더를 만든 다음 폴더에 인덱스 파일을 만들어 구성 요소를 생성합니다. 더 이상 그렇지 않습니다. .

- 일반 기반 레이아웃을 정의하고 페이지의 각 구성 요소가 비즈니스 로직에 초점을 맞추도록 하는 레이아웃이 있습니다.

- 오류 파일이 있지만 파일을 찾을 수 없음: 요청된 파일의 빌드 프로세스 중에 오류가 있거나 서버 측 렌더링 또는 서버 측 페이지 가져오기 중에 오류가 있는 경우 이 오류 파일이 렌더링됩니다. 렌더링되고 찾을 수 없는 파일이 렌더링되는 경우 요청한 페이지가 경로에 정의되어 있지 않거나 찾을 수 없습니다.

- 로딩 파일 존재: 이 파일은 요청된 페이지의 빌드가 진행되는 동안 렌더링됩니다.

버전 13 시작하기:
Nextjs 버전 13을 설치하려면 노드가 설치되어 있는지 확인하세요. Nodejs를 설치하려면 https://nodejs.org/en 으로 이동하세요 . Node를 설치한 후 다음 설치 과정을 따르세요. NextJs 템플릿(권장)을 사용하거나 처음부터 새로 만드는 두 가지 방법이 있습니다.
1. 처음부터 새로 만들기
Nextjs 버전 13을 처음부터 생성하려면 원하는 디렉터리에서 다음 명령을 실행해야 합니다.
npm init -y
npm install react react-dom next@latest

이 명령을 실행한 후 코드 편집기에서 디렉터리를 열고 폴더를 만듭니다 src. src 폴더에 app디렉터리를 만듭니다. 아래는 이렇게 생겼습니다.
위 형태로 폴더를 생성한 후, 앱 폴더에 layout.js파일, page.js파일, 연락처 디렉토리를 생성합니다. layout.js파일 에 다음 내용을 입력하세요.
레이아웃.js 파일에 아래 내용을 입력하세요.
"클라이언트 사용" ;
// 이 콘텐츠는 레이아웃.js 파일에 들어갑니다.
//이 파일은 공통 탐색 헤더를 설정하는 데 사용할 수 있습니다.
const Layout = ( { children } ) => {
return (
<html>
<head></head>
<body>
<main>{어린이}</main>
</body>
</html>
);
}; 기본 레이아웃
내보내기 ;
아래 코드를page.js
"클라이언트 사용" ;
const HomePage = async ( props ) => {
return <> 홈페이지 구성 요소</>;
}; 기본 홈페이지
내보내기 ;
이 모든 작업을 수행한 후 package.json파일에서 다음과 같은 새 스크립트를 스크립트 블로그에 추가하세요.
"스크립트" : {
"개발자" : "다음 개발자"
} ,
파일의 스크립트 블록에 새 항목을 만든 후 package.json서버를 시작하고 터미널로 이동하여 현재 디렉터리로 이동하고 실행 npm run dev해야 합니다. 그러면 localhost:3000을 실행할 때 다음과 같은 결과가 표시됩니다. 우리가 선호하는 브라우저.

디렉터리 에 contact/새 파일을 만들고 디렉터리 의 파일 page.js에 다음 내용을 추가합니다.page.jscontact
const 연락처 = ( ) => {
return <>연락처</>;
}; 기본 연락처
내보내기 ;
그런 다음 브라우저로 이동하여 localhost:3000/contact다음과 같은 내용이 표시되어야 합니다.

이를 통해 최신 버전의 Next.js의 파일 기반 라우팅이 어떻게 작동하는지 확인할 수 있습니다. 다음은 방금 구성한 파일 구조를 보여주는 이미지입니다.

NextJS의 최신 기능 사용
- 레이아웃 파일 사용: 이 파일은 공통 탐색 헤더를 설정하는 데 사용할 수 있습니다. 이는 애플리케이션의 모든 페이지에 걸쳐 있기 때문에 React-Redux 또는 React Context에 대한 공급자를 정의하는 곳입니다. 레이아웃 파일은 아래와 같이 공통 탐색 또는 헤더를 정의하는 데 사용될 수 있습니다. 파일 에 다음 코드를 추가하세요
layout.js.
"클라이언트 사용" ;
//이 파일은 공통 탐색 헤더를 설정하는 데 사용할 수 있습니다.
const Layout = ( { children } ) => {
return (
<html>
<head></head>
<body
style={{
backgroundColor: "blue",
height: "100vh",
}}
>
<main>{children}</main>
</body>
</html>
);
}; 기본 레이아웃
내보내기 ;
위에서 우리는 애플리케이션에 대한 헤더를 설정한 것을 볼 수 있으며, 다른 하위 디렉터리에 정의된 layout.js파일이 없는 한 이 헤더가 표시됩니다. 예를 들어 연락처 디렉토리에 파일을 생성 layout.js하고 아래 코드 내용을 추가한다면, npm run dev홈페이지에서 실행하여 개발 서버를 시작하면 아래와 같이 내용이 포함된 배경색이 빨간색이어야 합니다.

연락처 페이지로 이동하면 나머지 페이지와 다르게 보이는 페이지가 표시됩니다. 이는 해당 디렉토리의 원본 파일이 동일한 디렉토리에 새로 생성된 파일로 대체되었기 때문입니다. 결과 페이지는 다음과 같아야 합니다.

위에서 우리는layout.js 파일을 정의할 때 우선 순위 수준이 있다는 것을 알 수 있습니다. 현재 경로 파일에 가장 가까운 파일이 루트 파일 대신 로드되고 이 구현을 통해 애플리케이션에 대해 다른 헤더를 정의할 수 있습니다.
2. 서버 측 가져오기: 서버에서 앱 폴더에 있는 모든 파일의 데이터를 가져올 수 있으며, 이는 브라우저에 페이지로 표시됩니다. 기본적으로 이러한 페이지는 서버 기반 구성 요소이며 파일 상단에 클라이언트 파일임을 지정할 필요 없이 반응 기반 API의 사용을 허용하지 않습니다. 그러나 클라이언트 기반 API로 작업할 때는 서버 측 가져오기를 수행할 수 없습니다. 예를 들어 파일의 이 URL에서 데이터를 가져오고 반응 후크 https://jsonplaceholder.typicode.com/users/1page.js 을 사용하여 가져온 값을 상태로 설정해 보겠습니다 .useState
// 이것은 홈페이지입니다: url/
// 기본적으로 애플리케이션 URL 파일/폴더의 각 페이지는 항상 서버 기반 구성 요소입니다.
// 따라서 여기에서 API에서 데이터를 가져오는 것이 더 쉽습니다.
"클라이언트 사용" ;
import { useEffect, useState } from "react" ;
const fetchData = async ( ) => {
const url = "https://jsonplaceholder.typicode.com/users/1" ;
const response_val = 가져오기 (url) 대기 ; fetch_result = response_val을 기다리 세요 . JSON (); fetch_result를 반환합니다 . }; const HomePage = async ( props ) => { const [val, setVal] = useState ({}); 결과 = fetchData ()를 기다리 세요 ; useEffect ( () => { if (result) { setVal (val); } }, []); 콘솔 . 로그 (val); <> 홈페이지 구성요소</>를 반환합니다 . }; 기본 홈페이지 내보내기 ;
개발 서버를 시작하면 아래와 비슷한 오류가 표시되는 것을 볼 수 있습니다 async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding 'use client' to a module that was originally written for the server. page.js가 기본적으로 서버 기반 구성 요소로 설계되었다는 것은 오류에서 분명합니다. 하지만 태그를 추가하여 클라이언트 기반 프로젝트로 사용하려고 시도한 'use client'후 서버 측 페칭을 수행하려고 시도하여 오류가 발생했습니다. 여기서 해결 방법은 page.js파일을 별도의 서버 및 클라이언트 기반 구성 요소로 분할하는 것입니다. 여기에는 아래 설명된 대로 클라이언트 기반 구성 요소를 생성하고 이를 조건부로 page.js 파일에 추가하는 작업이 포함됩니다. component/src 폴더에 디렉토리를 생성 하고 라는 새 파일을 추가 Homepage.js하고 다음 내용을 추가하십시오.
"클라이언트 사용" ; "반응" 에서
가져오기 { useEffect } ; const HomeComponent = ( { 이메일 } ) => { useEffect ( () => { console . log ( "테스트 중" + 이메일); }); <h2>{이메일}</h2>을 반환합니다 . }; 기본 HomeComponent 내보내기 ;
page.js그런 다음 파일을 아래와 같이 리팩터링할 수 있습니다.
// 홈페이지입니다: url/
import HomeComponent from "../comComponent/home" ;
// 기본적으로 애플리케이션 URL 파일/폴더의 각 페이지는 항상 서버 기반 구성 요소입니다.
// 따라서 여기에서 API에서 데이터를 가져오는 것이 더 쉽습니다.
const fetchData = async ( ) => {
const url = "https:/ /jsonplaceholder.typicode.com/users/1" ;
const response_val = 가져오기 (url) 대기 ; fetch_result = response_val을 기다리 세요 . JSON (); fetch_result를 반환합니다 . }; const HomePage = async ( ) => { let result = fetchData ()를 기다립니다 ; return ( <> {result ? ( <HomeComponent {...result} /> ) : ( <h2>문제가 발생했습니다. 나중에 다시 시도해 주세요.</h2> )} </> ); }; 기본 홈페이지 내보내기 ;
HomeComponent는 page.js 파일에서 가져와 React 클라이언트 구성 요소로 활용됩니다. 가져온 데이터 결과는 표시된 대로 소품으로 전달됩니다. 이 접근 방식을 사용하면 데이터를 검색하고 클라이언트 측 구성 요소를 동시에 제공할 수 있습니다.
3. error.JS 파일 사용: 요청한 페이지 생성이나 서버 측 가져오기에 실패했을 때 사용자 정의된 오류 메시지를 보내기 위해 error.js 파일을 사용합니다. 이 파일을 사용하기 위해 디렉터리에 error.js 파일을 생성하고 해당 내용은 다음과 같이 표시되어야 합니다.
"클라이언트 사용" ;
const ErrorComponent = ( { 오류, 재설정 } ) => {
<div>
<h2>오류가 발생했습니다</h2>
{error.message && <h3>이유: {error.message ? error.message : ""}</h3>}
<button onClick={() => 재설정()}>페이지 새로고침</button>
</div>;
}; 기본 ErrorComponent
내보내기 ;
error.js 파일은 클라이언트 기반 컴포넌트여야 하므로 use client플래그를 추가해야 합니다. 위에서 보면 속성을 재구성하고 오류 데이터와 재설정 메서드를 추출한 것을 볼 수 있습니다. 재설정 방법을 사용하면 오류가 발생한 프로세스를 다시 시도할 수 있습니다.
4. 로딩 파일 사용: 클라이언트 기반 컴포넌트이므로 기본적으로 상단에 플래그를 추가할 필요가 없습니다. 파일 loading.js은 디렉토리에 있어야 하며 app/요청된 페이지를 가져오는 동안 클라이언트와 통신하는 데 사용됩니다. 이 파일은 서버 측 작업을 수행할 수 없다는 점에 유의하는 것이 중요합니다. 다음은 로딩 파일의 모양에 대한 예입니다.
내보내기 기본값 () => {
return (
<div>
<div>로드 중...</div>
</div>
);
};
5. 찾을 수 없는 파일 사용: 이 파일은 클라이언트 기반 구성 요소이기도 하며 사용자 정의 404 또는 찾을 수 없는 오류 페이지를 클라이언트에 보내는 데 사용됩니다. not-found.js 파일은 404.jsNext.js 버전 12의 페이지를 대체합니다 not-found.js. 파일에는 클라이언트가 포함될 수 있습니다. 간단한 not-found.js페이지는 아래와 같습니다.
"반응" 에서 반응을 가져옵니다 ; const NotFound = ( ) => { return <>페이지를 찾을 수 없음</>; }; 기본 NotFound 내보내기 ;
6. API 디렉터리 사용: 이 디렉터리 내에서 해당 비즈니스 로직과 함께 모든 API 엔드포인트를 정의해야 합니다. 이전에 설명한 대로 Node.js 런타임 환경을 활용한다는 점에 유의하는 것이 중요합니다. Next.js 내에서 API 엔드포인트를 올바르게 생성하려면 클라이언트와 동일한 폴더 구조 규칙을 준수해야 하지만 파일 이름은 달라야 합니다. API의 경우 기존에 사용했던 파일 route.js대신 파일을 활용해야 한다는 점을 기억하는 것이 중요합니다. page.js특정 경로에 대한 API 경로 파일을 정의하려면 다음 규칙을 따르세요. api앱 폴더 내에 폴더를 생성 한 후 route.js파일을 생성합니다. 다음 코드 베이스를 추가합니다.
import { NextResponse } from "next/server" ; 비동기 함수
내보내기 GET ( 요청 ) { NextResponse 반환 . json ({ msg : "API 테스트 중" }); }
위 코드를 보면, GET요청 유형을 나타내는 함수를 내보내고 들어오는 요청에 대한 데이터가 포함된 매개변수를 가져오는 것을 볼 수 있습니다. 마찬가지로 , 및 와 같은 다른 요청 유형을 정의할 수 POST있습니다 PUT. DELETE. 응답을 생성하려면 Node.js를 사용하는 것처럼 Next.js 클래스를 사용 NextResponse하고 해당 정적 메서드를 호출하여 응답을 JSON으로 변환합니다.json
Next.js 최신 버전의 다른 기능에는 template.js 파일 사용, 다음/탐색, 다음/레거시/이미지 도입 등이 포함됩니다. 이에 대해서는 다음 기사에서 설명하겠습니다.
결론:
이 기사에서 다루는 하위 주제:
- NEXTJS 소개
- 왜 NextJS인가?
- 이전 버전
- 새로운 기능:
- 버전 13 시작하기
- NextJS의 최신 기능 사용
저자 소개
- Ademola Ade-akanfe는 웹 및 모바일 애플리케이션 설계 및 개발 분야에서 3년 이상의 경험을 보유한 숙련된 풀 스택 소프트웨어 엔지니어입니다.
- 링크드인: https://linkedin/in/ademola-ade-akanfe
- 트위터: @dev 데모라
- 포트폴리오: https://portfolio-vcpf.vercel.app
스택아데믹
끝까지 읽어주셔서 감사합니다. 가기 전에:
- 박수를 치고 작가를 팔로우하는 것도 고려해 보세요 ! ????
- Twitter(X) , LinkedIn 및 YouTube 에서 우리를 팔로우하세요 .
- Stackademic.com을 방문하여 우리가 전 세계적으로 무료 프로그래밍 교육을 어떻게 민주화하고 있는지 자세히 알아보세요.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
댓글 0
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
|---|---|---|---|---|
| 2 |
[microfrontend][마이크로프론트엔드] 마이크로프론트엔드 아키텍쳐
| 졸리운_곰 | 2024.03.08 | 575 |
| 1 |
[microfrontend][마이크로프론트앤드] Building Micro Frontends With React : React로 마이크로 프론트엔드 구축
| 졸리운_곰 | 2024.03.08 | 537 |


